@vkontakte/calls-sdk 2.5.2-dev.92f2f89.0 → 2.5.2-dev.e4603f6.0

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.
Files changed (36) hide show
  1. package/CallsSDK.d.ts +10 -11
  2. package/abstract/BaseSignaling.d.ts +7 -7
  3. package/calls-sdk.cjs.js +8 -15
  4. package/calls-sdk.esm.js +8 -15
  5. package/classes/Conversation.d.ts +14 -14
  6. package/classes/DebugInfo.d.ts +2 -2
  7. package/classes/ParticipantIdRegistry.d.ts +0 -1
  8. package/classes/SpeakerDetector.d.ts +2 -2
  9. package/classes/SpecListener.d.ts +3 -3
  10. package/classes/codec/IDecoder.d.ts +2 -2
  11. package/classes/codec/LibVPxDecoder.d.ts +2 -2
  12. package/classes/codec/WebCodecsDecoder.d.ts +2 -2
  13. package/classes/screenshare/BaseStreamBuilder.d.ts +3 -3
  14. package/classes/screenshare/ScreenCaptureReceiver.d.ts +3 -11
  15. package/classes/screenshare/ScreenCaptureSender.d.ts +0 -2
  16. package/classes/screenshare/StreamBuilder.d.ts +2 -2
  17. package/classes/screenshare/WebmBuilder.d.ts +2 -2
  18. package/classes/transport/DirectTransport.d.ts +3 -2
  19. package/classes/transport/PerfStatReporter.d.ts +9 -1
  20. package/classes/transport/ServerTransport.d.ts +2 -4
  21. package/classes/transport/Statistics.d.ts +10 -3
  22. package/classes/transport/Transport.d.ts +5 -7
  23. package/default/Api.d.ts +1 -1
  24. package/default/Signaling.d.ts +7 -7
  25. package/package.json +1 -3
  26. package/static/External.d.ts +18 -18
  27. package/static/Params.d.ts +24 -32
  28. package/static/Utils.d.ts +12 -4
  29. package/types/ConversationParams.d.ts +1 -0
  30. package/types/ConversationResponse.d.ts +4 -0
  31. package/types/ExternalId.d.ts +17 -1
  32. package/types/Participant.d.ts +11 -3
  33. package/types/ParticipantLayout.d.ts +2 -6
  34. package/types/ParticipantPriority.d.ts +3 -3
  35. package/types/ParticipantStreamDescription.d.ts +2 -2
  36. package/types/SignalingMessage.d.ts +25 -17
package/calls-sdk.cjs.js CHANGED
@@ -1,19 +1,12 @@
1
1
  /**
2
- * @vkontakte/calls-sdk v2.5.2-dev.92f2f89.0
3
- * Fri, 28 Jan 2022 10:20:07 GMT
2
+ * @vkontakte/calls-sdk v2.5.2-dev.e4603f6.0
3
+ * Mon, 21 Feb 2022 12:08:31 GMT
4
4
  * https://st.mycdn.me/static/callssdk/2-5-2/doc/
5
5
  */
6
6
 
7
- var ca=Object.create;var Rt=Object.defineProperty;var da=Object.getOwnPropertyDescriptor;var pa=Object.getOwnPropertyNames,_r=Object.getOwnPropertySymbols,la=Object.getPrototypeOf,fr=Object.prototype.hasOwnProperty,ua=Object.prototype.propertyIsEnumerable;var Sr=Math.pow,vr=(n,e,t)=>e in n?Rt(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,Er=(n,e)=>{for(var t in e||(e={}))fr.call(e,t)&&vr(n,t,e[t]);if(_r)for(var t of _r(e))ua.call(e,t)&&vr(n,t,e[t]);return n};var Tr=n=>Rt(n,"__esModule",{value:!0});var hi=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),ha=(n,e)=>{Tr(n);for(var t in e)Rt(n,t,{get:e[t],enumerable:!0})},ma=(n,e,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of pa(e))!fr.call(n,i)&&i!=="default"&&Rt(n,i,{get:()=>e[i],enumerable:!(t=da(e,i))||t.enumerable});return n},Ie=n=>ma(Tr(Rt(n!=null?ca(la(n)):{},"default",n&&n.__esModule&&"default"in n?{get:()=>n.default,enumerable:!0}:{value:n,enumerable:!0})),n);var c=(n,e,t)=>new Promise((i,r)=>{var a=l=>{try{d(t.next(l))}catch(u){r(u)}},s=l=>{try{d(t.throw(l))}catch(u){r(u)}},d=l=>l.done?i(l.value):Promise.resolve(l.value).then(a,s);d((t=t.apply(n,e)).next())});var tn=hi(jt=>{"use strict";jt.byteLength=Ia;jt.toByteArray=Ra;jt.fromByteArray=Ma;var Fe=[],Ae=[],Ca=typeof Uint8Array!="undefined"?Uint8Array:Array,Ci="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Ze=0,Zr=Ci.length;Ze<Zr;++Ze)Fe[Ze]=Ci[Ze],Ae[Ci.charCodeAt(Ze)]=Ze;var Ze,Zr;Ae["-".charCodeAt(0)]=62;Ae["_".charCodeAt(0)]=63;function en(n){var e=n.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var t=n.indexOf("=");t===-1&&(t=e);var i=t===e?0:4-t%4;return[t,i]}function Ia(n){var e=en(n),t=e[0],i=e[1];return(t+i)*3/4-i}function ya(n,e,t){return(e+t)*3/4-t}function Ra(n){var e,t=en(n),i=t[0],r=t[1],a=new Ca(ya(n,i,r)),s=0,d=r>0?i-4:i,l;for(l=0;l<d;l+=4)e=Ae[n.charCodeAt(l)]<<18|Ae[n.charCodeAt(l+1)]<<12|Ae[n.charCodeAt(l+2)]<<6|Ae[n.charCodeAt(l+3)],a[s++]=e>>16&255,a[s++]=e>>8&255,a[s++]=e&255;return r===2&&(e=Ae[n.charCodeAt(l)]<<2|Ae[n.charCodeAt(l+1)]>>4,a[s++]=e&255),r===1&&(e=Ae[n.charCodeAt(l)]<<10|Ae[n.charCodeAt(l+1)]<<4|Ae[n.charCodeAt(l+2)]>>2,a[s++]=e>>8&255,a[s++]=e&255),a}function ba(n){return Fe[n>>18&63]+Fe[n>>12&63]+Fe[n>>6&63]+Fe[n&63]}function Pa(n,e,t){for(var i,r=[],a=e;a<t;a+=3)i=(n[a]<<16&16711680)+(n[a+1]<<8&65280)+(n[a+2]&255),r.push(ba(i));return r.join("")}function Ma(n){for(var e,t=n.length,i=t%3,r=[],a=16383,s=0,d=t-i;s<d;s+=a)r.push(Pa(n,s,s+a>d?d:s+a));return i===1?(e=n[t-1],r.push(Fe[e>>2]+Fe[e<<4&63]+"==")):i===2&&(e=(n[t-2]<<8)+n[t-1],r.push(Fe[e>>10]+Fe[e>>4&63]+Fe[e<<2&63]+"=")),r.join("")}});var rn=hi(Ii=>{Ii.read=function(n,e,t,i,r){var a,s,d=r*8-i-1,l=(1<<d)-1,u=l>>1,g=-7,f=t?r-1:0,W=t?-1:1,K=n[e+f];for(f+=W,a=K&(1<<-g)-1,K>>=-g,g+=d;g>0;a=a*256+n[e+f],f+=W,g-=8);for(s=a&(1<<-g)-1,a>>=-g,g+=i;g>0;s=s*256+n[e+f],f+=W,g-=8);if(a===0)a=1-u;else{if(a===l)return s?NaN:(K?-1:1)*(1/0);s=s+Math.pow(2,i),a=a-u}return(K?-1:1)*s*Math.pow(2,a-i)};Ii.write=function(n,e,t,i,r,a){var s,d,l,u=a*8-r-1,g=(1<<u)-1,f=g>>1,W=r===23?Math.pow(2,-24)-Math.pow(2,-77):0,K=i?0:a-1,k=i?1:-1,Y=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(d=isNaN(e)?1:0,s=g):(s=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-s))<1&&(s--,l*=2),s+f>=1?e+=W/l:e+=W*Math.pow(2,1-f),e*l>=2&&(s++,l/=2),s+f>=g?(d=0,s=g):s+f>=1?(d=(e*l-1)*Math.pow(2,r),s=s+f):(d=e*Math.pow(2,f-1)*Math.pow(2,r),s=0));r>=8;n[t+K]=d&255,K+=k,d/=256,r-=8);for(s=s<<r|d,u+=r;u>0;n[t+K]=s&255,K+=k,s/=256,u-=8);n[t+K-k]|=Y*128}});var wi=hi(gt=>{"use strict";var yi=tn(),mt=rn(),nn=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;gt.Buffer=h;gt.SlowBuffer=xa;gt.INSPECT_MAX_BYTES=50;var Kt=2147483647;gt.kMaxLength=Kt;h.TYPED_ARRAY_SUPPORT=Aa();!h.TYPED_ARRAY_SUPPORT&&typeof console!="undefined"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function Aa(){try{var n=new Uint8Array(1),e={foo:function(){return 42}};return Object.setPrototypeOf(e,Uint8Array.prototype),Object.setPrototypeOf(n,e),n.foo()===42}catch(t){return!1}}Object.defineProperty(h.prototype,"parent",{enumerable:!0,get:function(){if(!!h.isBuffer(this))return this.buffer}});Object.defineProperty(h.prototype,"offset",{enumerable:!0,get:function(){if(!!h.isBuffer(this))return this.byteOffset}});function Ke(n){if(n>Kt)throw new RangeError('The value "'+n+'" is invalid for option "size"');var e=new Uint8Array(n);return Object.setPrototypeOf(e,h.prototype),e}function h(n,e,t){if(typeof n=="number"){if(typeof e=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return Ri(n)}return an(n,e,t)}h.poolSize=8192;function an(n,e,t){if(typeof n=="string")return wa(n,e);if(ArrayBuffer.isView(n))return Oa(n);if(n==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof n);if(Ve(n,ArrayBuffer)||n&&Ve(n.buffer,ArrayBuffer)||typeof SharedArrayBuffer!="undefined"&&(Ve(n,SharedArrayBuffer)||n&&Ve(n.buffer,SharedArrayBuffer)))return Pi(n,e,t);if(typeof n=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');var i=n.valueOf&&n.valueOf();if(i!=null&&i!==n)return h.from(i,e,t);var r=ka(n);if(r)return r;if(typeof Symbol!="undefined"&&Symbol.toPrimitive!=null&&typeof n[Symbol.toPrimitive]=="function")return h.from(n[Symbol.toPrimitive]("string"),e,t);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof n)}h.from=function(n,e,t){return an(n,e,t)};Object.setPrototypeOf(h.prototype,Uint8Array.prototype);Object.setPrototypeOf(h,Uint8Array);function sn(n){if(typeof n!="number")throw new TypeError('"size" argument must be of type number');if(n<0)throw new RangeError('The value "'+n+'" is invalid for option "size"')}function Da(n,e,t){return sn(n),n<=0?Ke(n):e!==void 0?typeof t=="string"?Ke(n).fill(e,t):Ke(n).fill(e):Ke(n)}h.alloc=function(n,e,t){return Da(n,e,t)};function Ri(n){return sn(n),Ke(n<0?0:Mi(n)|0)}h.allocUnsafe=function(n){return Ri(n)};h.allocUnsafeSlow=function(n){return Ri(n)};function wa(n,e){if((typeof e!="string"||e==="")&&(e="utf8"),!h.isEncoding(e))throw new TypeError("Unknown encoding: "+e);var t=on(n,e)|0,i=Ke(t),r=i.write(n,e);return r!==t&&(i=i.slice(0,r)),i}function bi(n){for(var e=n.length<0?0:Mi(n.length)|0,t=Ke(e),i=0;i<e;i+=1)t[i]=n[i]&255;return t}function Oa(n){if(Ve(n,Uint8Array)){var e=new Uint8Array(n);return Pi(e.buffer,e.byteOffset,e.byteLength)}return bi(n)}function Pi(n,e,t){if(e<0||n.byteLength<e)throw new RangeError('"offset" is outside of buffer bounds');if(n.byteLength<e+(t||0))throw new RangeError('"length" is outside of buffer bounds');var i;return e===void 0&&t===void 0?i=new Uint8Array(n):t===void 0?i=new Uint8Array(n,e):i=new Uint8Array(n,e,t),Object.setPrototypeOf(i,h.prototype),i}function ka(n){if(h.isBuffer(n)){var e=Mi(n.length)|0,t=Ke(e);return t.length===0||n.copy(t,0,0,e),t}if(n.length!==void 0)return typeof n.length!="number"||Di(n.length)?Ke(0):bi(n);if(n.type==="Buffer"&&Array.isArray(n.data))return bi(n.data)}function Mi(n){if(n>=Kt)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Kt.toString(16)+" bytes");return n|0}function xa(n){return+n!=n&&(n=0),h.alloc(+n)}h.isBuffer=function(e){return e!=null&&e._isBuffer===!0&&e!==h.prototype};h.compare=function(e,t){if(Ve(e,Uint8Array)&&(e=h.from(e,e.offset,e.byteLength)),Ve(t,Uint8Array)&&(t=h.from(t,t.offset,t.byteLength)),!h.isBuffer(e)||!h.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;for(var i=e.length,r=t.length,a=0,s=Math.min(i,r);a<s;++a)if(e[a]!==t[a]){i=e[a],r=t[a];break}return i<r?-1:r<i?1:0};h.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}};h.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(e.length===0)return h.alloc(0);var i;if(t===void 0)for(t=0,i=0;i<e.length;++i)t+=e[i].length;var r=h.allocUnsafe(t),a=0;for(i=0;i<e.length;++i){var s=e[i];if(Ve(s,Uint8Array))a+s.length>r.length?h.from(s).copy(r,a):Uint8Array.prototype.set.call(r,s,a);else if(h.isBuffer(s))s.copy(r,a);else throw new TypeError('"list" argument must be an Array of Buffers');a+=s.length}return r};function on(n,e){if(h.isBuffer(n))return n.length;if(ArrayBuffer.isView(n)||Ve(n,ArrayBuffer))return n.byteLength;if(typeof n!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof n);var t=n.length,i=arguments.length>2&&arguments[2]===!0;if(!i&&t===0)return 0;for(var r=!1;;)switch(e){case"ascii":case"latin1":case"binary":return t;case"utf8":case"utf-8":return Ai(n).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return t*2;case"hex":return t>>>1;case"base64":return gn(n).length;default:if(r)return i?-1:Ai(n).length;e=(""+e).toLowerCase(),r=!0}}h.byteLength=on;function Na(n,e,t){var i=!1;if((e===void 0||e<0)&&(e=0),e>this.length||((t===void 0||t>this.length)&&(t=this.length),t<=0)||(t>>>=0,e>>>=0,t<=e))return"";for(n||(n="utf8");;)switch(n){case"hex":return Ka(this,e,t);case"utf8":case"utf-8":return pn(this,e,t);case"ascii":return Wa(this,e,t);case"latin1":case"binary":return ja(this,e,t);case"base64":return Ha(this,e,t);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return $a(this,e,t);default:if(i)throw new TypeError("Unknown encoding: "+n);n=(n+"").toLowerCase(),i=!0}}h.prototype._isBuffer=!0;function et(n,e,t){var i=n[e];n[e]=n[t],n[t]=i}h.prototype.swap16=function(){var e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)et(this,t,t+1);return this};h.prototype.swap32=function(){var e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)et(this,t,t+3),et(this,t+1,t+2);return this};h.prototype.swap64=function(){var e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)et(this,t,t+7),et(this,t+1,t+6),et(this,t+2,t+5),et(this,t+3,t+4);return this};h.prototype.toString=function(){var e=this.length;return e===0?"":arguments.length===0?pn(this,0,e):Na.apply(this,arguments)};h.prototype.toLocaleString=h.prototype.toString;h.prototype.equals=function(e){if(!h.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e?!0:h.compare(this,e)===0};h.prototype.inspect=function(){var e="",t=gt.INSPECT_MAX_BYTES;return e=this.toString("hex",0,t).replace(/(.{2})/g,"$1 ").trim(),this.length>t&&(e+=" ... "),"<Buffer "+e+">"};nn&&(h.prototype[nn]=h.prototype.inspect);h.prototype.compare=function(e,t,i,r,a){if(Ve(e,Uint8Array)&&(e=h.from(e,e.offset,e.byteLength)),!h.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(t===void 0&&(t=0),i===void 0&&(i=e?e.length:0),r===void 0&&(r=0),a===void 0&&(a=this.length),t<0||i>e.length||r<0||a>this.length)throw new RangeError("out of range index");if(r>=a&&t>=i)return 0;if(r>=a)return-1;if(t>=i)return 1;if(t>>>=0,i>>>=0,r>>>=0,a>>>=0,this===e)return 0;for(var s=a-r,d=i-t,l=Math.min(s,d),u=this.slice(r,a),g=e.slice(t,i),f=0;f<l;++f)if(u[f]!==g[f]){s=u[f],d=g[f];break}return s<d?-1:d<s?1:0};function cn(n,e,t,i,r){if(n.length===0)return-1;if(typeof t=="string"?(i=t,t=0):t>2147483647?t=2147483647:t<-2147483648&&(t=-2147483648),t=+t,Di(t)&&(t=r?0:n.length-1),t<0&&(t=n.length+t),t>=n.length){if(r)return-1;t=n.length-1}else if(t<0)if(r)t=0;else return-1;if(typeof e=="string"&&(e=h.from(e,i)),h.isBuffer(e))return e.length===0?-1:dn(n,e,t,i,r);if(typeof e=="number")return e=e&255,typeof Uint8Array.prototype.indexOf=="function"?r?Uint8Array.prototype.indexOf.call(n,e,t):Uint8Array.prototype.lastIndexOf.call(n,e,t):dn(n,[e],t,i,r);throw new TypeError("val must be string, number or Buffer")}function dn(n,e,t,i,r){var a=1,s=n.length,d=e.length;if(i!==void 0&&(i=String(i).toLowerCase(),i==="ucs2"||i==="ucs-2"||i==="utf16le"||i==="utf-16le")){if(n.length<2||e.length<2)return-1;a=2,s/=2,d/=2,t/=2}function l(K,k){return a===1?K[k]:K.readUInt16BE(k*a)}var u;if(r){var g=-1;for(u=t;u<s;u++)if(l(n,u)===l(e,g===-1?0:u-g)){if(g===-1&&(g=u),u-g+1===d)return g*a}else g!==-1&&(u-=u-g),g=-1}else for(t+d>s&&(t=s-d),u=t;u>=0;u--){for(var f=!0,W=0;W<d;W++)if(l(n,u+W)!==l(e,W)){f=!1;break}if(f)return u}return-1}h.prototype.includes=function(e,t,i){return this.indexOf(e,t,i)!==-1};h.prototype.indexOf=function(e,t,i){return cn(this,e,t,i,!0)};h.prototype.lastIndexOf=function(e,t,i){return cn(this,e,t,i,!1)};function La(n,e,t,i){t=Number(t)||0;var r=n.length-t;i?(i=Number(i),i>r&&(i=r)):i=r;var a=e.length;i>a/2&&(i=a/2);for(var s=0;s<i;++s){var d=parseInt(e.substr(s*2,2),16);if(Di(d))return s;n[t+s]=d}return s}function Ua(n,e,t,i){return $t(Ai(e,n.length-t),n,t,i)}function Ba(n,e,t,i){return $t(Ya(e),n,t,i)}function Fa(n,e,t,i){return $t(gn(e),n,t,i)}function Va(n,e,t,i){return $t(za(e,n.length-t),n,t,i)}h.prototype.write=function(e,t,i,r){if(t===void 0)r="utf8",i=this.length,t=0;else if(i===void 0&&typeof t=="string")r=t,i=this.length,t=0;else if(isFinite(t))t=t>>>0,isFinite(i)?(i=i>>>0,r===void 0&&(r="utf8")):(r=i,i=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var a=this.length-t;if((i===void 0||i>a)&&(i=a),e.length>0&&(i<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var s=!1;;)switch(r){case"hex":return La(this,e,t,i);case"utf8":case"utf-8":return Ua(this,e,t,i);case"ascii":case"latin1":case"binary":return Ba(this,e,t,i);case"base64":return Fa(this,e,t,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Va(this,e,t,i);default:if(s)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),s=!0}};h.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function Ha(n,e,t){return e===0&&t===n.length?yi.fromByteArray(n):yi.fromByteArray(n.slice(e,t))}function pn(n,e,t){t=Math.min(n.length,t);for(var i=[],r=e;r<t;){var a=n[r],s=null,d=a>239?4:a>223?3:a>191?2:1;if(r+d<=t){var l,u,g,f;switch(d){case 1:a<128&&(s=a);break;case 2:l=n[r+1],(l&192)==128&&(f=(a&31)<<6|l&63,f>127&&(s=f));break;case 3:l=n[r+1],u=n[r+2],(l&192)==128&&(u&192)==128&&(f=(a&15)<<12|(l&63)<<6|u&63,f>2047&&(f<55296||f>57343)&&(s=f));break;case 4:l=n[r+1],u=n[r+2],g=n[r+3],(l&192)==128&&(u&192)==128&&(g&192)==128&&(f=(a&15)<<18|(l&63)<<12|(u&63)<<6|g&63,f>65535&&f<1114112&&(s=f))}}s===null?(s=65533,d=1):s>65535&&(s-=65536,i.push(s>>>10&1023|55296),s=56320|s&1023),i.push(s),r+=d}return Ga(i)}var ln=4096;function Ga(n){var e=n.length;if(e<=ln)return String.fromCharCode.apply(String,n);for(var t="",i=0;i<e;)t+=String.fromCharCode.apply(String,n.slice(i,i+=ln));return t}function Wa(n,e,t){var i="";t=Math.min(n.length,t);for(var r=e;r<t;++r)i+=String.fromCharCode(n[r]&127);return i}function ja(n,e,t){var i="";t=Math.min(n.length,t);for(var r=e;r<t;++r)i+=String.fromCharCode(n[r]);return i}function Ka(n,e,t){var i=n.length;(!e||e<0)&&(e=0),(!t||t<0||t>i)&&(t=i);for(var r="",a=e;a<t;++a)r+=Qa[n[a]];return r}function $a(n,e,t){for(var i=n.slice(e,t),r="",a=0;a<i.length-1;a+=2)r+=String.fromCharCode(i[a]+i[a+1]*256);return r}h.prototype.slice=function(e,t){var i=this.length;e=~~e,t=t===void 0?i:~~t,e<0?(e+=i,e<0&&(e=0)):e>i&&(e=i),t<0?(t+=i,t<0&&(t=0)):t>i&&(t=i),t<e&&(t=e);var r=this.subarray(e,t);return Object.setPrototypeOf(r,h.prototype),r};function _e(n,e,t){if(n%1!=0||n<0)throw new RangeError("offset is not uint");if(n+e>t)throw new RangeError("Trying to access beyond buffer length")}h.prototype.readUintLE=h.prototype.readUIntLE=function(e,t,i){e=e>>>0,t=t>>>0,i||_e(e,t,this.length);for(var r=this[e],a=1,s=0;++s<t&&(a*=256);)r+=this[e+s]*a;return r};h.prototype.readUintBE=h.prototype.readUIntBE=function(e,t,i){e=e>>>0,t=t>>>0,i||_e(e,t,this.length);for(var r=this[e+--t],a=1;t>0&&(a*=256);)r+=this[e+--t]*a;return r};h.prototype.readUint8=h.prototype.readUInt8=function(e,t){return e=e>>>0,t||_e(e,1,this.length),this[e]};h.prototype.readUint16LE=h.prototype.readUInt16LE=function(e,t){return e=e>>>0,t||_e(e,2,this.length),this[e]|this[e+1]<<8};h.prototype.readUint16BE=h.prototype.readUInt16BE=function(e,t){return e=e>>>0,t||_e(e,2,this.length),this[e]<<8|this[e+1]};h.prototype.readUint32LE=h.prototype.readUInt32LE=function(e,t){return e=e>>>0,t||_e(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};h.prototype.readUint32BE=h.prototype.readUInt32BE=function(e,t){return e=e>>>0,t||_e(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};h.prototype.readIntLE=function(e,t,i){e=e>>>0,t=t>>>0,i||_e(e,t,this.length);for(var r=this[e],a=1,s=0;++s<t&&(a*=256);)r+=this[e+s]*a;return a*=128,r>=a&&(r-=Math.pow(2,8*t)),r};h.prototype.readIntBE=function(e,t,i){e=e>>>0,t=t>>>0,i||_e(e,t,this.length);for(var r=t,a=1,s=this[e+--r];r>0&&(a*=256);)s+=this[e+--r]*a;return a*=128,s>=a&&(s-=Math.pow(2,8*t)),s};h.prototype.readInt8=function(e,t){return e=e>>>0,t||_e(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]};h.prototype.readInt16LE=function(e,t){e=e>>>0,t||_e(e,2,this.length);var i=this[e]|this[e+1]<<8;return i&32768?i|4294901760:i};h.prototype.readInt16BE=function(e,t){e=e>>>0,t||_e(e,2,this.length);var i=this[e+1]|this[e]<<8;return i&32768?i|4294901760:i};h.prototype.readInt32LE=function(e,t){return e=e>>>0,t||_e(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};h.prototype.readInt32BE=function(e,t){return e=e>>>0,t||_e(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};h.prototype.readFloatLE=function(e,t){return e=e>>>0,t||_e(e,4,this.length),mt.read(this,e,!0,23,4)};h.prototype.readFloatBE=function(e,t){return e=e>>>0,t||_e(e,4,this.length),mt.read(this,e,!1,23,4)};h.prototype.readDoubleLE=function(e,t){return e=e>>>0,t||_e(e,8,this.length),mt.read(this,e,!0,52,8)};h.prototype.readDoubleBE=function(e,t){return e=e>>>0,t||_e(e,8,this.length),mt.read(this,e,!1,52,8)};function Ce(n,e,t,i,r,a){if(!h.isBuffer(n))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>r||e<a)throw new RangeError('"value" argument is out of bounds');if(t+i>n.length)throw new RangeError("Index out of range")}h.prototype.writeUintLE=h.prototype.writeUIntLE=function(e,t,i,r){if(e=+e,t=t>>>0,i=i>>>0,!r){var a=Math.pow(2,8*i)-1;Ce(this,e,t,i,a,0)}var s=1,d=0;for(this[t]=e&255;++d<i&&(s*=256);)this[t+d]=e/s&255;return t+i};h.prototype.writeUintBE=h.prototype.writeUIntBE=function(e,t,i,r){if(e=+e,t=t>>>0,i=i>>>0,!r){var a=Math.pow(2,8*i)-1;Ce(this,e,t,i,a,0)}var s=i-1,d=1;for(this[t+s]=e&255;--s>=0&&(d*=256);)this[t+s]=e/d&255;return t+i};h.prototype.writeUint8=h.prototype.writeUInt8=function(e,t,i){return e=+e,t=t>>>0,i||Ce(this,e,t,1,255,0),this[t]=e&255,t+1};h.prototype.writeUint16LE=h.prototype.writeUInt16LE=function(e,t,i){return e=+e,t=t>>>0,i||Ce(this,e,t,2,65535,0),this[t]=e&255,this[t+1]=e>>>8,t+2};h.prototype.writeUint16BE=h.prototype.writeUInt16BE=function(e,t,i){return e=+e,t=t>>>0,i||Ce(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=e&255,t+2};h.prototype.writeUint32LE=h.prototype.writeUInt32LE=function(e,t,i){return e=+e,t=t>>>0,i||Ce(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=e&255,t+4};h.prototype.writeUint32BE=h.prototype.writeUInt32BE=function(e,t,i){return e=+e,t=t>>>0,i||Ce(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4};h.prototype.writeIntLE=function(e,t,i,r){if(e=+e,t=t>>>0,!r){var a=Math.pow(2,8*i-1);Ce(this,e,t,i,a-1,-a)}var s=0,d=1,l=0;for(this[t]=e&255;++s<i&&(d*=256);)e<0&&l===0&&this[t+s-1]!==0&&(l=1),this[t+s]=(e/d>>0)-l&255;return t+i};h.prototype.writeIntBE=function(e,t,i,r){if(e=+e,t=t>>>0,!r){var a=Math.pow(2,8*i-1);Ce(this,e,t,i,a-1,-a)}var s=i-1,d=1,l=0;for(this[t+s]=e&255;--s>=0&&(d*=256);)e<0&&l===0&&this[t+s+1]!==0&&(l=1),this[t+s]=(e/d>>0)-l&255;return t+i};h.prototype.writeInt8=function(e,t,i){return e=+e,t=t>>>0,i||Ce(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=e&255,t+1};h.prototype.writeInt16LE=function(e,t,i){return e=+e,t=t>>>0,i||Ce(this,e,t,2,32767,-32768),this[t]=e&255,this[t+1]=e>>>8,t+2};h.prototype.writeInt16BE=function(e,t,i){return e=+e,t=t>>>0,i||Ce(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=e&255,t+2};h.prototype.writeInt32LE=function(e,t,i){return e=+e,t=t>>>0,i||Ce(this,e,t,4,2147483647,-2147483648),this[t]=e&255,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4};h.prototype.writeInt32BE=function(e,t,i){return e=+e,t=t>>>0,i||Ce(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4};function un(n,e,t,i,r,a){if(t+i>n.length)throw new RangeError("Index out of range");if(t<0)throw new RangeError("Index out of range")}function hn(n,e,t,i,r){return e=+e,t=t>>>0,r||un(n,e,t,4,34028234663852886e22,-34028234663852886e22),mt.write(n,e,t,i,23,4),t+4}h.prototype.writeFloatLE=function(e,t,i){return hn(this,e,t,!0,i)};h.prototype.writeFloatBE=function(e,t,i){return hn(this,e,t,!1,i)};function mn(n,e,t,i,r){return e=+e,t=t>>>0,r||un(n,e,t,8,17976931348623157e292,-17976931348623157e292),mt.write(n,e,t,i,52,8),t+8}h.prototype.writeDoubleLE=function(e,t,i){return mn(this,e,t,!0,i)};h.prototype.writeDoubleBE=function(e,t,i){return mn(this,e,t,!1,i)};h.prototype.copy=function(e,t,i,r){if(!h.isBuffer(e))throw new TypeError("argument should be a Buffer");if(i||(i=0),!r&&r!==0&&(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r<i&&(r=i),r===i||e.length===0||this.length===0)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(i<0||i>=this.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t<r-i&&(r=e.length-t+i);var a=r-i;return this===e&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(t,i,r):Uint8Array.prototype.set.call(e,this.subarray(i,r),t),a};h.prototype.fill=function(e,t,i,r){if(typeof e=="string"){if(typeof t=="string"?(r=t,t=0,i=this.length):typeof i=="string"&&(r=i,i=this.length),r!==void 0&&typeof r!="string")throw new TypeError("encoding must be a string");if(typeof r=="string"&&!h.isEncoding(r))throw new TypeError("Unknown encoding: "+r);if(e.length===1){var a=e.charCodeAt(0);(r==="utf8"&&a<128||r==="latin1")&&(e=a)}}else typeof e=="number"?e=e&255:typeof e=="boolean"&&(e=Number(e));if(t<0||this.length<t||this.length<i)throw new RangeError("Out of range index");if(i<=t)return this;t=t>>>0,i=i===void 0?this.length:i>>>0,e||(e=0);var s;if(typeof e=="number")for(s=t;s<i;++s)this[s]=e;else{var d=h.isBuffer(e)?e:h.from(e,r),l=d.length;if(l===0)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(s=0;s<i-t;++s)this[s+t]=d[s%l]}return this};var qa=/[^+/0-9A-Za-z-_]/g;function Ja(n){if(n=n.split("=")[0],n=n.trim().replace(qa,""),n.length<2)return"";for(;n.length%4!=0;)n=n+"=";return n}function Ai(n,e){e=e||1/0;for(var t,i=n.length,r=null,a=[],s=0;s<i;++s){if(t=n.charCodeAt(s),t>55295&&t<57344){if(!r){if(t>56319){(e-=3)>-1&&a.push(239,191,189);continue}else if(s+1===i){(e-=3)>-1&&a.push(239,191,189);continue}r=t;continue}if(t<56320){(e-=3)>-1&&a.push(239,191,189),r=t;continue}t=(r-55296<<10|t-56320)+65536}else r&&(e-=3)>-1&&a.push(239,191,189);if(r=null,t<128){if((e-=1)<0)break;a.push(t)}else if(t<2048){if((e-=2)<0)break;a.push(t>>6|192,t&63|128)}else if(t<65536){if((e-=3)<0)break;a.push(t>>12|224,t>>6&63|128,t&63|128)}else if(t<1114112){if((e-=4)<0)break;a.push(t>>18|240,t>>12&63|128,t>>6&63|128,t&63|128)}else throw new Error("Invalid code point")}return a}function Ya(n){for(var e=[],t=0;t<n.length;++t)e.push(n.charCodeAt(t)&255);return e}function za(n,e){for(var t,i,r,a=[],s=0;s<n.length&&!((e-=2)<0);++s)t=n.charCodeAt(s),i=t>>8,r=t%256,a.push(r),a.push(i);return a}function gn(n){return yi.toByteArray(Ja(n))}function $t(n,e,t,i){for(var r=0;r<i&&!(r+t>=e.length||r>=n.length);++r)e[r+t]=n[r];return r}function Ve(n,e){return n instanceof e||n!=null&&n.constructor!=null&&n.constructor.name!=null&&n.constructor.name===e.name}function Di(n){return n!==n}var Qa=function(){for(var n="0123456789abcdef",e=new Array(256),t=0;t<16;++t)for(var i=t*16,r=0;r<16;++r)e[i+r]=n[t]+n[r];return e}()});ha(exports,{Api:()=>Ft,BaseApi:()=>pt,BaseLogger:()=>lt,BaseSignaling:()=>ut,CallDirection:()=>We,CallType:()=>Le,ChatRoomEventType:()=>Ht,ConversationOption:()=>Gt,DebugMessageType:()=>ir,ExternalIdType:()=>at,FacingMode:()=>Ki,FatalError:()=>ne,HangupReason:()=>x,HangupType:()=>P,MediaOption:()=>le,MediaTrackKind:()=>me,MediaType:()=>Se,MuteState:()=>je,ParticipantState:()=>j,ParticipantStatus:()=>J,RecordRole:()=>Jn,Signaling:()=>xe,SignalingCommandType:()=>G,SignalingConnectionType:()=>Ue,SignalingNotification:()=>O,UserRole:()=>Ye,UserType:()=>X,Utils:()=>T,acceptCall:()=>Ys,addMovie:()=>Do,addParticipant:()=>eo,addParticipantInternal:()=>ea,apiCall:()=>qs,authorize:()=>Js,browser:()=>Vs,callInternal:()=>Qn,callTo:()=>js,captureScreen:()=>ro,changeConversationOptions:()=>_o,changeDevice:()=>io,changeParticipantState:()=>po,changePriorities:()=>co,changeVideoEffect:()=>Lo,chatHistory:()=>So,chatMessage:()=>fo,chatMessageInternal:()=>aa,createJoinLink:()=>To,customData:()=>vo,customDataInternal:()=>sa,debug:()=>xo,debugMessage:()=>No,declineCall:()=>zs,forceRelayPolicy:()=>Ro,getAnonymTokenByLink:()=>Io,getCurrentConversation:()=>Ho,getStreamInfo:()=>Ao,getTokenForAnonym:()=>$s,getWaitingHall:()=>Bo,grantRoles:()=>uo,grantRolesInternal:()=>ia,hangup:()=>Zs,init:()=>Ws,joinCall:()=>Qs,joinCallByLink:()=>Xs,joinCallInternal:()=>Zn,muteParticipant:()=>ho,muteParticipantInternal:()=>ra,pinParticipant:()=>mo,pinParticipantInternal:()=>na,processPush:()=>Ks,processPushInternal:()=>Xn,promoteParticipant:()=>Fo,recordSetRole:()=>Mo,removeHistoryRecords:()=>Vo,removeJoinLink:()=>Co,removeMovie:()=>Oo,removeParticipant:()=>to,removeParticipantInternal:()=>ta,setApi:()=>Yn,setAudioStream:()=>Uo,setLocalResolution:()=>oo,setLogger:()=>Hs,setMediaModifiers:()=>go,setSignalingFactory:()=>zn,setStatisticsInterval:()=>ko,setVideoEffects:()=>Gs,setVideoStream:()=>no,setVolume:()=>yo,startConversation:()=>Eo,startStream:()=>bo,stopStream:()=>Po,toggleLocalAudio:()=>so,toggleLocalVideo:()=>ao,updateDisplayLayout:()=>lo,updateMovie:()=>wo});var hr=Ie(require("webrtc-adapter"));var pt=class{createJoinLink(e){return c(this,null,function*(){return{join_link:"nop"}})}removeJoinLink(e){return c(this,null,function*(){return{success:!0}})}getAnonymTokenByLink(e,t){return c(this,null,function*(){return""})}log(e){}prepareUserIds(e){return c(this,null,function*(){})}getCachedOkIdByExternalId(e){return null}cacheExternalId(e,t){}hangupConversation(e){}removeHistoryRecords(e){return c(this,null,function*(){})}cleanup(){}getTokenForAnonym(e,t){return c(this,null,function*(){return""})}call(i){return c(this,arguments,function*(e,t={}){return null})}};var lt=class{log(e,t,i=!1){}destroy(){}};var Q=class{constructor(){this._handlers={};this._listeners=[]}_triggerEvent(e,...t){if(!!this._handlers.hasOwnProperty(e))for(let i of this._handlers[e])i.apply(this,t)}addEventListener(e,t){if(typeof t!="function")throw new Error("Listener should be a function");return this._handlers.hasOwnProperty(e)||(this._handlers[e]=[]),this._handlers[e].push(t),{dispose:this.removeEventListener.bind(this,e,t)}}removeEventListener(e,t){if(!this._handlers.hasOwnProperty(e))return;t||delete this._handlers[e];let i=this._handlers[e].indexOf(t);i>=0&&this._handlers[e].splice(i,1)}subscribe(e,t,i){let r=e.addEventListener(t,i);this._listeners.push(r)}unsubscribe(){this._listeners.forEach(e=>{e.dispose()})}};var ut=class extends Q{get ready(){return!0}setParticipantIdRegistry(e){}requestRealloc(){}setEndpoint(e){}setConversationId(e){}readyToSend(){}cleanup(){}requestTestMode(e){}getNextCommandSequenceNumber(){return 0}};var Cr=(i=>(i.INCOMING="INCOMING",i.OUTGOING="OUTGOING",i.JOINING="JOINING",i))(Cr||{}),We=Cr;var Ir=(i=>(i.USER="USER",i.GROUP="GROUP",i.CHAT="CHAT",i))(Ir||{}),Le=Ir;var yr=(t=>(t.ATTENDEE="ATTENDEE",t.HAND_UP="HAND_UP",t))(yr||{}),Ht=yr;var Rr=(t=>(t.ADD_PARTICIPANT="ADD_PARTICIPANT",t.RECORD="RECORD",t))(Rr||{}),br=Rr;var Pr=(i=>(i.REQUIRE_AUTH_TO_JOIN="REQUIRE_AUTH_TO_JOIN",i.AUDIENCE_MODE="AUDIENCE_MODE",i.WAITING_HALL="WAITING_HALL",i))(Pr||{}),Gt=Pr;function Mr(n,e){if(n.length!==e.length)return!1;for(let t of n)if(!e.includes(t))return!1;return!0}function Ar(n,e){let t=new Set(n);for(let[i,r]of Object.entries(e))r?t.add(i):t.delete(i);return Array.from(t)}var Dr=(k=>(k.CAMERA_PERMISSION="camera",k.MIC_PERMISSION="mic",k.CAMERA_ACCESS="cameralock",k.MIC_ACCESS="miclock",k.MIC_NOT_FOUND="nomic",k.SCREEN_PERMISSION="screenpermission",k.SCREEN_ACCESS="screenlock",k.CONNECTION="connection",k.NETWORK="network",k.UNKNOWN="unknown",k.UNSUPPORTED="unsupported",k.SIGNALING_FAILED="signalingfailed",k.API="api",k.AUTH="auth",k))(Dr||{}),ne=Dr;var wr=($=>($.CANCELED="CANCELED",$.REJECTED="REJECTED",$.REMOVED="REMOVED",$.HUNGUP="HUNGUP",$.MISSED="MISSED",$.BUSY="BUSY",$.FAILED="FAILED",$.NETWORK_ERROR="NETWORK_ERROR",$.KILLED="KILLED",$.BANNED="BANNED",$.CALLER_IS_BLOCKED="CALLER_IS_BLOCKED",$.NOT_FRIENDS="NOT_FRIENDS",$.CALLEE_IS_OFFLINE="CALLEE_IS_OFFLINE",$.UNKNOWN_ERROR="UNKNOWN_ERROR",$.UNSUPPORTED="UNSUPPORTED",$.OLD_VERSION="OLD_VERSION",$.SERVICE_DISABLED="SERVICE_DISABLED",$.EXTERNAL_API_ERROR="EXTERNAL_API_ERROR",$.SOCKET_CLOSED="SOCKET_CLOSED",$.ENDED="ENDED",$))(wr||{}),P=wr;var Or=(i=>(i.AUDIO="AUDIO",i.VIDEO="VIDEO",i.SCREEN_SHARING="SCREEN_SHARING",i))(Or||{}),le=Or;var kr=(i=>(i.UNMUTE="UNMUTE",i.MUTE="MUTE",i.MUTE_PERMANENT="MUTE_PERMANENT",i))(kr||{}),je=kr;var xr=(r=>(r.CALLED="CALLED",r.ACCEPTED="ACCEPTED",r.REJECTED="REJECTED",r.HUNGUP="HUNGUP",r))(xr||{}),j=xr;var Nr=(r=>(r.START="start",r.ACCEPT="accept",r.JOIN="join",r.RETRY="retry",r))(Nr||{}),Ue=Nr;var Lr=(i=>(i.NOTIFICATION="NOTIFICATION",i.FAILED="FAILED",i.RECONNECT="RECONNECT",i))(Lr||{}),fe=Lr;var Ur=(D=>(D.TRANSMITTED_DATA="transmitted-data",D.ACCEPTED_CALL="accepted-call",D.HUNGUP="hungup",D.PARTICIPANT_ADDED="participant-added",D.PARTICIPANT_JOINED="participant-joined",D.CLOSED_CONVERSATION="closed-conversation",D.MEDIA_SETTINGS_CHANGED="media-settings-changed",D.PARTICIPANT_STATE_CHANGED="participant-state-changed",D.RATE_CALL_DATA="rate-call-data",D.FEATURE_SET_CHANGED="feature-set-changed",D.TOPOLOGY_CHANGED="topology-changed",D.PRODUCER_UPDATED="producer-updated",D.CONSUMER_ANSWERED="consumer-answered",D.MULTIPARTY_CHAT_CREATED="multiparty-chat-created",D.FORCE_MEDIA_SETTINGS_CHANGE="force-media-settings-change",D.SETTINGS_UPDATE="settings-update",D.VIDEO_QUALITY_UPDATE="video-quality-update",D.REGISTERED_PEER="registered-peer",D.SWITCH_MICRO="switch-micro",D.RECORD_STARTED="record-started",D.RECORD_STOPPED="record-stopped",D.REALLOC_CON="realloc-con",D.AUDIO_ACTIVITY="audio-activity",D.SPEAKER_CHANGED="speaker-changed",D.STALLED_ACTIVITY="stalled-activity",D.CHAT_MESSAGE="chat-message",D.CUSTOM_DATA="custom-data",D.ROLES_CHANGED="roles-changed",D.MUTE_PARTICIPANT="mute-participant",D.PIN_PARTICIPANT="pin-participant",D.OPTIONS_CHANGED="options-changed",D.NETWORK_STATUS="network-status",D.PARTICIPANT_SOURCES_UPDATE="participant-sources-update",D.PROMOTE_PARTICIPANT="promote-participant",D.CHAT_ROOM_UPDATED="chat-room-updated",D.PROMOTION_APPROVED="promotion-approved",D.JOIN_LINK_CHANGED="join-link-changed",D))(Ur||{}),O=Ur;var Br=(b=>(b.ERROR="callError",b.DEVICES="callDevices",b.CALL_SPEC_ERROR="callSpecError",b.ICE_CONNECTION_STATE="callIceConnectionState",b.ICE_CONNECTION_TYPE="callIceConnectionType",b.ICE_RESTART="callIceRestart",b.PUSH="callPush",b.OUTGOING_CALL="callStart",b.OUTGOING_MULTIPARTY_CALL="callStartMultiparty",b.JOIN_CONVERSATION="callJoinConversation",b.ACCEPTED_OUTGOING="callAcceptedOutgoing",b.ACCEPT_INCOMING="callAcceptIncoming",b.DECLINE_INCOMING="callDeclineIncoming",b.ACCEPT_CONCURRENT="callAcceptConcurrent",b.HANGUP="callHangup",b.MEDIA_STATUS="callMediaStatus",b.DEVICE_CHANGED="callDeviceChanged",b.SOCKET_ACTION="callSocketAction",b.ADD_PARTICIPANT="callAddParticipant",b.REMOVE_PARTICIPANT="callRemoveParticipant",b.POOR_CONNECTION="callPoorConnection",b.TOPOLOGY_CHANGE_REQUESTED="callTopologyChangeRequested",b.RELAY_POLICY="callForceRelay",b.PAT_ALLOCATED="patAllocate",b.PAT_DEALLOCATED="patDeallocate",b.PAT_ERROR="patError",b.PAT_WAITING_TIME_ERROR="patWaitingTimeError",b.PAT_OUTDATED_RESPONSE="patOutdatedResponse",b))(Br||{}),_=Br;var Fr=(t=>(t.AUDIO_MIX="audio-mix",t.PARTICIPANT_AGNOSTIC_TRACK_PREFIX="pat",t))(Fr||{}),ke=Fr;var Vr=(t=>(t.NO_AVAILABLE_TRACKS="no-available-tracks",t.UNKNOWN_ERROR="unknown-error",t))(Vr||{}),Hr=Vr;function Gr(n){switch(n){case 1:return"no-available-tracks";default:return"unknown-error"}}var Wr=(t=>(t.CREATOR="CREATOR",t.ADMIN="ADMIN",t))(Wr||{}),Ye=Wr;function bt(n,e){if(n.length!==e.length)return!1;for(let t of n)if(!e.includes(t))return!1;return!0}var jr=(t=>(t.USER="USER",t.GROUP="GROUP",t))(jr||{}),X=jr;var mi=class{constructor(){this._items=[]}get length(){return this._items.length}push(e){this._items.push(e)}shift(){return this._items.shift()||null}bisect(){let e=this.length>1?Math.floor(this.length/2):1;this._items=this._items.slice(e)}clear(){this._items=[]}toString(){return this._items.length?JSON.stringify(this._items,(e,t)=>t instanceof Error?String(t):t):""}};var Kr=2*1024*1024,ga=512*1024,Pt=100*1024,_a=5,gi="_okcls_logs_session_",fa=3e4,$r=class{constructor(){this._items=[];this._itemsSize=0;this._storageSize=Kr;try{let e=window.localStorage;for(let t of Object.keys(e)){if(t.indexOf(gi)!==0)continue;let i=e.getItem(t);if(!i){Yr(t);continue}let r=Jr(i);this.add(t,r)}}catch(e){console.error("Storage is blocked",e),this._storageSize=0}this._items.sort((e,t)=>e.date-t.date),this.cleanup(Pt)}get size(){return this._itemsSize}get length(){return this._items.length}get available(){return Math.max(this._storageSize-this._itemsSize,0)}get items(){return this._items}set storageSize(e){this._storageSize=e}add(e,t){let i=parseInt(e.replace(gi,""),10);this._itemsSize+=t,this._items.push({key:e,size:t,date:i})}deleteOldestItem(){let e=this._items.shift();e&&(Yr(e.key),this._itemsSize-=e.size)}cleanup(e){for(;this.length&&(this.size>Kr||this.length>_a-1||this.size+e>this.available);)this.deleteOldestItem()}};function qr(){return`${gi}${Date.now()}`}function Jr(n){return new Blob([n]).size}function Yr(n){try{window.localStorage.removeItem(n)}catch(e){console.error("Failed to remove log from storage",e)}}function _i(){let n=ze.toString();if(!Te.available||!n)return;let e=Jr(n);Te.cleanup(e);try{window.localStorage.setItem(Wt,n)}catch(t){if(console.warn("Failed to write log to storage",t),Te.storageSize=Te.size+e,Te.cleanup(Pt+e),Te.available>=Pt+e){_i();return}if(e>Pt){ze.bisect(),_i();return}Te.storageSize=0;return}e>ga&&(Te.add(Wt,e),Wt=qr(),ze.clear(),Te.cleanup(Pt))}function fi(){!Te.available||!ze.length||_i()}function Sa(n=!1){let e=[];try{let r=window.localStorage;for(let s of Te.items){let d=r.getItem(s.key);e.push(d)}let a=ze.toString();a&&e.push(a)}catch(r){console.error("Storage is blocked",r)}let t=`[${e.join(",")}]`;if(n)return t;let i=`logs_${Date.now()}.json`;return va(t,i),i}function va(n,e){let t=document.createElement("a"),i=new Blob([n],{type:"text/json"});t.href=URL.createObjectURL(i),t.download=e,t.click()}function zr(n,e){!Te.available||(ze.push({t:Date.now(),l:n,d:e}),vi||(vi=window.setTimeout(()=>{vi=null,fi()},fa)))}function Si(){Te||(Te=new $r,ze=new mi,Wt=qr(),window.addEventListener("beforeunload",fi))}var Te,ze,Wt,vi=null;window.__VKCallsSDKLogs__=(n=!1)=>(Te||Si(),fi(),Sa(n));var Xi=Ie(require("file-saver"));var Se=(r=>(r.CAMERA="CAMERA",r.SCREEN="SCREEN",r.STREAM="STREAM",r.MOVIE="MOVIE",r))(Se||{}),Ei=":",Qr="s",Xr="m";function Qe(n){return n.participantId+(n.mediaType?Ei+Qr+n.mediaType:"")+(n.streamName?Ei+Xr+n.streamName:"")}function Mt(n){let e=n.split(Ei),t=e.shift();if(!t)throw new Error("Illegal stream description: "+n);let i={participantId:t,mediaType:null};for(let r of e)switch(r.charAt(0)){case Qr:i.mediaType=Ta(r.slice(1));break;case Xr:i.streamName=r.slice(1);break;default:throw new Error("Unexpected parameter type "+r.charAt(0)+" in stream description "+n)}return i}function Ta(n){for(let e of Object.keys(Se))if(e===n)return Se[e];return null}var Ti=Ie(require("@vkontakte/libvpx"));var ve=(s=>(s.INIT="init",s.READY="ready",s.FRAME="frame",s.ERROR="error",s.DEBUG="debug",s.LOG_ERROR="log_error",s))(ve||{});var m=class extends lt{constructor(e,t){super();this._batchInterval=3e3;this._batch=[];this._batchTimeout=null;this._api=e,this._externalLogger=t}_send(e){this._api.log(e)}_sendBatch(){this._stopTimeout(),this._batch.length>0&&(this._send(this._batch),this._batch=[],this._startTimeout())}_startTimeout(){this._batchTimeout=window.setTimeout(()=>this._sendBatch(),this._batchInterval)}_stopTimeout(){this._batchTimeout&&(clearTimeout(this._batchTimeout),this._batchTimeout=null)}_onUnload(){this._sendBatch(),this._stopTimeout()}log(e,t,i=!1){let r={};typeof t!="undefined"&&(r.param=t),this._logInternal(e,r,i),this._externalLogger&&this._externalLogger.log(e,t,i)}logCustom(e,t,i=!1){this._logInternal(e,t,i)}_logInternal(e,t,i){let r={type:1,time:0,operation:e,timestamp:Date.now(),custom:t,uid:this._api.getUserId()};this._batch.push(r),(i||!this._batchTimeout)&&this._sendBatch()}destroy(){this._sendBatch(),this._stopTimeout(),this._externalLogger&&this._externalLogger.destroy()}static create(e,t){m._instance||(m._instance=new m(e,t))}static log(e,t,i=!1){m._instance&&m._instance.log(e,t,i)}static logCustom(e,t,i=!1){m._instance&&m._instance.logCustom(e,t,i)}static destroy(){m._instance&&m._instance.destroy(),m._instance=null}};var Be=class{constructor(){this._worker=null}_createWorker(s,d){return c(this,arguments,function*(e,t,i=[],r={},a=[]){return new Promise((l,u)=>{let g=i.join(","),f=new Blob([e,`exports.default(${g});`],{type:"application/javascript; charset=utf-8"}),W=window.URL.createObjectURL(f);this._worker=new Worker(W),this._worker.onmessage=K=>{switch(K.data.type){case ve.READY:l();break;case ve.ERROR:u(K.data.error);break;case ve.FRAME:t(K.data);break;case ve.DEBUG:o.debug(K.data.message);break;case ve.LOG_ERROR:m.log(_.ERROR,K.data.message);break}},this._sendToWorker(ve.INIT,r,a)})})}_removeWorker(){var e;(e=this._worker)==null||e.terminate(),this._worker=null}_sendToWorker(e,t={},i=[]){var r;(r=this._worker)==null||r.postMessage(Object.assign({type:e},t),i)}static isBrowserSupported(){throw new Error("Not implemented")}};var ht=class extends Be{init(e){return c(this,null,function*(){o.debug("LibVPxDecoder started"),yield this._createWorker('var exports=(()=>{var b=Object.defineProperty;var M=a=>b(a,"__esModule",{value:!0});var V=(a,i)=>{M(a);for(var e in i)b(a,e,{get:i[e],enumerable:!0})};var h={};V(h,{default:()=>D});var t=(s=>(s.INIT="init",s.READY="ready",s.FRAME="frame",s.ERROR="error",s.DEBUG="debug",s.LOG_ERROR="log_error",s))(t||{});var D=(a,i)=>{let e=null,n=null,m=!0;function R(){return a({locateFile:i}).then(r=>n=r)}function s(r,y,l,d,x,E){if(!n){self.postMessage({type:t.LOG_ERROR,message:"decoder-init-fail-libvpx"}),self.postMessage({type:t.FRAME,error:"Fatal initialization error"});return}if(m!==l&&(m=l,e&&(e=null,self.postMessage({type:t.DEBUG,message:`LibVPxDecoder codec changed to ${l?"VP9":"VP8"} - reinitialize`}))),!e&&(self.postMessage({type:t.DEBUG,message:`LibVPxDecoder codec ${l?"VP9":"VP8"}`}),e=new n.VpxDecoder,e.debug(E),!e.init(l?n.VpxType.VP9:n.VpxType.VP8))){e=null,self.postMessage({type:t.FRAME,error:"Decoder failed to create"});return}try{e.allocateBuffer(y.byteLength).set(new Uint8Array(y))}catch(o){self.postMessage({type:t.DEBUG,message:o}),e=null,self.postMessage({type:t.FRAME,error:String(o)});return}if(!(e.decode()&&e.nextImage())){self.postMessage({type:t.FRAME,error:"Decode failed for "+d});return}let c=e.getImageBuffer();if(!c){self.postMessage({type:t.FRAME,error:"No decoded data"});return}let f=e.getImageWidth(),u=e.getImageHeight();e.nextImage()&&(self.postMessage({type:t.DEBUG,message:"LibVPxDecoder dropped frame"}),self.postMessage({type:t.LOG_ERROR,message:"LibVPxDecoder-drop"}));let p=new Uint8ClampedArray(c.byteLength);if(p.set(c),x){let o=new ImageData(p,f,u);createImageBitmap(o,0,0,f,u).then(g=>{self.postMessage({type:t.FRAME,crc:d,data:g},[g]),g.close()})}else self.postMessage({type:t.FRAME,data:p.buffer,crc:d,width:f,height:u},[p.buffer])}R().then(()=>{self.onmessage=r=>{switch(r.data.type){case t.FRAME:s(r.data.timestamp,r.data.data,r.data.isVP9,r.data.crc,r.data.useImageBitmap,r.data.debug);break}},self.postMessage({type:t.READY})}).catch(r=>{self.postMessage({type:t.ERROR,error:String(r)})})};return h;})();\n',t=>{if(t.error)o.warn("LibVPxDecoder",t.error);else if(t.data instanceof ArrayBuffer){let i=new ImageData(new Uint8ClampedArray(t.data),t.width,t.height);e(i,t.crc)}else e(t.data,t.crc)},[Ti.default,Ti.default.getUrl])})}decodeFrame(e,t,i,r,a){let s="ImageBitmap"in window;this._sendToWorker(ve.FRAME,{timestamp:e,data:t.buffer,isVP9:i,crc:r,keyFrame:a,useImageBitmap:s,debug:o.enabled()},[t.buffer])}destroy(){this._removeWorker(),o.debug("LibVPxDecoder destroyed")}static isBrowserSupported(){return"WebAssembly"in window&&"Worker"in window}};var Xe=class extends Be{init(e){return c(this,null,function*(){o.debug("WebCodecsDecoder started"),yield this._createWorker('var exports=(()=>{var l=Object.defineProperty;var g=e=>l(e,"__esModule",{value:!0});var V=(e,c)=>{g(e);for(var t in c)l(e,t,{get:c[t],enumerable:!0})};var R={};V(R,{default:()=>y});var n=(t=>(t.VP9="vp09.00.50.08",t.VP8="vp8",t))(n||{}),o=(r=>(r.INIT="init",r.READY="ready",r.FRAME="frame",r.ERROR="error",r.DEBUG="debug",r.LOG_ERROR="log_error",r))(o||{});var y=()=>{let e=null,c=!0,t=[];function p(){self.postMessage({type:o.READY})}function m(a,r,d,u,f=!1){t.push(u),(!e||c!==d)&&(c=d,e?self.postMessage({type:o.DEBUG,message:`WebCodecsDecoder codec changed to ${d?"VP9":"VP8"}`}):(self.postMessage({type:o.DEBUG,message:`WebCodecsDecoder codec ${d?"VP9":"VP8"}`}),e=new VideoDecoder({output:s=>{("createImageBitmap"in s?s.createImageBitmap():createImageBitmap(s)).then(i=>{self.postMessage({type:o.FRAME,crc:t&&t.length?t.pop():"",data:i}),i.close()}).finally(()=>s.close())},error:s=>{e&&e.state!=="closed"&&e.close(),e=null,self.postMessage({type:o.FRAME,error:"WebCodecsDecoder failed, reinitialize"})}})),e.configure({codec:d?n.VP9:n.VP8}));let E=new EncodedVideoChunk({type:f?"key":"delta",timestamp:a,data:r});e.decode(E)}self.onmessage=a=>{switch(a.data.type){case o.INIT:p();break;case o.FRAME:m(a.data.timestamp,a.data.data,a.data.isVP9,a.data.crc,a.data.keyFrame);break}}};return R;})();\n',t=>{t.error?o.warn("WebCod_createWorkerecsDecoder",t.error):e(t.data,t.crc)})})}decodeFrame(e,t,i,r,a=!1){this._sendToWorker(ve.FRAME,{timestamp:e,data:t.buffer,isVP9:i,crc:r,keyFrame:a},[t.buffer])}destroy(){this._removeWorker(),o.debug("WebCodecsDecoder destroyed")}static isBrowserSupported(){return"VideoDecoder"in window&&"Worker"in window&&"VideoFrame"in window&&"ImageBitmap"in window&&"createImageBitmap"in window}};var Yi=Ie(wi()),zi=Ie(require("crc"));var Oi="_okcls_",_t=(()=>{try{let n=Date.now().toString(),e=window.localStorage,t=!1;return e.setItem(n,n),t=e.getItem(n)===n,e.removeItem(n),t?e:null}catch(n){return null}})();function Xa(n){let e=_t?_t.getItem(Oi+n):null;if(e===null)return null;try{return JSON.parse(e)}catch(t){return null}}function Za(n,e){try{_t&&_t.setItem(Oi+n,JSON.stringify(e))}catch(t){}}function es(n){_t&&_t.removeItem(Oi+n)}var ki;(i=>{function n(r){return Xa(r)||null}i.get=n;function e(r,a){Za(r,a)}i.set=e;function t(r){es(r)}i.remove=t})(ki||(ki={}));var qe=ki;var ft=Ie(require("big-integer"));function _n(n,e){if(n.isAudioEnabled!==e.isAudioEnabled||n.isVideoEnabled!==e.isVideoEnabled||n.isScreenSharingEnabled!==e.isScreenSharingEnabled||n.videoStreams.length!==e.videoStreams.length)return!1;for(let t of n.videoStreams)if(!e.videoStreams.find(i=>i.id===t.id&&i.source===t.source))return!1;return!0}function Ee(n){return Object.assign({isAudioEnabled:!1,isVideoEnabled:!1,isScreenSharingEnabled:!1,videoStreams:[]},n||{})}var fn=n=>n.stop(),Sn=n=>n.getTracks().forEach(fn),xi=n=>n.getVideoTracks().forEach(fn),vn=n=>n.getVideoTracks()[0].clone();var x=class extends Error{constructor(e,t){super();this.name="HangupReason",this.code=t&&t.code||0,this.remote=t&&t.remote||!1,Object.values(P).indexOf(e)>-1?this.hangup=e:this.error=e;let i=[];this.error&&i.push("error"),this.remote&&i.push("remote"),this.code&&i.push(`code: ${this.code}`),t&&t.message&&i.push(`message: '${t.message}'`),this.message=e+(i.length?` (${i.join(", ")})`:""),Error.captureStackTrace&&Error.captureStackTrace(this,x)}};var ye=(i=>(i.SOURCE_CHANGED="SOURCE_CHANGED",i.TRACK_REPLACED="TRACK_REPLACED",i.SCREEN_STATUS="SCREEN_STATUS",i))(ye||{}),me=(i=>(i.audio="audio",i.video="video",i.screen="screen",i))(me||{}),Ni=class extends Q{constructor(){super();this._stream=null;this._trackVideoStreamBackup=null;this._screenTrack=null;this._sendVideoTrack=null;this._mediaSettings=Ee();this._videoStatusOnScreenCapturingEnabled=!1;this._effect=null;this._initDeviceChangeListener()}request(){return c(this,arguments,function*(e=[le.AUDIO]){if(this._stream)return;let t=e.includes(le.VIDEO),i=e.includes(le.AUDIO);if(!y.isBrowserSupported())throw new x(ne.UNSUPPORTED);try{this._stream=yield y.getUserMedia(t,i),this._mediaSettings.isVideoEnabled=t&&this._stream.getVideoTracks().filter(r=>r.enabled).length>0||!1,this._mediaSettings.isAudioEnabled=i&&this._stream.getAudioTracks().filter(r=>r.enabled).length>0||!1}catch(r){throw new x(r)}})}getStream(){return this._stream}getScreenTrack(){return this._screenTrack}getSendVideoTrack(e=!1){return this._sendVideoTrack&&!e?this._sendVideoTrack:this._stream?this._stream.getVideoTracks()[0]:null}_getSendAudioTrack(){var e;return((e=this._stream)==null?void 0:e.getAudioTracks()[0])||null}addTrackToPeerConnection(e,t=!1){let i=this.getStream(),r=this._getSendAudioTrack(),a=this.getSendVideoTrack(t);if(!i||!r&&!a)throw new Error("No local stream found");r&&e.addTrack(r,i),a&&e.addTrack(a,i)}getMediaSettings(){return this._mediaSettings}changeDevice(e){return c(this,null,function*(){switch(e){case"videoinput":return this._changeVideoInput();case"audioinput":return this._changeAudioInput();default:return Promise.reject()}})}setVideoStream(e,t){return c(this,null,function*(){return t?this._changeScreen(e):this._changeVideoInput(e)})}_initDeviceChangeListener(){if(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices||!navigator.mediaDevices.addEventListener)return;let e=!1,t=!1,i=T.throttle(()=>{t&&this._changeVideoInput().catch(()=>{}),e&&this._changeAudioInput().catch(()=>{}),e=!1,t=!1},1e3);navigator.mediaDevices.addEventListener("devicechange",()=>c(this,null,function*(){if(!this._stream)return;let r=this._stream.getAudioTracks()[0],a=r&&r.enabled&&r.getSettings(),s=a&&a.groupId,d=this._stream.getVideoTracks()[0],l=d&&d.enabled&&d.getSettings(),u=l&&l.groupId;if(!s&&!u)return;let g=yield navigator.mediaDevices.enumerateDevices();!e&&s&&(e=!g.find(f=>f.groupId===s)),!t&&u&&(t=!g.find(f=>f.groupId===u)),i()}))}_changeVideoInput(e=null){return c(this,null,function*(){try{let t=e?"stream":"video",i=e||(yield y.getUserVideo(void 0,!!this._effect));if(!this._stream)i.getTracks().forEach(r=>r.stop());else{p.consumerScreenTrack||this._disableScreenCapture();let r=this._getVideoEffectTrack(i),a=yield this._videoEffect(this._effect,r);this._stopLocalTrack("video"),m.log(_.DEVICE_CHANGED,t),o.log("Video stream changed"),yield this._replaceLocalTrack(a),this._mediaSettings.isVideoEnabled=!0,this._triggerEvent("SOURCE_CHANGED",{kind:"video",mediaSettings:this._mediaSettings})}}catch(t){throw m.log(_.ERROR,"change_video"),o.warn("Camera change failed",t),t}})}_getVideoEffectTrack(e){let t;return this._effect?(this._trackVideoStreamBackup||(this._trackVideoStreamBackup=vn(e)),t=this._trackVideoStreamBackup.clone(),xi(e)):this._trackVideoStreamBackup?(t=this._trackVideoStreamBackup.clone(),this._stopAndRemoveTrackVideoStreamBackup(),xi(e)):t=e.getVideoTracks()[0],t}setAudioStream(e){return c(this,null,function*(){return this._changeAudioInput(e)})}_changeAudioInput(e=null){return c(this,null,function*(){try{if(e=e||(yield y.getUserAudio()),!this._stream)e.getTracks().forEach(t=>t.stop());else{let t=e.getAudioTracks()[0];this._stopLocalTrack("audio"),m.log(_.DEVICE_CHANGED,"audio"),o.log("Audio stream changed"),yield this._replaceLocalTrack(t),this._mediaSettings.isAudioEnabled=!0,this._triggerEvent("SOURCE_CHANGED",{kind:"audio",mediaSettings:this._mediaSettings})}}catch(t){throw m.log(_.ERROR,"change_audio"),o.error("Microphone change failed",t),t}})}_changeScreen(e){return c(this,null,function*(){try{if(e=e||(yield y.getScreenMedia()),e.addEventListener("inactive",()=>{this._mediaSettings.isScreenSharingEnabled&&this.toggleScreenCapturing(!1)},!1),!this._stream)e.getTracks().forEach(t=>t.stop());else{let t=e.getVideoTracks()[0],i=p.consumerScreenTrack?t:yield this._videoEffect(null,t);m.log(_.DEVICE_CHANGED,"screen"),o.log("Screen capturing started"),this._screenTrack=i,this._mediaSettings.isScreenSharingEnabled=!0,p.consumerScreenTrack||(this._videoStatusOnScreenCapturingEnabled=this._mediaSettings.isVideoEnabled,this._mediaSettings.isVideoEnabled=!0,this._stopLocalTrack("video"),this._sendVideoTrack=p.consumerScreenDataChannel?y.getBlackMediaTrack(p.videoMinWidth,p.videoMinHeight):i,yield this._replaceLocalTrack(i,this._sendVideoTrack)),this._triggerEvent("SCREEN_STATUS",{track:i,mediaSettings:this._mediaSettings}),this._triggerEvent("SOURCE_CHANGED",{kind:"screen",mediaSettings:this._mediaSettings})}}catch(t){throw m.log(_.ERROR,"screen"),o.warn("Screen capturing failed",t),t}})}_disableScreenCapture(){this._sendVideoTrack&&(this._sendVideoTrack.stop(),this._sendVideoTrack=null),this._screenTrack&&(this._screenTrack.stop(),this._screenTrack=null),this._mediaSettings.isScreenSharingEnabled&&(this._mediaSettings.isScreenSharingEnabled=!1,this._triggerEvent("SCREEN_STATUS",{mediaSettings:this._mediaSettings}),this._triggerEvent("SOURCE_CHANGED",{kind:"screen",mediaSettings:this._mediaSettings}))}_replaceLocalTrack(e,t){return c(this,null,function*(){!this._stream||this._stream.getTracks().forEach(i=>{var r,a;i.kind===e.kind&&((r=this._stream)==null||r.removeTrack(i),(a=this._stream)==null||a.addTrack(e),this._triggerEvent("TRACK_REPLACED",e,t))})})}_stopLocalTrack(e){this._stream&&this._stream.getTracks().forEach(t=>{t.kind===e&&t.stop()})}_videoEffect(e,t){return c(this,null,function*(){if(!p.videoEffects)return t;try{return m.log(_.DEVICE_CHANGED,`effect_${e}`),p.videoEffects.setEffect(e,t)}catch(i){return o.warn("Video effect failed",i),t}})}_stopAndRemoveTrackVideoStreamBackup(){this._trackVideoStreamBackup&&(this._trackVideoStreamBackup.stop(),this._trackVideoStreamBackup=null)}destroy(){p.videoEffects&&(this._effect=null,p.videoEffects.destroy()),this._stream&&(Sn(this._stream),this._stream=null),this._stopAndRemoveTrackVideoStreamBackup(),this._disableScreenCapture()}toggleScreenCapturing(e){return c(this,null,function*(){return e?this._changeScreen():p.consumerScreenTrack?this._disableScreenCapture():this._videoStatusOnScreenCapturingEnabled?this._changeVideoInput():this.toggleVideo(!1)})}toggleVideo(e){return c(this,null,function*(){if(!this._stream)return;p.consumerScreenTrack||this._disableScreenCapture();let t;if(e){let i=yield y.getUserVideo(void 0,!!this._effect);t=this._getVideoEffectTrack(i),t=yield this._videoEffect(this._effect,t)}else t=y.getBlackMediaTrack(p.videoMinWidth,p.videoMinHeight),t=yield this._videoEffect(null,t),this._stopAndRemoveTrackVideoStreamBackup();this._stopLocalTrack("video"),yield this._replaceLocalTrack(t),this._mediaSettings.isVideoEnabled=e,this._triggerEvent("SOURCE_CHANGED",{kind:"video",mediaSettings:this._mediaSettings})})}toggleAudio(e){return c(this,null,function*(){if(!this._stream)return;let t;e?t=(yield y.getUserAudio()).getAudioTracks()[0]:t=y.getSilentMediaTrack(),this._stopLocalTrack("audio"),yield this._replaceLocalTrack(t),this._mediaSettings.isAudioEnabled=e,this._triggerEvent("SOURCE_CHANGED",{kind:"audio",mediaSettings:this._mediaSettings})})}setResolution(e,t){return c(this,null,function*(){if(!p.consumerScreenTrack&&this._mediaSettings.isScreenSharingEnabled)return;if(!this._stream)throw new Error("Local stream not found");let i=this._stream.getVideoTracks()[0];if(!i)throw new Error("Local video track not found");if(!!i.enabled){if(!this._effect)return i.applyConstraints({width:{ideal:e},height:{ideal:t}});yield this.toggleVideo(!1),yield this.toggleVideo(!0)}})}updateNoiseSuppression(){return c(this,null,function*(){if(!this._stream||!this._mediaSettings.isAudioEnabled)return;let e=this._stream.getAudioTracks()[0];if(!e)throw new Error("Local audio track not found");if(!!e.enabled)return e.applyConstraints({noiseSuppression:p.noiseSuppression})})}videoEffect(e){return c(this,null,function*(){if(!p.videoEffects)throw new Error("Video Effects library is not set");if(!p.consumerScreenTrack&&this._mediaSettings.isScreenSharingEnabled)throw new Error("Can't apply effect to screensharing");if(!this._mediaSettings.isVideoEnabled){this._effect=e;return}if(this._stream&&e!==this._effect)return this._effect=e,this._changeVideoInput(this._stream)})}};var Li;(gr=>{function n(C,R,M,b,w=!1){let Me=/[\r\n]+/,Z=`\r
8
- `;if(!R&&!M&&!b)return w?U(C.split(Me)).join(Z):C;function U(z){let Ne=["a=rtcp-fb:111 nack","a=rtcp-fb:111 nack pli"],ge="a=rtcp-fb:111",oe=z.findIndex(te=>te.startsWith(ge));return~oe&&(z[oe]=z[oe]+Z+Ne.join(Z)),z}function ee(z,Ne,ge){let oe=z.split(" "),te=oe.slice(0,3),he;for(he=3;he<oe.length;he++)ge.includes(oe[he])&&te.push(oe[he]);for(he=3;he<oe.length;he++)!ge.includes(oe[he])&&!Ne.includes(oe[he])&&te.push(oe[he]);return te.join(" ")}function A(z,Ne){let ge=new RegExp("a=rtpmap:(\\d+) ([a-zA-Z0-9-]+)\\/\\d+"),oe,te=[];for(oe=0;oe<z.length;++oe){let he=z[oe].match(ge);he&&he.length===3&&he[2]===Ne&&te.push(he[1])}return te}function q(z,Ne,ge,oe){let te,he="m="+Ne;for(te=0;te<z.length;++te)if(z[te].startsWith(he)){z[te]=ee(z[te],ge,oe);break}}let pe=[],D=C.split(Me);(M||R)&&(pe=A(D,"H264"));let Ge=[];if(b&&(Ge=A(D,"VP9")),M){let z=pe.slice(0),Ne=new RegExp("a=fmtp:(\\d+) apt=(\\d+)"),ge;for(ge=0;ge<D.length;++ge){let te=D[ge].match(Ne);te&&te.length===3&&z.includes(te[2])&&z.push(te[1])}let oe=new RegExp("a=(rtpmap|rtcp-fb|fmtp):(\\d+) .*");for(ge=D.length;ge--;){let te=D[ge].match(oe);te&&te.length===3&&z.includes(te[2])&&D.splice(ge,1)}q(D,"video",z,[])}else R&&q(D,"video",[],pe);return b&&q(D,"video",[],Ge),w&&U(D),D.join(Z)}gr.patchSDP=n;function e(C){return C?`${C.type||"WEB_SOCKET"}_${C.id}`:"_"}gr.getPeerIdString=e;function t(C,R){return C&&C.id===R.id&&(C.type||"WEB_SOCKET")===(R.type||"WEB_SOCKET")}gr.comparePeerId=t;function i(C){return c(this,null,function*(){return!C||!C.getStats?Promise.resolve(null):C.getStats(null).then(R=>{let M=null,b=null;if(R.forEach(w=>{w.type==="transport"&&w.selectedCandidatePairId?b=R.get(w.selectedCandidatePairId):w.type==="candidate-pair"&&w.state==="succeeded"&&!b&&(!w.hasOwnProperty("selected")||w.selected)&&(b=w)}),b&&b.localCandidateId){let w=R.get(b.localCandidateId);w&&(M={type:w.candidateType,ip:w.ip||w.ipAddress,port:w.port||w.portNumber})}return M}).catch(()=>null)})}gr.getPeerConnectionHostInfo=i;let r=/^[0-9]+$/,a=/^([gu])([0-9]+)$/;function s(C,R){let M=String(C);return a.test(M)?(o.warn(`Already composite id [${C}] type supplied [${R}]`),M):R===X.GROUP?"g"+M:R===X.USER?"u"+M:(o.warn(`Unknown type [${R}] for id [${C}]`),M.match(r)?"u"+M:M)}gr.composeId=s;function d(C){return s(C.id,C.idType||X.USER)}gr.composeParticipantId=d;function l(C){return C.participant?d(C.participant):s(C.participantId,C.participantType||X.USER)}gr.composeMessageId=l;function u(C){let R=String(C),M=R.match(a);return M?{id:Number(M[2]),type:M[1]==="g"?X.GROUP:X.USER}:(o.warn(`Unsupported compositeId [${C}]`),{id:Number(R),type:X.USER})}gr.decomposeId=u;function g(){let C="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),R=new Array(36),M=0,b,w;for(w=0;w<36;w++)w===8||w===13||w===18||w===23?R[w]="-":w===14?R[w]="4":(M<=2&&(M=33554432+Math.random()*16777216|0),b=M&15,M=M>>4,R[w]=C[w===19?b&3|8:b]);return R.join("")}gr.uuid=g;function f(C,R){let M;function b(){let w=this,Me=arguments;M&&window.clearTimeout(M),M=window.setTimeout(()=>{C.apply(w,Me)},R)}return b}gr.throttle=f;function W(C){let R="",M=C.split(`
9
- `);for(let Z of M)if(Z.startsWith("a=fingerprint")){let U=Z.split(" ");if(U.length===2){R=U[1];break}}if(!R)return ft.default.minusOne;let b=R.split(":"),w=ft.default.zero;for(let Z=Math.min(7,b.length-1);Z>=0;Z--){let U=(0,ft.default)(b[Z],16);w=w.shiftLeft(8).or(U)}return((Z,U)=>{let ee=U.value;if(typeof ee=="bigint")return(0,ft.default)(BigInt.asIntN(Z,ee));let A=ft.default.one.shiftLeft(Z),q=U.and(A.subtract(1));return q.greaterOrEquals(A.subtract(q))?q.subtract(A):q})(64,w)}gr.sdpFingerprint=W;function K(C){return c(this,null,function*(){return new Promise(R=>window.setTimeout(R,C))})}gr.delay=K;function k(C,R,M){let b=[];return C.getSenders().forEach(w=>Y(R,w,w.track,M,b)),b}gr.applySettings=k;function Y(C,R,M,b,w){if(C&&M&&M.kind===me.video){let Me=M.getSettings();if(Me){let Z=C.maxBitrateK?C.maxBitrateK*1024:null,U=Me.width,ee=Me.height,A=U&&ee&&C.maxDimension?Math.max(1,Math.max(U,ee)/C.maxDimension):null,q=C.maxFramerate?C.maxFramerate:null,pe=C.degradationPreference?C.degradationPreference:"balanced",D=b[M.id];if(D&&D.bitrate===Z&&D.scaleResolutionDownBy===A&&D.maxFramerate===q&&D.degradationPreference===pe){w[M.id]=D;return}w[M.id]={bitrate:Z,scaleResolutionDownBy:A,maxFramerate:q,degradationPreference:pe};let Ge=R.getParameters();Ge.encodings||(Ge.encodings=[{}]),Ge.encodings.forEach(z=>{Z?z.maxBitrate=Z:delete z.maxBitrate,A?z.scaleResolutionDownBy=A:delete z.scaleResolutionDownBy,q?z.maxFramerate=q:delete z.maxFramerate}),Ge.degradationPreference=pe,R.setParameters(Ge)}}}gr.applyVideoTrackSettings=Y;function se(C,R){Array.isArray(R)||(R=[R]);for(let M of R)if(C.includes(M))return!0;return!1}gr.includesOneOf=se;function ce(C){var R;return Object.entries(((R=C.participantState)==null?void 0:R.state)||{}).reduce((M,[b,w])=>(C.participantState&&(M[b]={ts:C.participantState.stateUpdateTs[b],state:w}),M),{})}gr.mapParticipantState=ce;function dt(C){return Object.entries(C).reduce((R,[M,{state:b}])=>(R[M]=b,R),{})}gr.mapLegacyParticipantState=dt;function ue(C){return C.map(R=>{let M={uid:R.externalId,mediaSettings:R.mediaSettings,status:R.status,muteStates:R.muteStates,unmuteOptions:R.unmuteOptions};return p.participantStateMapped&&(M.participantState=R.participantState),M})}gr.mapSharedParticipants=ue;function $(C,R){let M=Object.keys(C),b=Object.keys(R);if(M.length!==b.length)return!1;for(let w of M)if(!b.hasOwnProperty(w)||C[w].state!==R[w].state||C[w].ts!==R[w].ts)return!1;return!0}gr.isEqualParticipantState=$;function Oe(C,R){let M=Object.keys(C),b=Object.keys(R);if(M.length!==b.length)return!1;for(let w of M)if(!R.hasOwnProperty(w)||C[w]!==R[w])return!1;return!0}gr.isObjectsEquals=Oe;function It(C,R){if(C.length!==R.length)return!1;for(let M of C)if(R.indexOf(M)<0)return!1;return!0}gr.isArraysEquals=It;function mr(C){return!Object.keys(C).length}gr.isEmptyObject=mr})(Li||(Li={}));var T=Li;var tt=null,Ui=null,qt=[],Jt=[],Bi=[],At=null,Dt=null,Fi=null,Vi=!1,Hi=!1,Yt,St,zt,En=!1,Tn=!1,Gi=null,Wi="",Qt=[],ji=null,Cn=navigator.appVersion,ts=navigator.appName,Re=navigator.userAgent,Ki=(r=>(r.USER="user",r.ENVIRONMENT="environment",r.LEFT="left",r.RIGHT="right",r))(Ki||{}),wt=class{constructor(e,t=!1,i=p.videoMaxWidth,r=p.videoMaxHeight){let a=!1;if(e){a={noiseSuppression:p.noiseSuppression,echoCancellation:!0,autoGainControl:!0};let d;Dt&&(d=Dt.deviceId),typeof e=="string"&&(d=e),d&&(a.deviceId={exact:d})}let s=!1;if(t){s={width:{min:p.videoMinWidth,max:i,ideal:i},height:{min:p.videoMinHeight,max:r,ideal:r},aspectRatio:{ideal:p.videoAspectRatio},frameRate:{ideal:p.videoFrameRate}};let d;At&&(d=At.deviceId),typeof t=="string"&&(d=t),d&&(s.deviceId={exact:d}),p.videoFacingMode&&(s.facingMode={exact:p.videoFacingMode})}this.audio=a,this.video=s,this.needVideo=!!s}getNative(){return Object.assign({},{audio:this.audio,video:this.video})}simplify(){return typeof this.video=="object"&&(this.video.width||this.video.height?(delete this.video.width,delete this.video.height):this.video.aspectRatio?delete this.video.aspectRatio:this.video.frameRate?delete this.video.frameRate:(this.video.deviceId||this.video.facingMode)&&(delete this.video.deviceId,delete this.video.facingMode)),typeof this.audio=="object"&&(this.audio.echoCancellation||this.audio.autoGainControl||this.audio.noiseSuppression?(delete this.audio.echoCancellation,delete this.audio.autoGainControl,delete this.audio.noiseSuppression):this.audio.deviceId&&delete this.audio.deviceId),this.video===!0&&this.audio===!0?this.video=!1:this.video===!1&&this.audio===!0?(this.audio=!1,this.video=this.needVideo):this.video===!0&&this.audio===!1&&(this.video=!1),this.video&&!Object.keys(this.video).length&&(this.video=!0),this.audio&&!Object.keys(this.audio).length&&(this.audio=!0),this}canSimplify(){let e=typeof this.video=="object"&&(this.video.width||this.video.height||this.video.aspectRatio||this.video.frameRate||this.video.facingMode||this.video.deviceId)||this.video;return!!(typeof this.audio=="object"&&(this.audio.deviceId||this.audio.noiseSuppression||this.audio.echoCancellation||this.audio.autoGainControl)||this.audio||e)}isVideo(){return!!this.video}isAudio(){return!!this.audio}},In=class extends wt{constructor(e,t){super(!1,!0);typeof this.video=="object"?(delete this.video.deviceId,delete this.video.aspectRatio,delete this.video.frameRate,delete this.video.facingMode):this.video={},this.video.cursor="motion",this.video.width=e,this.video.height=t,this.video.frameRate=p.screenFrameRate}};function is(){return c(this,null,function*(){tt=null,yield Xt()})}function rs(){tt=null,Xt().then(()=>E.onDeviceChange())}function Xt(){return c(this,null,function*(){return tt||(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices?[]:(!Ui&&navigator.mediaDevices.addEventListener&&(Ui=T.throttle(rs,1e3),navigator.mediaDevices.addEventListener("devicechange",Ui)),tt=navigator.mediaDevices.enumerateDevices().then(n=>{qt=n.filter(r=>r.kind==="videoinput"?(r.label&&(Vi=!0),!0):!1),Jt=n.filter(r=>r.kind==="audioinput"?(r.label?Hi=!0:it.isMobile()&&it.browserName()==="Firefox"&&(Hi=Vi),!0):!1),Bi=n.filter(r=>r.kind==="audiooutput");let e=qe.get("videoinput"),t=qe.get("audioinput"),i=qe.get("audiooutput");return At=qt.find(r=>r.deviceId===e)||null,Dt=Jt.find(r=>r.deviceId===t)||null,Fi=Bi.find(r=>r.deviceId===i)||null,tt=Promise.resolve(n),n}).catch(()=>(tt=null,[]))))})}function ns(){return c(this,null,function*(){return it.isBrowserSupported()?new Promise(n=>{new window.RTCPeerConnection().createOffer({offerToReceiveVideo:!0}).then(t=>{/^a=rtpmap:\d+ VP8\/\d+$/m.test(t.sdp)&&(En=!0),/^a=mid:0$/m.test(t.sdp)&&(Tn=!0),n()}).catch(n)}):Promise.resolve()})}function Zt(n,e){return c(this,null,function*(){o.debug("Try to get media",n.getNative());let t=it.hasPermissions(n.isVideo());!t&&!e&&E.onPermissionsRequested();try{let i=yield navigator.mediaDevices.getUserMedia(n.getNative());return t||(yield is()),i}catch(i){switch(i.name){case"PermissionDeniedError":case"PermissionDismissedError":case"NotAllowedError":case"SecurityError":case"DOMException":e=n.isVideo()?ne.CAMERA_PERMISSION:ne.MIC_PERMISSION;break;case"OverconstrainedError":case"TypeError":case"NotFoundError":break;case"AbortError":case"NotReadableError":e=n.isVideo()?ne.CAMERA_ACCESS:ne.MIC_ACCESS;break}if(n.canSimplify())return Zt(n.simplify(),e);let r=e||ne.UNKNOWN;throw E.onPermissionsError(r),r}})}function as(n){return c(this,null,function*(){o.debug("Try to get screen",n.getNative());try{let e=yield navigator.mediaDevices.getDisplayMedia(n.getNative()),t=e==null?void 0:e.getVideoTracks()[0];return t&&(o.debug("Got display media track",t.id),t.contentHint="text"),e}catch(e){switch(e.name){case"PermissionDeniedError":case"NotAllowedError":case"SecurityError":throw ne.SCREEN_PERMISSION;default:throw ne.SCREEN_ACCESS}}})}function $i(){return Qt.length||(Qt=(()=>{let n,e=!1,t=0,i=Re.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];if(/trident/i.test(i[1]))return n=/\brv[ :]+(\d+)/g.exec(Re),["IE",n&&n[1]||"Unknown",e,t];if(i[1]==="Safari"){if(n=Re.match(/\bEdge\/(\d+)/),n)return["Edge",n[1]||"Unknown",e,t];if(n=Re.match(/\bCriOS\/(\d+)/),n)return["Chrome",n[1],!0,n[1]];if(n=Re.match(/\bFxiOS\/(\d+)/),n)return["Firefox",n[1],!1,t];if(n=Re.match(/\bYaBrowser\/(\d+)/),n)return["Yandex",n[1],!1,t];if(n=Re.match(/\bOPT\/(\d+)/),n)return["Opera",n[1],!1,t]}if(i[1]==="Chrome"){if(e=!0,t=Number(i[2]),n=Re.match(/\bOPR\/(\d+)/),n)return["Opera",n[1]||"Unknown",e,t];if(n=Re.match(/\bYaBrowser\/(\d+)/),n)return["Yandex",n[1]||"Unknown",e,t];if(n=Re.match(/\bSferum\/((\d+)(?:\.\d+)*)/),n)return["Sferum",n[1]||"Unknown",e,t];if(n=Re.match(/\bEdge?\/(\d+)/),n)return["Edge",n[1]||"Unknown",e,t];if(typeof window.opr!="undefined"&&/^(.+\.)?ok.ru$/.test(window.location.host))return["Opera","Hidden",e,t]}return n=Re.match(/version\/(\d+)/i),[i[2]?i[1]:ts,n&&n[1]||i[2]||Cn,e,t]})()),Qt}var it;(Z=>{function n(){return c(this,null,function*(){return yield ns(),Xt()})}Z.init=n;function e(){return qt}Z.getCameras=e;function t(){return Jt}Z.getMicrophones=t;function i(){return Bi}Z.getOutput=i;function r(){return qt.length>0}Z.hasCamera=r;function a(){return Jt.length>0}Z.hasMicrophone=a;function s(){return At}Z.getSavedCamera=s;function d(){return Dt}Z.getSavedMicrophone=d;function l(){return Fi}Z.getSavedOutput=l;function u(){return Vi}Z.hasCameraPermission=u;function g(){return Hi}Z.hasMicrophonePermission=g;function f(U=!1){return g()?r()&&U?u():!0:!1}Z.hasPermissions=f;function W(U=!1,ee=!0){return c(this,null,function*(){let A=a()&&ee,q=r()&&U,pe;if(!A&&!q)pe=new MediaStream;else try{pe=yield Zt(new wt(A,q))}catch(D){pe=new MediaStream}return pe.getVideoTracks().length||pe.addTrack(dt()),pe.getAudioTracks().length||pe.addTrack(ce()),pe})}Z.getUserMedia=W;function K(){return c(this,null,function*(){return as(new In(window.screen.width,window.screen.height))})}Z.getScreenMedia=K;function k(U,ee=!1){return c(this,null,function*(){let A=ee?p.videoEffectMaxWidth:p.videoMaxWidth,q=ee?p.videoEffectMaxHeight:p.videoMaxHeight;return Zt(new wt(!1,U||!0,A,q))})}Z.getUserVideo=k;function Y(U){return c(this,null,function*(){return Zt(new wt(U||!0,!1))})}Z.getUserAudio=Y;function se(U,ee){return c(this,null,function*(){let q=(yield Xt()).find(pe=>pe.kind===U&&pe.deviceId===ee);return q?(U==="videoinput"?At=q:U==="audioinput"?Dt=q:U==="audiooutput"&&(Fi=q),qe.set(U,ee),q):null})}Z.saveDeviceId=se;function ce(){if(!zt||zt.readyState==="ended"){let U=Me(),ee=U.createMediaStreamDestination(),A=U.createGain();A.gain.value=1e-5,A.connect(ee),A.connect(U.destination);let q=U.createOscillator();q.type="sine",q.frequency.value=0,q.connect(A),q.start(),zt=ee.stream.getAudioTracks()[0]}return Object.assign(zt.clone(),{enabled:!1})}Z.getSilentMediaTrack=ce;function dt(U=p.videoMinWidth,ee=p.videoMinHeight){return St||(St=document.createElement("canvas"),St.getContext("2d")),St.width=U,St.height=ee,(!Yt||Yt.readyState==="ended")&&(Yt=St.captureStream(p.videoFrameRate).getVideoTracks()[0]),Object.assign(Yt.clone(),{enabled:!1})}Z.getBlackMediaTrack=dt;function ue(){if(M()==="Edge"&&b()<70)return!1;try{let U=window;return navigator.mediaDevices&&navigator.mediaDevices.getUserMedia&&U.RTCPeerConnection&&U.RTCIceCandidate&&U.RTCSessionDescription&&U.HTMLCanvasElement&&U.HTMLCanvasElement.prototype.captureStream&&U.RTCRtpSender&&U.RTCRtpSender.prototype.replaceTrack&&U.RTCRtpSender.prototype.getParameters&&navigator.sendBeacon&&!0||!1}catch(U){return!1}}Z.isBrowserSupported=ue;function $(){return!!navigator.mediaDevices.getDisplayMedia}Z.isScreenCapturingSupported=$;function Oe(){return En}Z.canVP8=Oe;function It(){return Tn}Z.isUnifiedPlan=It;function mr(){return Z.browserName()==="Opera"&&Z.os()==="Windows"}Z.isBrokenH264=mr;function gr(){return!(Z.baseChromeVersion()&&Z.isMobile())}Z.canPreferH264=gr;function C(){return Wi||(Wi=(()=>{let U={Windows:/Win/,Android:/Android/,OpenBSD:/OpenBSD/,SunOS:/SunOS/,Linux:/(Linux|X11)/,iPad:/(iPad)/,iPhone:/(iPhone)/,iPod:/(iPod)/,MacOS:/(MacPPC|MacIntel|Mac_PowerPC|Macintosh|Mac OS X)/,QNX:/QNX/,UNIX:/UNIX/,BeOS:/BeOS/,OS2:/OS\/2/,Bot:/(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/};for(let ee in U)if(U.hasOwnProperty(ee)&&U[ee].test(Re))return ee;return"Unknown"})()),Wi}Z.os=C;function R(){return Gi===null&&(Gi=/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(Cn)),Gi}Z.isMobile=R;function M(){return $i()[0]}Z.browserName=M;function b(){return $i()[1]}Z.browserVersion=b;function w(){return $i()[3]}Z.baseChromeVersion=w;function Me(){return ji||(ji=new(window.AudioContext||window.webkitAudioContext)),ji}Z.getAudioContext=Me})(it||(it={}));var y=it;var yn=Ie(require("bit-buffer")),qi=Ie(wi()),Ji=Ie(require("crc"));var ss=65536,rt=class{constructor(e,t){this._chunks=[];this._participantId=e,this._onStream=t}appendChunk(e){let t=this._chunks.length;if(e.start)t&&(o.warn("[FrameBuilder] Cleanup buffer",Array.prototype.slice.call(this._chunks)),this._chunks=[]);else if(!t||(this._chunks[t-1].sequence+1)%ss!==e.sequence){o.warn("[FrameBuilder] Got incorrect chunk");return}if(this._chunks.push(e),e.end){let i=this._processFrameData(),{width:r,height:a}=rt.getFrameSize(i);this._processFrame({timestamp:e.timestamp,frameData:i,isVP9:e.isVP9,keyframe:e.keyframe,width:r,height:a})}}destroy(){this._chunks=[]}_processFrameData(){let e=this._chunks;this._chunks=[];let t=e.reduce((s,d)=>s+d.data.byteLength,0),i=new Uint8Array(t),r=[],a=0;for(let s of e)p.sharePrintChunkData&&o.debug("got chunk",a,s.data.byteLength,s.sequence,s.timestamp,s.keyframe,s.isVP9,s.data),r.push(Ji.default.crc32(qi.default.Buffer.from(s.data)).toFixed()),i.set(new Uint8Array(s.data),a),a+=s.data.byteLength;if(p.sharePrintFrameData){let s=Ji.default.crc32(qi.default.Buffer.from(i)).toFixed();o.debug("processed screenshare frame data",s,r)}return i}static getFrameSize(e){let t={width:0,height:0},i=new yn.BitStream(e.buffer);i.bigEndian=!0,i.index+=2;let r=i.readBits(1),s=i.readBits(1)<<1|r;return s===3&&i.index++,i.readBits(1)===1||i.readBits(1)!==0||(i.index++,i.index++,i.index+=24,s>=2&&i.index++,i.readBits(3)!==7?(i.index++,(s===1||s===3)&&(i.index+=3)):(s===1||s===3)&&i.index++,t.width=i.readBits(16)+1,t.height=i.readBits(16)+1),t}static isBrowserSupported(){throw new Error("Method `isBrowserSupported` is not implemented")}};var Ot=class extends rt{constructor(e,t){super(e,t);this._decoderReady=!1;this._decoderQueue=[];this._canvas=null;this._canvasContext=null;this._stream=null;this._track=null;o.debug(`StreamBuilder started for participant [${e}]`),this._useImageBitmap="ImageBitmap"in window,Xe.isBrowserSupported()&&!p.sharePlayWebcodecDisabled?this._decoder=new Xe:this._decoder=new ht,this._decoder.init((i,r)=>this._drawImage(i,r)).then(()=>{this._decoderReady=!0,this._decodeQueue()})}_createStream(e,t){this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.width=e,this._canvas.height=t,this._canvas.style.pointerEvents="none",this._canvas.style.visibility="hidden",this._canvas.style.position="absolute",this._canvas.style.width="160px",this._canvas.style.height="90px",this._canvas.style.bottom="0",this._canvas.style.right="0",this._canvas.style.zIndex="5000",document.body.appendChild(this._canvas),this._useImageBitmap?this._canvasContext=this._canvas.getContext("bitmaprenderer"):this._canvasContext=this._canvas.getContext("2d"),this._stream=this._canvas.captureStream(0),this._track=this._stream.getVideoTracks()[0],this._track.contentHint="text")}_removeStream(){this._stream&&(this._stream.getTracks().forEach(e=>e.stop()),this._stream=null,this._track=null),this._canvasContext=null;try{this._canvas&&document.body.removeChild(this._canvas)}catch(e){}this._canvas=null}_requestCanvasFrame(){this._track&&this._track.requestFrame?this._track.requestFrame():this._stream&&this._stream.requestFrame&&this._stream.requestFrame()}_drawImage(e,t){if(this._track||(this._createStream(e.width,e.height),this._onStream(this._stream)),p.sharePlayPrintFrameByFrame){let i=document.createElement("canvas");i.width=e.width,i.height=e.height,i.style.width="160px",i.style.height="90px",document.body.appendChild(i);let r;if(this._useImageBitmap?r=i.getContext("bitmaprenderer"):r=i.getContext("2d"),i.setAttribute("crc",t),e instanceof ImageData){let a=r;a.clearRect(0,0,i.width,i.height),a.putImageData(e,0,0)}else r.transferFromImageBitmap(e)}else{let i=this._canvas;if(i.width=e.width,i.height=e.height,e instanceof ImageData){let r=this._canvasContext;r.clearRect(0,0,i.width,i.height),r.putImageData(e,0,0)}else this._canvasContext.transferFromImageBitmap(e);this._requestCanvasFrame()}}_processFrame(e){if(!this._decoderReady||this._decoderQueue.length)this._decoderQueue.push(e),this._decodeQueue();else{let t=zi.default.crc32(Yi.default.Buffer.from(e.frameData)).toFixed();this._decoder.decodeFrame(e.timestamp,e.frameData,e.isVP9,t,e.keyframe)}}_decodeQueue(){if(!this._decoderReady)return;let e=this._decoderQueue;this._decoderQueue=[],e.forEach(t=>{let i=zi.default.crc32(Yi.default.Buffer.from(t.frameData)).toFixed();this._decoder.decodeFrame(t.timestamp,t.frameData,t.isVP9,i,t.keyframe)})}destroy(){super.destroy(),this._decoder.destroy(),this._removeStream(),o.debug(`StreamBuilder destroyed for participant ${this._participantId}`)}static isBrowserSupported(){return("CanvasCaptureMediaStream"in window||"CanvasCaptureMediaStreamTrack"in window)&&!(y.browserName()==="Safari"&&y.browserVersion()>=15)}};var ei=1,os=1,Rn=0,bn=11,Pn=1,Mn=2,An=4,Dn=8;function wn(n,e,t,i,r,a,s){let d=0;e&&(d|=Pn),t&&(d|=Mn),i&&(d|=An),s||(d|=Dn);let l=new ArrayBuffer(bn),u=new DataView(l);if(u.setUint8(0,ei),u.setUint16(1,r),u.setUint32(3,n),u.setUint8(7,a?1:0),u.setUint16(8,Rn),u.setUint8(10,d),!s)return l;let g=new Uint8Array(l.byteLength+s.byteLength);return g.set(new Uint8Array(l),0),g.set(new Uint8Array(s),l.byteLength),g.buffer}function On(n){let e=new DataView(n),t=e.getUint8(0),i=e.getUint16(1),r=e.getUint32(3),a=e.getUint8(7)===1,s=e.getUint16(8),d=e.getUint8(10),l=!!(d&Pn),u=!!(d&Mn),g=!!(d&An),f=!!(d&Dn);if(t!==ei)throw new Error(`Unexpected protocol version. Got ${t}, expected ${ei}`);return{timestamp:r,start:l,end:u,keyframe:g,sequence:i,isVP9:a,ssrc:s,eos:f,data:n.slice(bn)}}function kn(n){if(!n||!n.byteLength||n.byteLength!==4)return!1;let e=new DataView(n);return!(e.getUint8(0)!==ei||e.getUint8(1)!==os||e.getUint16(2)!==Rn)}var S=Ie(require("simple-ebml-builder"));var cs=Sr(2,15)-1,Qi=1,ds=5,ps=5;var ti=class{constructor(e){this._queue=[];this._clearBufferTill=0;this._mediaSource=new MediaSource,this._codec=e;let t=()=>{this._mediaSource.removeEventListener("sourceopen",t),this._initBuffer(),this._handleQueue()};this._mediaSource.addEventListener("sourceopen",t,!1)}_handleQueue(){if(!this._sourceBuffer||this._sourceBuffer.updating||!this._queue.length)return;if(this._clearBufferTill&&this._sourceBuffer.buffered.length){let i=this._sourceBuffer.buffered.start(0);i<this._clearBufferTill&&(this._sourceBuffer.remove(i,this._clearBufferTill),o.debug(`[WebmBuilder] SourceBuffer cleanup from ${i} to ${this._clearBufferTill}`)),this._clearBufferTill=0;return}let e=this._queue;this._queue=[];let t=ti._buildQueue(e);this._sourceBuffer.appendBuffer(t)}static _buildQueue(e){if(e.length){if(e.length===1)return S.build(e[0])}else return new Uint8Array;let t=e.reduce((a,s)=>a+s.countSize(),0),i=new Uint8Array(t),r=0;for(let a of e){let s=S.build(a);i.set(s,r),r+=s.byteLength}return i}_initBuffer(){this._sourceBuffer=this._mediaSource.addSourceBuffer(`video/webm; codecs="${this._codec}"`),this._sourceBuffer.mode="sequence",this._sourceBuffer.addEventListener("updateend",()=>this._handleQueue())}changeType(e){var t;return this._codec=e,(t=this._sourceBuffer)==null?void 0:t.changeType(e)}append(e,t=!1){this._queue.push(e),t&&this._handleQueue()}cleanup(){var a;let e=(a=this._sourceBuffer)==null?void 0:a.buffered,t=e==null?void 0:e.length;if(!t)return;let i=e.start(0),r=Math.max(0,e.end(t-1)-ds);r-i>ps&&(this._clearBufferTill=r)}destroy(){this._queue=[],this._mediaSource.readyState==="open"&&(this._sourceBuffer.abort(),this._mediaSource.endOfStream()),this._sourceBuffer=null,this._clearBufferTill=0}get codec(){return this._codec}get mediaSource(){return this._mediaSource}get buffered(){var e;return(e=this._sourceBuffer)==null?void 0:e.buffered}},$e=class extends rt{constructor(e,t){super(e,t);this._video=null;this._stream=null;this._earliestTimestamp=0;this._clusterStartTime=0;this._lastFrameTimestamp=0;o.debug(`[WebmBuilder] started for participant [${e}]`)}static _intToU16BE(e){return new Uint8Array([e>>8,e])}static _genWebmHeader(){return S.element(S.ID.EBML,[S.element(S.ID.EBMLVersion,S.number(1)),S.element(S.ID.EBMLReadVersion,S.number(1)),S.element(S.ID.EBMLMaxIDLength,S.number(4)),S.element(S.ID.EBMLMaxSizeLength,S.number(8)),S.element(S.ID.DocType,S.string("webm")),S.element(S.ID.DocTypeVersion,S.number(2)),S.element(S.ID.DocTypeReadVersion,S.number(2))])}static _genSegmentHeader(e,t,i){let r=S.element(S.ID.Info,[S.element(S.ID.TimecodeScale,S.number(1e6)),S.element(S.ID.MuxingApp,S.string("vk-webm-builder")),S.element(S.ID.WritingApp,S.string("vk-webm-builder"))]),a=[S.element(S.ID.PixelWidth,S.number(e)),S.element(S.ID.PixelHeight,S.number(t))],s=S.element(S.ID.Tracks,S.element(S.ID.TrackEntry,[S.element(S.ID.TrackNumber,S.number(Qi)),S.element(S.ID.TrackUID,S.number(Qi)),S.element(S.ID.TrackType,S.number(1)),S.element(S.ID.FlagLacing,S.number(0)),S.element(S.ID.DefaultDuration,S.number(1e9)),S.element(S.ID.CodecID,S.string(`V_${i.toUpperCase()}`)),S.element(S.ID.Video,a)]));return S.unknownSizeElement(S.ID.Segment,[r,s])}static _genClusterHeader(e){return S.unknownSizeElement(S.ID.Cluster,[S.element(S.ID.Timecode,S.number(Math.round(e)))])}_createVideo(e){this._mediaBuffer=new ti(e),this._video=document.createElement("video"),this._video.autoplay=!0,this._video.controls=!1,this._video.muted=!0,this._video.style.pointerEvents="none",this._video.style.visibility="hidden",this._video.style.position="absolute",this._video.style.width="160px",this._video.style.height="90px",this._video.style.bottom="0",this._video.style.right="0",this._video.style.zIndex="5000",this._video.src=URL.createObjectURL(this._mediaBuffer.mediaSource),document.body.appendChild(this._video);let t=()=>{if(this._video.src){o.warn(`[WebmBuilder] Video paused for participant [${this._participantId}], try to play again`);let i=this._video.seekable;i.length&&(this._video.currentTime=i.end(i.length-1)-1),this._video.play().catch(()=>{})}};this._video.onpause=t,this._video.onwaiting=t,this._video.onstalled=t,this._video.onerror=()=>o.warn(`[WebmBuilder] Video Error for participant [${this._participantId}]`,this._video.error),this._stream=this._video.captureStream(),this._onStream(this._stream)}_processFrame(e){let t=e.isVP9?"vp9":"vp8";this._mediaBuffer?this._mediaBuffer.codec!==t&&this._mediaBuffer.changeType(t):this._createVideo(t);let i=e.timestamp;if(i<=this._lastFrameTimestamp&&(i=this._lastFrameTimestamp+10,o.debug(`[WebmBuilder] Fixup timestamp for participant [${this._participantId}]`)),this._lastFrameTimestamp=i,this._earliestTimestamp)i-=this._earliestTimestamp;else{if(!e.keyframe)return;this._earliestTimestamp=i,i=0}if(e.keyframe){this._clusterStartTime=i,o.debug(`[WebmBuilder] Segment header for participant [${this._participantId}]`);let s=$e._genWebmHeader();this._mediaBuffer.append(s);let d=$e._genSegmentHeader(e.width,e.height,t);this._mediaBuffer.append(d),this._mediaBuffer.cleanup()}let r=Math.round(i-this._clusterStartTime);if(r>cs&&(this._clusterStartTime=i,r=0),r===0){o.debug(`[WebmBuilder] Cluster header for participant [${this._participantId}]`);let s=$e._genClusterHeader(this._clusterStartTime);this._mediaBuffer.append(s)}let a=S.element(S.ID.SimpleBlock,[S.vintEncodedNumber(Qi),S.bytes($e._intToU16BE(r)),S.number((e.keyframe?1:0)<<7),S.bytes(e.frameData)]);this._mediaBuffer.append(a,!0)}destroy(){super.destroy(),this._video&&(this._video.onpause=null,this._video.onwaiting=null,this._video.onstalled=null,this._video.onerror=null,this._video.pause(),this._video.src="",document.body.removeChild(this._video)),this._mediaBuffer&&(this._mediaBuffer.destroy(),this._mediaBuffer=null),this._stream&&(this._stream.getTracks().forEach(e=>e.stop()),this._stream=null),o.debug(`[WebmBuilder] destroyed for participant [${this._participantId}]`)}static isBrowserSupported(){var e,t,i;return"captureStream"in((e=window.HTMLVideoElement)==null?void 0:e.prototype)&&((t=window.MediaSource)==null?void 0:t.isTypeSupported('video/webm; codecs="vp8"'))&&((i=window.MediaSource)==null?void 0:i.isTypeSupported('video/webm; codecs="vp9"'))}};var nt=class{constructor(e,t,i,r,a){this._participantIdRegistry=null;this._streamBuilders={};this._onStream=()=>{};this._onEos=()=>{};this._parts=[];this._lastChunk=0;this._frames=0;o.debug("ScreenCaptureReceiver started"),t instanceof RTCDataChannel?(this._datachannel=t,this._datachannel.onmessage=s=>this._onDataChannelMessage(s.data)):this._replay(t),this._participantIdRegistry=i,this._conversation=e,this._onStream=r,this._onEos=a}_replay(e){return c(this,null,function*(){let t=yield e.arrayBuffer(),i=new DataView(t),r=0;for(;r<i.byteLength;){let a=this._readUint32(i,r);yield this._sleep(p.sharePlayFixedDelay?p.sharePlayFixedDelay:a);let s=this._readUint32(i,r+=4),d=t.slice(r+=4,r+=s);this._onDataChannelMessage(d)}})}_sleep(e){return c(this,null,function*(){return new Promise((t,i)=>{setTimeout(()=>{t()},e)})})}_readUint32(e,t){return e.getUint8(t)+(e.getUint8(t+1)<<8)+(e.getUint8(t+2)<<16)+(e.getUint8(t+3)<<24)}_onDataChannelMessage(e){var a,s;if(p.shareDumpReceived&&this._datachannel){let d=new Date().getTime(),l=this._lastChunk?d-this._lastChunk:0;this._lastChunk=d,this._parts.push(new Uint32Array([l,e.byteLength])),this._parts.push(new Uint8Array(e))}let t=On(e);t.end&&this._frames++;let i=(s=(a=this._participantIdRegistry)==null?void 0:a.getStreamDescription(t.ssrc))==null?void 0:s.participantId;if(!i)if(p.sharePlayRegisterMissingParticipantId&&this._conversation&&this._conversation.getRandomParticipant()){let d=this._conversation.getRandomParticipant();o.warn(`Registering ${d.id} as compacted ID ${t.ssrc}`),this._participantIdRegistry.register(t.ssrc,{participantId:d.id,mediaType:Se.SCREEN})}else{o.warn(`Participant id for ssrc ${t.ssrc} not found in registry`);return}if(t.eos){if(this.close(i),this._onEos(i),p.shareDumpReceived&&this._lastChunk){let d=new Date().toISOString().replace(/:/g,"-").replace(/.\d+Z/,"").replace("T","_");(0,Xi.saveAs)(new Blob(this._parts),"received-screenshare-"+i+"-"+d+".dat"),this._parts=[],this._lastChunk=0}o.log(`Received ${this._frames} screenshare frames`),this._frames=0;return}let r=this._streamBuilders[i];if(!r){let d=l=>this._onStream(i,l);r=new Ot(i,d),this._streamBuilders[i]=r}r.appendChunk(t)}close(e){let t=this._streamBuilders[e];t&&(t.destroy(),delete this._streamBuilders[e])}destroy(){if(o.log(`Received ${this._frames} screenshare frames`),this._frames=0,p.shareDumpReceived&&this._lastChunk){let e=new Date().toISOString().replace(/:/g,"-").replace(/.\d+Z/,"").replace("T","_");(0,Xi.saveAs)(new Blob(this._parts),"received-screenshare-"+e+".dat"),this._parts=[],this._lastChunk=0}this._datachannel&&(this._datachannel.onbufferedamountlow=null,this._datachannel.onmessage=null),this._onStream=()=>{},Object.values(this._streamBuilders).forEach(e=>e.destroy()),this._streamBuilders={},this._participantIdRegistry=null,o.debug("ScreenCaptureReceiver destroyed")}static isBrowserSupported(){return(Xe.isBrowserSupported()||ht.isBrowserSupported())&&(Ot.isBrowserSupported()||$e.isBrowserSupported())}};var xn=Ie(require("file-saver"));var Zi=Ie(require("@vkontakte/libvpx"));var ls=1e3,kt=class extends Be{constructor(e,t){super();this._video=null;this._imageCapture=null;this._canvas=null;this._canvasCtx=null;this._stream=null;this._track=null;this._frameReadTimeout=0;this._lastFrame=null;this._sourceTrack=e,this._onFrame=t,this._useImageCapture="ImageCapture"in window&&"ImageBitmap"in window,(e.readyState!=="live"||!e.enabled||e.muted)&&(this._useImageCapture=!1)}_createDom(){this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.style.pointerEvents="none",this._canvas.style.visibility="hidden",this._canvas.style.position="absolute",this._canvas.style.width="160px",this._canvas.style.height="90px",this._canvas.style.bottom="0",this._canvas.style.right="160px",this._canvas.style.zIndex="5000",this._canvasCtx=this._canvas.getContext("2d"),document.body.appendChild(this._canvas)),!this._video&&!this._useImageCapture&&(this._video=document.createElement("video"),this._video.controls=!1,this._video.autoplay=!1,this._video.preload="auto",this._video.muted=!0,this._video.style.pointerEvents="none",this._video.style.visibility="hidden",this._video.style.position="absolute",this._video.style.width="160px",this._video.style.height="90px",this._video.style.bottom="0",this._video.style.right="0",this._video.style.zIndex="5000",document.body.appendChild(this._video))}_removeDom(){try{this._canvas&&document.body.removeChild(this._canvas),this._video&&document.body.removeChild(this._video)}catch(e){}this._canvasCtx=null,this._canvas=null,this._video=null}_createStream(e){return c(this,null,function*(){if(!this._canvas)throw new Error("Canvas not found");if(!this._video&&!this._useImageCapture)throw new Error("Video element not found");return this._stream=this._canvas.captureStream(0),this._track=this._stream.getVideoTracks()[0],new Promise((t,i)=>{if(this._useImageCapture)this._imageCapture=new ImageCapture(e),t();else{let r=this._video;r.srcObject=new MediaStream([e]),r.onloadeddata=d=>t(),r.onerror=()=>i(new Error("Video element error"));let a=r.play(),s=()=>i(new Error("Autoplay is disabled"));a?a.catch(s):s()}})})}_removeStream(){var e;window.clearTimeout(this._frameReadTimeout),(e=this._lastFrame)==null||e.close(),this._stream&&(this._stream.getTracks().forEach(t=>t.stop()),this._stream=null,this._track=null),this._video&&(this._video.pause(),this._video.srcObject=null),this._imageCapture&&(this._imageCapture=null)}_drawFrameVideo(){if(!this._canvas||!this._canvasCtx||!this._video||!this._track)throw new Error("Fatal error");let e=this._video.videoWidth,t=this._video.videoHeight;return this._canvas.width=this._video.width=e,this._canvas.height=this._video.height=t,this._canvasCtx.clearRect(0,0,e,t),this._canvasCtx.drawImage(this._video,0,0,e,t),this._requestCanvasFrame(),this._canvasCtx.getImageData(0,0,e,t)}_getFrameBitmap(){return c(this,null,function*(){if(!this._imageCapture)throw new Error("Destroyed");return this._imageCapture.grabFrame()})}_drawFrameData(e){var r;if(!this._canvas||!this._canvasCtx||!this._track)throw new Error("Destroyed");let t=e.width,i=e.height;return this._canvas.width=t,this._canvas.height=i,this._canvasCtx.clearRect(0,0,t,i),this._canvasCtx.drawImage(e,0,0,t,i),this._requestCanvasFrame(),(r=this._canvasCtx)==null?void 0:r.getImageData(0,0,t,i)}_requestCanvasFrame(){this._track&&this._track.requestFrame?this._track.requestFrame():this._stream&&this._stream.requestFrame&&this._stream.requestFrame()}init(){return c(this,null,function*(){this._createDom();let e=this._sourceTrack.getSettings().width,t=this._sourceTrack.getSettings().height;o.debug(`LibVPxEncoder started ${e}x${t}, codec ${this.isVP9()?"VP9":"VP8"}`),yield this._createStream(this._sourceTrack),yield this._createWorker(`var exports=(()=>{var u=Object.defineProperty;var b=o=>u(o,"__esModule",{value:!0});var g=(o,n)=>{b(o);for(var t in n)u(o,t,{get:n[t],enumerable:!0})};var y={};g(y,{default:()=>R});var e=(r=>(r.INIT="init",r.READY="ready",r.FRAME="frame",r.ERROR="error",r.DEBUG="debug",r.LOG_ERROR="log_error",r))(e||{});var R=(o,n)=>{let t;function m(a,r){return o({locateFile:n}).then(s=>{if(t=new s.VpxEncoder,t.debug(r),!t.init(a?s.VpxType.VP9:s.VpxType.VP8))throw self.postMessage({type:e.LOG_ERROR,message:"encoder-init-fail-libvpx"}),new Error("LibVPxEncoder failed to create");t.setMaxQuantizer(10),t.setTargetBitrate(1024)})}function E(a,r,s,i){let c=t.allocateImage(a,r);if(!c){self.postMessage({type:e.FRAME,error:"No buffer data"});return}c.set(new Uint8Array(s));let f=Math.round(performance.now()),l=150;if(!t.encode(f,l,i)){self.postMessage({type:e.FRAME,error:"Encode failed"});return}let p=t.readFrame();if(!p){self.postMessage({type:e.FRAME,error:"No encoded data"});return}t.readFrame()&&(self.postMessage({type:e.DEBUG,message:"LibVPxEncoder dropped frame"}),self.postMessage({type:e.LOG_ERROR,message:"LibVPxEncoder-drop"}));let d=new Uint8Array(p.byteLength);d.set(p),self.postMessage({type:e.FRAME,frameType:i?"key":"delta",timestamp:f,duration:l,data:d.buffer},[d.buffer])}self.onmessage=a=>{switch(a.data.type){case e.INIT:m(a.data.isVP9,a.data.debug).then(()=>self.postMessage({type:e.READY})).catch(r=>self.postMessage({type:e.ERROR,error:String(r)}));break;case e.FRAME:E(a.data.width,a.data.height,a.data.imageData,a.data.keyFrame);break}}};return y;})();
10
- `,i=>{var r;i.error?this._onFrame(null,i.error):this._onFrame({type:i.frameType,timestamp:i.timestamp,duration:i.duration,data:i.data,byteLength:(r=i.data)==null?void 0:r.byteLength})},[Zi.default,Zi.default.getUrl],{isVP9:this.isVP9(),debug:o.enabled()})})}_encode(e,t){let i=e.data.buffer;this._sendToWorker(ve.FRAME,{width:e.width,height:e.height,imageData:i,keyFrame:t},[i])}_requestFrameVideo(e){let t=this._drawFrameVideo();this._encode(t,e)}_requestFrameBitmap(e){this._frameReadTimeout=window.setTimeout(()=>{if(this._lastFrame){let t=this._drawFrameData(this._lastFrame);this._encode(t,e)}else this._onFrame(null)},ls),this._getFrameBitmap().then(t=>{var r;window.clearTimeout(this._frameReadTimeout),(r=this._lastFrame)==null||r.close(),this._lastFrame=t;let i=this._drawFrameData(t);this._encode(i,e)}).catch(()=>{})}requestFrame(e=!1){this._useImageCapture?this._requestFrameBitmap(e):this._requestFrameVideo(e)}isVP9(){return!1}destroy(){this._removeWorker(),this._removeStream(),this._removeDom(),o.debug("LibVPxEncoder destroyed")}static isBrowserSupported(){return"WebAssembly"in window&&"Worker"in window&&("CanvasCaptureMediaStream"in window||"CanvasCaptureMediaStreamTrack"in window)}};var vt=class extends Be{constructor(e,t){super();this._sourceTrack=e,this._onFrame=t,this._trackProcessor=new MediaStreamTrackProcessor(e)}init(){return c(this,null,function*(){let e=this._sourceTrack.getSettings().width,t=this._sourceTrack.getSettings().height,i=this._trackProcessor.readable;o.debug(`WebCodecsEncoder started ${e}x${t}, codec ${this.isVP9()?"VP9":"VP8"}`),yield this._createWorker(`var exports=(()=>{var b=Object.defineProperty;var g=i=>b(i,"__esModule",{value:!0});var F=(i,n)=>{g(i);for(var r in n)b(i,r,{get:n[r],enumerable:!0})};var A={};F(A,{default:()=>h});var l=(r=>(r.VP9="vp09.00.50.08",r.VP8="vp8",r))(l||{}),d=(t=>(t.INIT="init",t.READY="ready",t.FRAME="frame",t.ERROR="error",t.DEBUG="debug",t.LOG_ERROR="log_error",t))(d||{});var h=()=>{let i=1e3,n,r,c,s,f,t,a=null,p=0,u=!1;function V(e){n=e.readable,r=n.getReader(),c=e.width,s=e.height,f=e.isVP9,t=e.framerate,m.configure({framerate:t,codec:f?l.VP9:l.VP8,width:c,height:s,latencyMode:"realtime"}),self.postMessage({type:d.READY})}function y(e){p=self.setTimeout(()=>{a&&E(a,e)},i),!u&&(u=!0,r.read().finally(()=>{u=!1,self.clearTimeout(p)}).then(({done:o,value:R})=>{if(a==null||a.close(),a=null,!(o||!R)){if(!m){r.releaseLock(),n.cancel();return}a=R,E(R,e)}}))}function E(e,o){(e.codedWidth!==c||e.codedHeight!==s)&&(c=e.codedWidth,s=e.codedHeight,m.configure({framerate:t,codec:f?l.VP9:l.VP8,width:c,height:s,latencyMode:"realtime"})),m.encode(e,{keyFrame:o})}let m=new VideoEncoder({output:e=>{let o;e.data?o=e.data:(o=new ArrayBuffer(e.byteLength),e.copyTo(o)),self.postMessage({type:d.FRAME,frameType:e.type,timestamp:e.timestamp,duration:e.duration,data:o},[o])},error:e=>{self.postMessage({type:d.FRAME,error:String(e)})}});self.onmessage=e=>{switch(e.data.type){case d.INIT:V(e.data);break;case d.FRAME:y(e.data.keyFrame);break}}};return A;})();
11
- `,r=>{var a;r.error?this._onFrame(null,r.error):this._onFrame({type:r.frameType,timestamp:r.timestamp,duration:r.duration,data:r.data,byteLength:(a=r.data)==null?void 0:a.byteLength})},[],{readable:i,width:e,height:t,isVP9:this.isVP9(),framerate:p.screenFrameRate},[i])})}requestFrame(e=!1){this._sendToWorker(ve.FRAME,{keyFrame:e})}isVP9(){return!0}destroy(){this._removeWorker(),o.debug("WebCodecsEncoder destroyed")}static isBrowserSupported(){return"VideoEncoder"in window&&"Worker"in window&&"EncodedVideoChunk"in window&&"MediaStreamTrackProcessor"in window}};var us=16*1024,hs=11,Nn=us-hs,ms=65536,er=0,Et=class{constructor(e,t){this._destroyed=!1;this._needKeyframe=!0;this._parts=[];this._lastChunk=0;o.debug("ScreenCaptureSender started"),this._datachannel=t;let i=(r,a)=>{if(!this._destroyed){if(!r){o.warn("requestFrame failed, keyFrame: "+this._needKeyframe,a),this._needKeyframe=!0,this._requestFrame();return}this._send(r).catch(s=>{o.warn("sendFrame failed",s),this._needKeyframe=!0}).finally(()=>this._requestFrame())}};vt.isBrowserSupported()?this._encoder=new vt(e,i):this._encoder=new kt(e,i),this._datachannel.onmessage=r=>{kn(r.data)&&(o.debug(`[${this._datachannel.label}] Requested keyframe`),this._needKeyframe=!0)},this._encoder.init().then(()=>this._requestFrame()).catch(r=>o.warn("ScreenCaptureSender init failed",r))}_requestFrame(){this._destroyed||(this._encoder.requestFrame(this._needKeyframe),this._needKeyframe=!1)}_wrapHeader(e,t,i,r,a){let s=wn(e,t,i,r,er,this._encoder.isVP9(),a);return er=(er+1)%ms,s}_stopPacket(){return this._wrapHeader(Date.now(),!1,!1,!1,null)}_send(e){return c(this,null,function*(){return new Promise((t,i)=>{this._sendChunk(e,0,t,i)})})}_sendChunk(e,t,i,r){if(!this._datachannel||this._datachannel.readyState!=="open"){r();return}let a=e.data.slice(t,t+Nn),s=e.data.byteLength<=t+a.byteLength,d=this._wrapHeader(e.timestamp,!t,s,e.type==="key",a);if(this._datachannel.onbufferedamountlow=s?()=>{this._datachannel.bufferedAmount<=this._datachannel.bufferedAmountLowThreshold&&i()}:null,p.shareDumpSent){let l=new Date().getTime(),u=this._lastChunk?l-this._lastChunk:0;this._lastChunk=l,this._parts.push(new Uint32Array([u,d.byteLength])),this._parts.push(new Uint8Array(d))}try{this._datachannel.send(d)}catch(l){o.warn("Error send data to DataChannel",l),r();return}s||window.setTimeout(()=>this._sendChunk(e,t+Nn,i,r),0)}destroy(){if(p.shareDumpSent&&this._lastChunk){let e=new Date().toISOString().replace(/:/g,"-").replace(/.\d+Z/,"").replace("T","_");(0,xn.saveAs)(new Blob(this._parts),"sent-screenshare-"+e+".dat"),this._parts=[],this._lastChunk=0}this._datachannel.onbufferedamountlow=null,this._datachannel.onmessage=null,this._datachannel.readyState==="open"&&this._datachannel.send(this._stopPacket()),this._destroyed=!0,this._encoder.destroy(),o.debug("ScreenCaptureSender destroyed")}static isBrowserSupported(){return vt.isBrowserSupported()||kt.isBrowserSupported()}};var ie=class{static get sessionKey(){return ie._sessionKey}static set sessionKey(e){ie._sessionKey=e}static get sessionSecretKey(){return ie._sessionSecretKey}static set sessionSecretKey(e){ie._sessionSecretKey=e}static get accessToken(){return ie._accessToken}static set accessToken(e){ie._accessToken=e}static isEmpty(){return!ie._sessionKey||!ie._sessionSecretKey}};var v=class{static set(e){e.hasOwnProperty("voiceParams")&&(Object.assign(v._params.voiceParams,e.voiceParams),delete e.voiceParams),e.hasOwnProperty("specListenerParams")&&(Object.assign(v._params.specListenerParams,e.specListenerParams),delete e.specListenerParams),e.hasOwnProperty("unifiedPlanBrowsers")&&(Object.assign(v._params.unifiedPlanBrowsers,e.unifiedPlanBrowsers),delete e.unifiedPlanBrowsers),e.hasOwnProperty("apiAuth")&&(ie.accessToken=e.apiAuth.accessToken,ie.sessionKey=e.apiAuth.sessionKey,ie.sessionSecretKey=e.apiAuth.sessionSecretKey),Object.assign(v._params,e)}static get(e){return v._params[e]}static get appName(){return"ok.calls.sdk.js"}static get appVersion(){return 1.1}static get sdkVersion(){return"2.5.2-dev.92f2f89.0"}static get debug(){return!1}static get protocolVersion(){return 5}static get platform(){return v._params.platform}static set platform(e){v._params.platform=e}static get clientType(){return v._params.clientType}static set clientType(e){v._params.clientType=e}static get device(){return v._params.device}static get apiAppId(){return 42}static get apiKey(){return v._params.apiKey}static get apiEnv(){return v._params.apiEnv}static get apiEndpoint(){switch(v.apiEnv){case"AUTO":case"PROD":return"https://api.ok.ru";case"TEST":return"https://apitest.ok.ru/api";case"VIDEOTEST":return"https://videotestapi.ok.ru/api";default:return v._params.apiEnv}}static get authToken(){return v._params.authToken}static set authToken(e){v._params.authToken=e}static get anonymToken(){return v._params.anonymToken}static set anonymToken(e){v._params.anonymToken=e}static get domain(){return v._params.domain}static get iceServers(){return v._params.iceServers}static set iceServers(e){v._params.iceServers=e}static get wssBase(){return v._params.wssBase}static set wssBase(e){v._params.wssBase=e}static get wssToken(){return v._params.wssToken}static set wssToken(e){v._params.wssToken=e}static get signalingReconnectDelay(){return v._params.signalingReconnectDelay}static get signalingReconnectMaxDelay(){return v._params.signalingReconnectMaxDelay}static get signalingReconnectMaxCount(){return v._params.signalingReconnectMaxCount}static get waitConnectionDelay(){return v._params.waitConnectionDelay}static get waitResponseDelay(){return v._params.waitResponseDelay}static get waitMessageDelay(){return v._params.waitMessageDelay}static get debugLog(){return v._params.debugLog}static get forceRelayPolicy(){return v._params.forceRelayPolicy}static set forceRelayPolicy(e){v._params.forceRelayPolicy=e}static get videoMinWidth(){return v._params.videoMinWidth}static get videoMaxWidth(){return v._params.videoMaxWidth}static set videoMaxWidth(e){v._params.videoMaxWidth=e}static get videoMinHeight(){return v._params.videoMinHeight}static get videoMaxHeight(){return v._params.videoMaxHeight}static set videoMaxHeight(e){v._params.videoMaxHeight=e}static get videoAspectRatio(){return v._params.videoAspectRatio}static get videoFrameRate(){return v._params.videoFrameRate}static get videoFacingMode(){return v._params.videoFacingMode}static get screenFrameRate(){return v._params.screenFrameRate}static get videoEffects(){return v._params.videoEffects}static set videoEffects(e){v._params.videoEffects=e}static get videoEffectMaxWidth(){return v._params.videoEffectMaxWidth}static set videoEffectMaxWidth(e){v._params.videoEffectMaxWidth=e}static get videoEffectMaxHeight(){return v._params.videoEffectMaxHeight}static set videoEffectMaxHeight(e){v._params.videoEffectMaxHeight=e}static get voiceParams(){return v._params.voiceParams}static get specListenerParams(){return v._params.specListenerParams}static get iceRestartWaitTime(){return v._params.iceRestartWaitTime}static get transportConnectionWaitTime(){return v._params.transportConnectionWaitTime}static get statisticsInterval(){return v._params.statisticsInterval}static set statisticsInterval(e){v._params.statisticsInterval=e}static get networkStatisticsInterval(){return v._params.networkStatisticsInterval}static get perfStatReportEnabled(){return v._params.perfStatReportEnabled}static get callStatReportEnabled(){return v._params.callStatReportEnabled}static get producerNotificationDataChannel(){return v._params.producerNotificationDataChannel&&nt.isBrowserSupported()}static get producerCommandDataChannel(){return v._params.producerCommandDataChannel}static get consumerScreenDataChannel(){return v._params.consumerScreenDataChannel&&Et.isBrowserSupported()}static get producerScreenDataChannel(){return v._params.producerScreenDataChannel&&v.producerNotificationDataChannel}static get screenShareWebmBuilder(){return v._params.screenShareWebmBuilder}static get noiseSuppression(){return v._params.noiseSuppression}static set noiseSuppression(e){v._params.noiseSuppression=e}static get preferH264(){return v._params.preferH264}static get preferVP9(){return v._params.preferVP9}static get audioNack(){return v._params.audioNack}static get consumerScreenTrack(){return v._params.consumerScreenTrack&&v.consumerScreenDataChannel}static get producerScreenTrack(){return v._params.producerScreenTrack&&v.producerScreenDataChannel}static isUnifiedPlanSupported(e,t){let i=v._params.unifiedPlanBrowsers;return i.hasOwnProperty(e)?t>=i[e]:!1}static get movieShare(){return v._params.movieShare&&v.videoTracksCount>0}static get videoTracksCount(){return v.producerNotificationDataChannel?v._params.videoTracksCount:0}static get breakVideoPayloadTypes(){return v._params.breakVideoPayloadTypes}static get filteredMessages(){return v._params.filteredMessages}static get batchParticipantsOnStart(){return v._params.batchParticipantsOnStart}static get participantStateMapped(){return v._params.participantStateMapped}static get shareDumpSent(){return!0}static get shareDumpReceived(){return!0}static get sharePrintChunkData(){return!0}static get sharePrintFrameData(){return!0}static get sharePlayWebcodecDisabled(){return!1}static get sharePlayPrintFrameByFrame(){return!1}static get sharePlayRegisterMissingParticipantId(){return!1}static get sharePlayFixedDelay(){return 0}},p=v;p._params={platform:"WEB",clientType:"PORTAL",device:"browser",apiKey:"",authToken:"",anonymToken:"",apiEnv:"AUTO",domain:"",iceServers:[],wssBase:"",wssToken:"",signalingReconnectDelay:1e3,signalingReconnectMaxDelay:5e3,signalingReconnectMaxCount:20,waitConnectionDelay:1e4,waitResponseDelay:1e4,waitMessageDelay:15e3,debugLog:!1,forceRelayPolicy:!1,videoMinWidth:428,videoMinHeight:240,videoMaxWidth:1280,videoMaxHeight:720,videoAspectRatio:16/9,videoFrameRate:25,screenFrameRate:15,videoEffects:null,videoEffectMaxWidth:640,videoEffectMaxHeight:360,iceRestartWaitTime:2e4,transportConnectionWaitTime:5e3,statisticsInterval:5e3,networkStatisticsInterval:2e4,perfStatReportEnabled:!0,callStatReportEnabled:!1,voiceParams:{smoothing:.8,minFreq:200,maxFreq:5e3,interval:500,threshold:.35,speakerLevelMultiplier:1.8},specListenerParams:{connectionTimeout:1e4,volumeTimeout:1e4},unifiedPlanBrowsers:{Firefox:10,Chrome:76,Safari:12},producerNotificationDataChannel:!0,producerCommandDataChannel:!0,consumerScreenDataChannel:!0,producerScreenDataChannel:!0,screenShareWebmBuilder:!1,noiseSuppression:!0,preferH264:!1,preferVP9:!0,audioNack:!0,consumerScreenTrack:!1,producerScreenTrack:!1,videoTracksCount:0,movieShare:!1,filteredMessages:!1,breakVideoPayloadTypes:!1,batchParticipantsOnStart:!1,participantStateMapped:!1};var J=(l=>(l.WAITING_HALL="WAITING_HALL",l.WAITING="WAITING",l.CONNECTING="CONNECTING",l.CONNECTED="CONNECTED",l.RECONNECT="RECONNECT",l.ERROR="ERROR",l.HANGUP="HANGUP",l.PERMISSIONS="PERMISSIONS",l))(J||{});function V(n,...e){let t=p.get(n);t&&setTimeout(t,0,...e)}function He(n){return Object.assign({},n)}function Tt(n){return n.slice()}var tr;(he=>{function n(I,B){V("onLocalStream",I,He(B))}he.onLocalStream=n;function e(I,B){V("onScreenStream",I,He(B))}he.onScreenStream=e;function t(I,B){V("onLocalStreamUpdate",He(I),B)}he.onLocalStreamUpdate=t;function i(I){V("onLocalStatus",I)}he.onLocalStatus=i;function r(I,B){V("onRemoteStream",I,B)}he.onRemoteStream=r;function a(I,B,de){V("onRemoteLive",I,B,de)}he.onRemoteLive=a;function s(I,B){V("onRemoteScreenStream",I,B)}he.onRemoteScreenStream=s;function d(I,B,de,yt){V("onConversation",I,He(B),He(de),yt)}he.onConversation=d;function l(I,B){V("onRemoteMediaSettings",I,He(B))}he.onRemoteMediaSettings=l;function u(I,B){V("onRemoteParticipantState",I,He(B))}he.onRemoteParticipantState=u;function g(I,B,de=null){V("onRemoteStatus",I,B,de)}he.onRemoteStatus=g;function f(I,B,de=null){V("onParticipantStatus",I,B,de)}he.onParticipantStatus=f;function W(){V("onPermissionsRequested")}he.onPermissionsRequested=W;function K(I){V("onPermissionsError",I)}he.onPermissionsError=K;function k(I){V("onRemoteRemoved",I)}he.onRemoteRemoved=k;function Y(I,B,de){V("onCallState",I,B,He(de))}he.onCallState=Y;function se(I,B){V("onDeviceSwitched",I,B)}he.onDeviceSwitched=se;function ce(I,B,de,yt=!1,li=!1,ui=null,oa=null){V("onMuteStates",He(I),Tt(B),Tt(de),yt,li,ui,oa)}he.onMuteStates=ce;function dt(I,B){V("onRolesChanged",I,Tt(B))}he.onRolesChanged=dt;function ue(I){V("onLocalRolesChanged",Tt(I))}he.onLocalRolesChanged=ue;function $(I,B){V("onPinnedParticipant",I,B)}he.onPinnedParticipant=$;function Oe(I){V("onLocalPin",I)}he.onLocalPin=Oe;function It(I){V("onOptionsChanged",Tt(I))}he.onOptionsChanged=It;function mr(){V("onCallAccepted")}he.onCallAccepted=mr;function gr(){V("onRateNeeded")}he.onRateNeeded=gr;function C(I){V("onSpeakerChanged",I)}he.onSpeakerChanged=C;function R(I){V("onVolumesDetected",Tt(I))}he.onVolumesDetected=R;function M(I,B){V("onLocalVolume",I,B)}he.onLocalVolume=M;function b(I,B){V("onJoinStatus",I,B)}he.onJoinStatus=b;function w(I,B){V("onHangup",I,B)}he.onHangup=w;function Me(I){V("onMultipartyChatCreated",He(I))}he.onMultipartyChatCreated=Me;function Z(){V("onDeviceChange")}he.onDeviceChange=Z;function U(I){V("onFingerprintChange",I)}he.onFingerprintChange=U;function ee(){V("onTokenExpired")}he.onTokenExpired=ee;function A(I,B,de=!1){V("onChatMessage",I,B,de)}he.onChatMessage=A;function q(I,B,de=!1){V("onCustomData",I,B,de)}he.onCustomData=q;function pe(I,B,de,yt,li,ui){V("onRecordStarted",I,B,de,yt,li,ui)}he.onRecordStarted=pe;function D(){V("onRecordStopped")}he.onRecordStopped=D;function Ge(I){V("onLocalNetworkStatusChanged",I)}he.onLocalNetworkStatusChanged=Ge;function z(I){V("onNetworkStatusChanged",I)}he.onNetworkStatusChanged=z;function Ne(I,...B){V("onDebugMessage",I,...B)}he.onDebugMessage=Ne;function ge(I,B){let de=Object.assign({},I,{memory:B});V("onStatistics",de)}he.onStatistics=ge;function oe(){V("onAutoplayError")}he.onAutoplayError=oe;function te(I,B,de){V("onChatRoomUpdated",I,B,de)}he.onChatRoomUpdated=te})(tr||(tr={}));var E=tr;var ir=(r=>(r.DEBUG="DEBUG",r.LOG="LOG",r.WARN="WARN",r.ERROR="ERROR",r))(ir||{}),rr;(ue=>{let n="📞",e=($,...Oe)=>{E.onDebugMessage($,...Oe)},t=!1,i=($,Oe)=>(...It)=>{$(...It),zr(Oe,It)},r=console.debug.bind(console,n),a=console.log.bind(console,n),s=console.warn.bind(console,n),d=console.error.bind(console,n),l=e.bind(null,"DEBUG"),u=e.bind(null,"LOG"),g=e.bind(null,"WARN"),f=e.bind(null,"ERROR");ue.debug=l,ue.log=u,ue.warn=g,ue.error=f;function se(){return t}ue.enabled=se;function ce($){t=$,p.debugLog&&Si(),$?(ue.debug=p.debugLog?i(r,"DEBUG"):r,ue.log=p.debugLog?i(a,"LOG"):a,ue.warn=p.debugLog?i(s,"WARN"):s,ue.error=p.debugLog?i(d,"ERROR"):d):(ue.debug=p.debugLog?i(l,"DEBUG"):l,ue.log=p.debugLog?i(u,"LOG"):u,ue.warn=p.debugLog?i(g,"WARN"):g,ue.error=p.debugLog?i(f,"ERROR"):f)}ue.toggle=ce;function dt($,...Oe){switch($){case"DEBUG":ue.debug(...Oe);break;case"LOG":ue.log(...Oe);break;case"WARN":ue.warn(...Oe);break;case"ERROR":ue.error(...Oe);break}}ue.send=dt})(rr||(rr={}));var o=rr;var at=(i=>(i.USER="USER",i.ANONYM="ANONYM",i.GROUP="GROUP",i))(at||{}),re;(d=>{function n(l){return l.length?typeof l[0]=="object"?l:l.map(u=>e(u)):[]}d.fromIds=n;function e(l,u="USER"){return{id:l,type:u}}d.fromId=e;function t(l){return{id:l.id,type:l.type==="ANONYM"?"ANONYM":"USER"}}d.fromSignaling=t;function i(l){return`{"id":"${l.id}","type":"${l.type}"}`}d.toString=i;function r(l,u="USER"){return i(e(l,u))}d.fromIdToString=r;function a(l){try{return JSON.parse(l)}catch(u){throw new Error(`Failed to parse ExternalId from string '${l}'`)}}d.fromString=a;function s(l,u){return l.id===u.id&&l.type===u.type}d.compare=s})(re||(re={}));function nr(n,e){return n===null||e===null?n===null&&e===null:!(n.maxDimension!==e.maxDimension||n.maxBitrateK!==e.maxBitrateK||n.maxFramerate!==e.maxFramerate||n.degradationPreference!==e.degradationPreference)}function ii(n,e){return!(!nr(n.camera,e.camera)||!nr(n.screenSharing,e.screenSharing))}function ar(n,e){return{camera:Object.assign({},n.camera,e.camera),screenSharing:Object.assign({},n.screenSharing,e.screenSharing)}}function Ln(n){try{return btoa(JSON.stringify(n))}catch(e){o.warn("WaitingParticipant: failed convert to string",n,e)}return null}function Un(n){try{return JSON.parse(atob(n))}catch(e){o.warn("WaitingParticipant: failed convert from string",n,e)}return null}var xt=class{constructor(e){this._fixNoPacketsApplied=!1;this._fixNoPacketsChecked=!1;this._fixTooManyPacketsApplied=!1;this._fixTooManyPacketsSucceeded=!1;this._fixTooManyPacketsFailed=!1;this._mediaSource=e}_fixAudioDeviceNoPackets(e){if(!(this._fixNoPacketsApplied&&this._fixNoPacketsChecked)){if(this._fixNoPacketsApplied&&!this._fixNoPacketsChecked){this._fixNoPacketsChecked=!0,m.log(_.ERROR,`audio_device_recover_${e.bandwidth?"success":"fail"}`);return}!this._fixNoPacketsApplied&&!e.bandwidth&&(this._fixNoPacketsApplied=!0,m.log(_.ERROR,"audio_device_recover"),this._mediaSource.toggleAudio(!0))}}_fixAudioDeviceTooManyPackets(e){if(this._fixTooManyPacketsSucceeded||this._fixTooManyPacketsFailed)return;let t=75,i=Date.now();if(!this._lastPacketsSentTime)e.packetsSent>0&&(this._lastPacketsSentTime=i,this._lastPacketsSent=e.packetsSent);else if(i-this._lastPacketsSentTime>500){let r=(e.packetsSent-this._lastPacketsSent)*1e3/(i-this._lastPacketsSentTime);this._lastPacketsSentTime=i,this._lastPacketsSent=e.packetsSent,this._fixTooManyPacketsApplied?r>t?(o.log("Failed to fix RV"),m.log(_.ERROR,"audio_device_recover_rv_fail"),this._fixTooManyPacketsFailed=!0):i-this._fixTooManyPacketsTime>6e4&&(o.log("Fixed RV"),m.log(_.ERROR,"audio_device_recover_rv_success"),this._fixTooManyPacketsSucceeded=!0):r>t&&(this._fixTooManyPacketsApplied=!0,o.log("Trying to fix RV"),this._mediaSource.toggleAudio(!0),this._fixTooManyPacketsTime=i)}}fix(e){if(!this._mediaSource)return;let t=e.find(i=>i.kind===me.audio);!t||(this._fixAudioDeviceNoPackets(t),this._fixAudioDeviceTooManyPackets(t))}};var ri=class{constructor(){this._output=null;this._volume=1;this._features={setSinkId:!!Audio.prototype.setSinkId}}add(e){this.destroy(),this._output={},this._output.audioTrack=e,this._initAudioElement()}remove(e){!this._output||this._output.audioTrack!==e||this.destroy()}get volume(){return this._volume}set volume(e){this._volume=Math.max(0,Math.min(1,e)),this._output&&this._output.audioElement&&(this._output.audioElement.volume=this._volume)}_initAudioElement(){var s;if(!((s=this._output)==null?void 0:s.audioTrack))return;let e=y.browserName()!=="Safari",t=document.createElement(e?"audio":"video");t.muted=!1,t.volume=this._volume,t.preload="auto";let i=()=>{o.warn("Error on play audio"),E.onAutoplayError()},r=d=>{t.srcObject=new MediaStream([d]),t.load();let l=t.play();l?l.catch(i):i()},a=()=>{var l;o.debug("Recover audio playback");let d=(l=this._output)==null?void 0:l.audioTrack;d?r(d):o.warn("Broken audio track")};t.onpause=a,t.onstalled=a,t.onerror=a,r(this._output.audioTrack),this._output.audioElement=t}_stopAudioElement(){var e,t,i;((e=this._output)==null?void 0:e.audioElement)&&(this._output.audioElement.pause(),this._output.audioElement.srcObject=null),(i=(t=this._output)==null?void 0:t.audioTrack)==null||i.stop()}destroy(){!this._output||(this._stopAudioElement(),this._output=null)}changeOutput(){return c(this,null,function*(){var e,t,i;try{if(!this._features.setSinkId)throw new Error('Feature "setSinkId" is not supported');if(!((e=this._output)==null?void 0:e.audioElement))throw new Error("Audio Element is not initialized");let r=y.getSavedOutput();r&&(yield(i=(t=this._output.audioElement).setSinkId)==null?void 0:i.call(t,r.deviceId))}catch(r){throw m.log(_.ERROR,"change_output"),o.error("Output change failed",r),r}})}};var gs=90,_s=3,ni=class extends Q{constructor(){super(...arguments);this._lastMemoryStat={percent:0,bytes:0}}onRemoteDataStats(e,t){this._calcMemory(),e.inbound.rtps.map(i=>{let r=typeof i.userId=="string"&&t[i.userId]||null;i.userId=r==null?void 0:r.externalId}),E.onStatistics(e,this._lastMemoryStat)}_calcMemory(){var r;let e=(r=window==null?void 0:window.performance)==null?void 0:r.memory;if(!e||!e.usedJSHeapSize||!e.jsHeapSizeLimit)return;let t=Number((100*e.usedJSHeapSize/e.jsHeapSizeLimit).toFixed(2)),i=Number((e.usedJSHeapSize/1024/1024).toFixed(1));t>gs?o.warn(`High memory usage: ${t}% (${i} MiB)`):(!this._lastMemoryStat.percent||Math.abs(t-this._lastMemoryStat.percent)>=_s)&&(o.debug(`Memory usage: ${t}% (${i} MiB)`),this._lastMemoryStat.percent=t,this._lastMemoryStat.bytes=e.usedJSHeapSize)}};var fs=44100,Nt=class{constructor(e,t){this._analyser=null;this._gainNode=null;this._fftBins=null;this._mediaStreamSource=null;this._lastSmoothedLevel=0;this._trackId=e,this._stream=t;try{let i=y.getAudioContext();this._gainNode=i.createGain(),this._gainNode.gain.value=1e-5,this._gainNode.connect(i.destination),this._analyser=i.createAnalyser(),this._analyser.fftSize=1024,this._analyser.smoothingTimeConstant=0,this._analyser.connect(this._gainNode),this._fftBins=new Uint8Array(this._analyser.frequencyBinCount),this._mediaStreamSource=i.createMediaStreamSource(t),this._mediaStreamSource.connect(this._analyser)}catch(i){}}get stream(){return this._stream}get trackId(){return this._trackId}_getBins(){if(!this._fftBins||!this._analyser)return new Uint8Array;this._analyser.getByteFrequencyData(this._fftBins);let e=fs/this._fftBins.length,t=Math.ceil(p.voiceParams.minFreq/e),i=Math.floor(p.voiceParams.maxFreq/e);return this._fftBins.subarray(t,i)}getLevel(){let e=this._getBins(),i=e.reduce((a,s)=>a+s,0)/e.length/255,r=this._lastSmoothedLevel*p.voiceParams.smoothing+i*(1-p.voiceParams.smoothing);return this._lastSmoothedLevel=r,{real:i,smoothed:r}}destroy(){this._mediaStreamSource&&(this._mediaStreamSource.disconnect(),this._mediaStreamSource=null),this._gainNode&&(this._gainNode.disconnect(),this._gainNode=null),this._analyser&&(this._analyser.disconnect(),this._analyser=null,this._fftBins=null,this._lastSmoothedLevel=0)}};var ai=class extends Q{constructor(e){super();this._detector=null;this._track=null;this._interval=null;let t=()=>{this._detector&&E.onLocalVolume(this._detector.getLevel().real,e.getMediaSettings().isAudioEnabled),this._interval=window.setTimeout(t,p.voiceParams.interval)};this._interval=window.setTimeout(t,p.voiceParams.interval);let i=()=>{let r=e.getStream();r&&this.init(r)};this.subscribe(e,ye.SOURCE_CHANGED,r=>{r.kind===me.audio&&r.mediaSettings.isAudioEnabled&&i()}),i()}init(e){this._stopDetector();let t=e.getAudioTracks();t.length&&(this._track=t[0].clone(),this._detector=new Nt("local",new MediaStream([this._track])))}_stopDetector(){this._detector&&(this._detector.destroy(),this._detector=null),this._track&&(this._track.stop(),this._track=null)}destroy(){this.unsubscribe(),this._interval&&(window.clearTimeout(this._interval),this._interval=null),this._stopDetector()}};var Ss=1e3;function be(n,e,t=0){return e in n&&n[e]?n[e]:t}function Bn(...n){return e=>{for(let t of n)if(t(e))return!0;return!1}}function Je(n,e){return t=>t[n]===e}function vs(n){return(e,t)=>e[n]-t[n]}function si(n,e){return e.reduce((t,i)=>(t[i[n]]=i,t),{})}function Es(n){let e={},t=[];for(let i of n)e[i.id]||(e[i.id]=!0,t.push(i));return t}function Ts(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function sr(n){return Object.keys(n).filter(e=>n[e]!==void 0).map(e=>[e,n[e]]).reduce((e,t)=>(e[t[0]]=Ts(t[1])?sr(t[1]):t[1],e),{})}function Cs(n){let e=[];for(let t of n)t.forEach(i=>e.push(i));return e}function Is(n){return c(this,null,function*(){let e=[];return RTCRtpReceiver.prototype.getStats?(e.push(...n.getReceivers().map(t=>t.getStats())),e.push(...n.getSenders().map(t=>t.getStats()))):e.push(n.getStats()),Promise.all(e).then(Cs).then(Es)})}function ys(n){let e=n.filter(Je("type","candidate-pair")).sort(vs("priority")).find(Bn(Je("nominated",!0),Je("selected",!0)));if(!e)return{totalRoundTripTime:0,currentRoundTripTime:0,bytesSent:0,bytesReceived:0};let t={totalRoundTripTime:e.totalRoundTripTime||0,currentRoundTripTime:e.currentRoundTripTime||0,bytesSent:e.bytesSent,bytesReceived:e.bytesReceived},i=n.find(Je("id",e.remoteCandidateId));i&&(t=Object.assign({},t,{remote:{type:i.candidateType,address:i.ip||i.address,port:i.port,protocol:i.protocol}}));let r=n.find(Je("id",e.localCandidateId));return r&&(t=Object.assign({},t,{local:{type:r.candidateType,address:r.ip||r.address,port:r.port,protocol:r.protocol,relayProtocol:r.relayProtocol,networkType:r.networkType}})),sr(t)}function Rs(n,e){let t=si("id",n),i=n.filter(Bn(Je("type","inbound-rtp"),Je("type","outbound-rtp")));y.browserName()==="Firefox"&&(i=Object.values(i.reduce((a,s)=>{if(!a[s.ssrc])a[s.ssrc]=s;else{let d=Object.assign({},a[s.ssrc],s),l=a[s.ssrc].isRemote?s:a[s.ssrc];d.id=l.id,d.type=l.type,delete d.isRemote,delete d.remoteId,a[d.ssrc]=d}return a},{})));let r={};if(y.browserName()==="Safari"){let a=n.filter(Je("type","track"));r=si("trackIdentifier",a)}return i.map(a=>{let s=Number(a.ssrc),d=a.mediaType||a.kind,l=a.trackId,u=a.type,g=a.codecId;if(y.browserName()==="Safari"){let se=/^.+_([\d]+)$/.exec(a.id);if(se&&(s=parseInt(se[1],10)),d=a.id.indexOf("Audio")>0?"audio":"video",e[s]){let ce=d+"-"+e[s];r[ce]&&(l=r[ce].id)}}if(!u||!s||!d)return null;let f=be(a,"framesDecoded"),W=be(a,"totalInterFrameDelay"),k=(be(a,"totalSquaredInterFrameDelay")-W*W/f)/f,Y={ssrc:s,type:u,kind:d,bytesReceived:be(a,"bytesReceived"),bytesSent:be(a,"bytesSent"),jitter:be(a,"jitter"),packetsLost:be(a,"packetsLost"),packetsReceived:be(a,"packetsReceived"),packetsSent:be(a,"packetsSent"),fractionLost:be(a,"fractionLost"),pliCount:be(a,"pliCount"),firCount:be(a,"firCount"),nackCount:be(a,"nackCount"),userId:e[s],interframeDelayVariance:k};if(g&&t[g]){let se=t[g];Y.clockRate=se.clockRate,Y.mimeType=se.mimeType}if(l&&t[l]){let se=t[l];Y.frameHeight=se.frameHeight,Y.frameWidth=se.frameWidth,Y.framesDecoded=se.framesDecoded,Y.framesReceived=se.framesReceived,Y.framesDropped=se.framesDropped}return sr(Y)}).filter(a=>!!a)}function bs(n,e){if(!e||!e.rtps||!n.rtps)return n;let t=si("ssrc",n.rtps),i=si("ssrc",e.rtps),r=(n.timestamp-e.timestamp)/1e3;return!t||!i||Object.keys(t).forEach(a=>{let s=t[a],d=i[a];if(!(!s||!d)){if(s.bytesReceived&&s.bytesReceived>d.bytesReceived&&(s.bandwidth=Math.round((s.bytesReceived-d.bytesReceived)/r)),s.bytesSent&&s.bytesSent>d.bytesSent&&(s.bandwidth=Math.round((s.bytesSent-d.bytesSent)/r)),s.packetsReceived)if(s.packetsReceived>d.packetsReceived||s.packetsLost>d.packetsLost){let l=s.packetsLost-d.packetsLost,u=s.packetsReceived-d.packetsReceived;s.packetLoss=parseFloat((100*l/(l+u)).toFixed(2))}else s.packetLoss=0;s.framesDropped&&d.framesDropped&&s.framesDropped>d.framesDropped&&(s.framesDroppedDelta=parseFloat(((s.framesDropped-d.framesDropped)/r).toFixed(0)))}}),n}function Lt(i,r){return c(this,arguments,function*(n,e,t={}){let a=yield Is(n),s={timestamp:Date.now(),transport:ys(a),rtps:Rs(a,t)};return e?bs(s,e):(yield T.delay(Ss),Lt(n,s,t))})}var oi=.8,st=class extends Q{constructor(e,t,i,r,a){super();this._remoteSDP={};this._remoteCandidates={};this._state=F.IDLE;this._isOpen=!1;this._remotePeerId=null;this._statInterval=null;this._settingsInterval=null;this._failedOnCreate=null;this._remoteStream=null;this._iceRestartTimeout=null;this._reconnectionTimeout=null;this._reconnectionPrevented=!1;this._fingerprint=null;this._neverConnected=!0;this._prevConsumerSettings={};this._lastNetworkStat={rtt:0,loss:0,date:0};this._remoteNetworkStat={rtt:0,loss:0};this._networkLimits={badNet:{loss:3,rtt:1e3},goodNet:{loss:.5,rtt:600}};if(this._signaling=i,this._mediaSource=r,this._participantId=e,this._isMaster=t,this._serverSettings=a,this.subscribe(this._signaling,fe.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,ye.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,ye.SOURCE_CHANGED,this._applySettings.bind(this)),this._pc=new RTCPeerConnection({iceServers:p.iceServers,iceTransportPolicy:p.forceRelayPolicy?"relay":"all"},{optional:[{googSuspendBelowMinBitrate:!1}]}),this._pc.onicecandidate=this._handleIceCandidate.bind(this),this._pc.ontrack=this._onAddTrack.bind(this),this._pc.oniceconnectionstatechange=this._onIceConnectionStateChange.bind(this),this._pc.onconnectionstatechange=this._onConnectionStateChange.bind(this),this._pc.onsignalingstatechange=this._onSignalingStateChange.bind(this),this._prevConsumerSettings={},this._isMaster){try{this._mediaSource.addTrackToPeerConnection(this._pc,!0),this._applySettings()}catch(s){m.log(_.ERROR,"addTrack-direct"),o.error("Unable to add media source tracks",s,{participantId:this._participantId}),this._failedOnCreate=s;return}this._createOffer(!1).catch(s=>{this._state===F.IDLE?this._failedOnCreate=s:this.close(s)})}this._startSettingsInterval(),this._startStatInterval()}getState(){return this._state}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==F.IDLE&&e!==F.CLOSED&&e!==F.FAILED&&this._startStatInterval()}open(e=null){return c(this,null,function*(){if(this._isOpen){o.warn("DirectTransport: Already opened",{participantId:this._participantId});return}if(this._failedOnCreate){this.close(this._failedOnCreate);return}if(o.debug("DirectTransport: Open transport",{participantId:this._participantId}),this._isOpen=!0,this._remotePeerId=e,!this._isMaster)try{this._mediaSource.addTrackToPeerConnection(this._pc,!0),this._applySettings()}catch(i){m.log(_.ERROR,"addTrack-direct"),o.error("DirectTransport: Unable to add media source tracks",i,{participantId:this._participantId}),this.close(i);return}this._setState(F.OPENED);let t=e;if(!e){let i=Object.keys(this._remoteSDP);t=i[i.length-1]}if(t&&this._remoteSDP[t])try{yield this._setRemoteDescription(t,this._remoteSDP[t])}catch(i){this.close();return}this._remoteSDP={},this._remoteCandidates={},this._triggerEvent(N.ACTIVE_PARTICIPANTS_NO_SIGNAL)})}updateSettings(e){ii(e,this._serverSettings)||(this._serverSettings=e,this._applySettings())}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}close(e){this._isOpen=!1,this._stopReconnection(),this._remoteStream&&(this._remoteStream.getTracks().forEach(t=>{t.stop(),this._triggerEvent(N.REMOTE_TRACK_REMOVED,this._remoteStream,t)}),this._remoteStream=null),this._stopStatInterval(),this._stopSettingsInterval(),this._pc&&(this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.oniceconnectionstatechange=null,this._pc.onconnectionstatechange=null,this._pc.onsignalingstatechange=null,this._pc.close()),this.unsubscribe(),e?(o.error("DirectTransport: Closed",e,{participantId:this._participantId}),this._setState(F.FAILED)):(o.debug("DirectTransport: Closed",{participantId:this._participantId}),this._setState(F.CLOSED)),this._triggerEvent(N.PEER_CONNECTION_CLOSED)}_setState(e){this._state!==e&&(o.debug(`DirectTransport: State changed to ${e}`,{participantId:this._participantId}),this._state=e,this._triggerEvent(N.STATE_CHANGED,e))}_onSignalingNotification(e){var t,i,r,a;switch(e.notification){case O.TRANSMITTED_DATA:this._handleTransmittedData(e);break;case O.SETTINGS_UPDATE:Object.assign(this._networkLimits.badNet,((t=e.settings)==null?void 0:t.badNet)||{}),Object.assign(this._networkLimits.goodNet,((i=e.settings)==null?void 0:i.goodNet)||{});break;case O.CUSTOM_DATA:e.data.hasOwnProperty("sdk")&&(this._remoteNetworkStat.rtt=((r=e.data.sdk)==null?void 0:r.rtt)||0,this._remoteNetworkStat.loss=((a=e.data.sdk)==null?void 0:a.loss)||0);break}}_handleTransmittedData(e){let t=e.data,i=T.getPeerIdString(e.peerId);T.composeMessageId(e)===this._participantId&&(t.candidate&&t.candidate.candidate?this._addIceCandidate(i,t.candidate).catch(this.close.bind(this)):t.sdp&&this._setRemoteDescription(i,t.sdp).catch(this.close.bind(this)))}_addIceCandidate(e,t){return c(this,null,function*(){if(this._isOpen&&(!this._remotePeerId||this._remotePeerId===e)&&this._pc&&this._pc.remoteDescription){o.debug("Add remote ice candidate",{participantId:this._participantId,candidate:t});try{yield this._pc.addIceCandidate(new RTCIceCandidate(t))}catch(i){throw m.log(_.ERROR,"addIceCandidate-direct"),o.error("Unable to add remote ice candidate",i,{participantId:this._participantId,candidate:t}),i}}else o.debug("Cache remote ice candidate",{participantId:this._participantId,candidate:t}),this._remoteCandidates[e]=this._remoteCandidates[e]||[],this._remoteCandidates[e].push(t)})}_setRemoteCandidates(e){return c(this,null,function*(){if(!this._remoteCandidates[e]){o.log(`No cached candidates found for peer ${e}`);return}let t=this._remoteCandidates[e];this._remoteCandidates[e]=[];for(let i of t)try{yield this._addIceCandidate(e,i)}catch(r){}})}_setRemoteDescription(e,t){return c(this,null,function*(){if(this._isOpen&&(!this._remotePeerId||this._remotePeerId===e)&&this._pc){o.debug("Add remote description",{participantId:this._participantId,sdp:t}),this._calcFingerprint(t.sdp);try{yield this._pc.setRemoteDescription(new RTCSessionDescription(t)),yield this._setRemoteCandidates(e)}catch(i){throw m.log(_.ERROR,"setRemoteDescription-direct"),o.error("Unable to set remote description",i,{participantId:this._participantId,sdp:t}),i}}else this._remoteSDP[e]=t})}_onAddTrack(e){o.debug("Added remote track",{participantId:this._participantId,kind:e.track.kind}),this._remoteStream?this._remoteStream.addTrack(e.track):(this._remoteStream=new MediaStream([e.track]),this._remoteStream.onremovetrack=t=>{this._triggerEvent(N.REMOTE_TRACK_REMOVED,this._remoteStream,t.track)}),this._triggerEvent(N.REMOTE_TRACK_ADDED,this._remoteStream,e.track)}_handleIceCandidate(e){return c(this,null,function*(){e.candidate&&this._signaling.ready&&(o.debug("Local ice candidate",{participantId:this._participantId,candidate:e.candidate}),yield this._signaling.sendCandidate(this._participantId,e.candidate))})}_onSignalingStateChange(){switch(o.debug(`DirectTransport: Signaling state changed to ${this._pc.signalingState}`,{participantId:this._participantId}),this._pc.signalingState){case"have-local-offer":let e=this._pc.localDescription;e?this._signaling.sendSdp(this._participantId,e).catch(this.close.bind(this)):this.close(new Error);break;case"have-remote-offer":this._createAnswer().catch(this.close.bind(this)).then(t=>c(this,null,function*(){return this._signaling.sendSdp(this._participantId,t)})).catch(this.close.bind(this));break}}_onIceConnectionStateChange(){switch(o.debug(`DirectTransport: Ice Connection state changed to ${this._pc.iceConnectionState}`,{participantId:this._participantId}),this._pc.iceConnectionState){case"checking":let e=this.getState();e===F.IDLE||e===F.OPENED?this._setState(F.CONNECTING):this._setState(F.RECONNECTING);break}}_onConnectionStateChange(){switch(o.debug(`DirectTransport: Connection state changed to ${this._pc.connectionState}`,{participantId:this._participantId}),m.log(_.ICE_CONNECTION_STATE,this._pc.connectionState),this._pc.connectionState){case"connected":this._neverConnected=!1,this._setState(F.CONNECTED),this._stopReconnection(),T.getPeerConnectionHostInfo(this._pc).then(e=>{e&&m.log(_.ICE_CONNECTION_TYPE,e.type)});break;case"failed":case"disconnected":this._reconnectionPrevented?this.close(new Error(`Ice connection ${this._pc.connectionState}`)):(this._setState(F.RECONNECTING),this._startReconnection());break;case"closed":this.close(new Error("Ice connection closed"));break}}_startReconnection(){this._reconnectionTimeout||this._iceRestartTimeout||(o.log("Waiting for reconnection...",{participantId:this._participantId}),this._reconnectionTimeout=window.setTimeout(()=>{this._reconnectionTimeout=null,this._neverConnected?this._requestTopologySwitch():this._startIceRestart()},p.transportConnectionWaitTime))}_requestTopologySwitch(){this._isMaster&&this._signaling.ready&&(o.log("Switch topology DIRECT to SERVER",{participantId:this._participantId}),this._signaling.switchTopology(Pe.SERVER))}_stopReconnection(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=null),this._iceRestartTimeout&&(clearTimeout(this._iceRestartTimeout),this._iceRestartTimeout=null)}_startIceRestart(){this._isMaster?(m.log(_.ICE_RESTART),o.log("Ice restart",{participantId:this._participantId}),this._createOffer(!0).catch(this.close.bind(this))):o.debug("Waiting for ice restart...",{participantId:this._participantId}),this._iceRestartTimeout=window.setTimeout(()=>{this._iceRestartTimeout=null,o.error("Ice restart failed",{participantId:this._participantId}),m.log(_.ERROR,"iceRestart-direct"),this._requestTopologySwitch()},p.iceRestartWaitTime)}_createOffer(e){return c(this,null,function*(){let t={iceRestart:e,offerToReceiveAudio:!0,offerToReceiveVideo:!0};return o.debug("Create offer",{participantId:this._participantId,options:t}),this._pc.createOffer(t).catch(i=>{throw o.error("Unable to create offer",i,{participantId:this._participantId}),m.log(_.ERROR,"createOffer-direct"),i}).then(i=>c(this,null,function*(){return o.debug("Created offer",{participantId:this._participantId,offer:i}),i=st._patchDescription(i),o.debug("Set local description",{participantId:this._participantId,offer:i}),this._calcFingerprint(i.sdp),this._pc.setLocalDescription(i).then(()=>this._pc.localDescription)})).catch(i=>{throw o.error("Unable to set local description",i,{participantId:this._participantId}),m.log(_.ERROR,"setLocalDescription-direct"),i})})}_createAnswer(){return c(this,null,function*(){return o.debug("Create answer",{participantId:this._participantId}),this._pc.createAnswer().catch(e=>{throw o.error("Unable to create answer",e,{participantId:this._participantId}),m.log(_.ERROR,"createAnswer-direct"),e}).then(e=>c(this,null,function*(){return o.debug("Created answer",{participantId:this._participantId,answer:e}),e=st._patchDescription(e),o.debug("Set local description",{participantId:this._participantId,answer:e}),this._calcFingerprint(e.sdp),this._pc.setLocalDescription(e)})).then(()=>this._pc.localDescription).catch(e=>{throw o.error("Unable to set local description",e,{participantId:this._participantId}),m.log(_.ERROR,"setLocalDescription-direct"),e})})}static _patchDescription(e){let t=!!y.baseChromeVersion();return e.sdp=T.patchSDP(e.sdp,p.preferH264&&y.canPreferH264(),y.isBrokenH264(),p.preferVP9,t&&p.audioNack),e}_onReplacedTrack(e){this._pc&&(this._pc.getSenders().forEach(t=>{t.track&&t.track.kind===e.kind&&(t.track.enabled=e.enabled,t.replaceTrack(e).catch(i=>{o.error("DirectTransport: Unable to replace track",i,{participantId:this._participantId}),m.log(_.ERROR,"replaceTrack-direct")}))}),this._applySettings())}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}Lt(this._pc,this._lastStat).then(t=>{this._lastStat=t;let i={inbound:{topology:Pe.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="inbound-rtp"?(r.userId=this._participantId,!0):!1)},outbound:{topology:Pe.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="outbound-rtp")}};this._checkBadNetwork(i),this._triggerEvent(N.REMOTE_DATA_STATS,i),this._statInterval=window.setTimeout(e,p.statisticsInterval)})};this._statInterval=window.setTimeout(e,p.statisticsInterval)}_stopStatInterval(){this._statInterval&&(window.clearTimeout(this._statInterval),this._statInterval=null)}_checkBadNetwork(e){if(!this._signaling.ready)return;let t=ce=>ce.rtt<=this._networkLimits.goodNet.rtt&&ce.loss<=this._networkLimits.goodNet.loss,i=ce=>ce.rtt>=this._networkLimits.badNet.rtt||ce.loss>=this._networkLimits.badNet.loss,r=Math.round(e.outbound.transport.currentRoundTripTime*1e3)||0,a=e.inbound.rtps.reduce((ce,dt)=>Math.max(ce,dt.packetLoss||0),0),s={rtt:this._lastNetworkStat.rtt*(1-oi)+r*oi,loss:this._lastNetworkStat.loss*(1-oi)+a*oi},d=i(s),l=t(s),u=i(this._remoteNetworkStat),g=t(this._remoteNetworkStat),f=i(this._lastNetworkStat),W=t(this._lastNetworkStat),Y=d||u?.2:l&&g?1:0,se=Date.now();if((f!==d||W!==l||se-this._lastNetworkStat.date>p.networkStatisticsInterval)&&(this._lastNetworkStat.date=Date.now(),this._signaling.customData({sdk:Object.assign({type:"bad-net"},s)},null).catch(ce=>{o.warn("Unable to send [bad-net]",ce)})),Y){let ce={};ce[this._participantId]=ce[""]=Y,this._triggerEvent(N.NETWORK_STATUS,ce)}this._lastNetworkStat.rtt=s.rtt,this._lastNetworkStat.loss=s.loss}_startSettingsInterval(){let e=2e3;if(this._settingsInterval)return;let t=()=>{if(!this._pc){this._stopSettingsInterval();return}this._applySettings(),this._settingsInterval=window.setTimeout(t,e)};this._settingsInterval=window.setTimeout(t,e)}_stopSettingsInterval(){this._settingsInterval&&(window.clearTimeout(this._settingsInterval),this._settingsInterval=null)}_calcFingerprint(e){let t=T.sdpFingerprint(e);this._fingerprint===null?this._fingerprint=t:(E.onFingerprintChange(this._fingerprint.xor(t).toString()),this._fingerprint=null)}_applySettings(){var t;let e=this._mediaSource.getMediaSettings().isScreenSharingEnabled?this._serverSettings.screenSharing:this._serverSettings.camera;e&&((t=this._pc)==null?void 0:t.connectionState)==="connected"&&(this._prevConsumerSettings=T.applySettings(this._pc,e,this._prevConsumerSettings))}};var Fn=(r=>(r.producerNotification="producerNotification",r.producerCommand="producerCommand",r.consumerScreenShare="consumerScreenShare",r.producerScreenShare="producerScreenShare",r))(Fn||{}),Ut=Fn;var ot=Ie(require("messagepack"));var or=class{constructor(){this.streamDescriptionByCompactId=new Map}getStreamDescription(e){return this.streamDescriptionByCompactId.get(e)}register(e,t){this.streamDescriptionByCompactId.set(e,t)}handleMessage(e){var a,s;let t=new Uint8Array(e),i=t[0],r=t.subarray(1);switch(i){case 1:let d=(0,ot.decode)(r);return Object.entries(d).forEach(([k,Y])=>{let se=Mt(k);this.streamDescriptionByCompactId.set(Y,se)}),null;case 2:case 4:let l=(0,ot.decode)(r),u=[];for(let k of l){let Y=this.getStreamDescription(k);Y&&u.push(Y.participantId)}return i===2?{type:"notification",notification:O.AUDIO_ACTIVITY,activeParticipants:u}:{type:"notification",notification:O.STALLED_ACTIVITY,stalledParticipants:u};case 3:let g=(0,ot.decode)(r);return{type:"notification",notification:O.SPEAKER_CHANGED,speaker:(a=this.getStreamDescription(g))==null?void 0:a.participantId};case 5:let f=(0,ot.decode)(r);return{type:"notification",notification:O.VIDEO_QUALITY_UPDATE,quality:{maxBitrate:f[0],maxDimension:f[1]}};case 6:let W=(0,ot.decode)(r),K={};for(let[k,Y]of Object.entries(W)){let se=(s=this.getStreamDescription(Number(k)))==null?void 0:s.participantId;se&&(K[se]=Y/100)}return{type:"notification",notification:O.NETWORK_STATUS,statuses:K};case 7:return this._createParticipantSourcesUpdateNotification(r);default:return o.debug("unsupported message type: "+i),null}}_createParticipantSourcesUpdateNotification(e){let t=(0,ot.decode)(e),i=[];for(let[r,a]of Object.entries(t)){let s=a[0],d=a[1],l=a[2],u;if(s!==null){if(u=this.getStreamDescription(s),!u){o.error(`could not uncompress participant ID ${s}`);continue}}else u=null;if(l===null){o.error("unexpected null sequenceNumber",r,a);continue}let g=ke.PARTICIPANT_AGNOSTIC_TRACK_PREFIX+"-"+r,f=d?d>>>0:null;i.push({participantStreamDescription:u,streamId:g,rtpTimestamp:f,sequenceNumber:l})}return{type:"notification",notification:O.PARTICIPANT_SOURCES_UPDATE,participantUpdateInfos:i}}};var Vn="videochat-epi",Ps=5e3,Ms=3e4,Bt=class extends Q{constructor(e,t){super();this._previousTimestamp=0;this._previousCallStatReportTimestamp=0;this._previousCallStatReport={nack_sent:0,nack_received:0,pli_sent:0,pli_received:0,fir_sent:0,fir_received:0,frames_dropped:0,jitter_video:0,jitter_audio:0,interframe_delay_variance:0};this._signaling=t,this.subscribe(e,N.REMOTE_DATA_STATS,this._handleStats.bind(this))}destroy(){this.unsubscribe()}static getEstimatedPerformanceIndex(){try{let e=parseInt(localStorage.getItem(Vn)||"",10);return isNaN(e)?0:e}catch(e){return 0}}_handleStats(e){return c(this,null,function*(){if(!e.inbound||!e.inbound.rtps)return;let t=Date.now();p.perfStatReportEnabled&&this._previousTimestamp+Ps<=t&&(yield this.reportPerfStats(e),this._previousTimestamp=t),p.callStatReportEnabled&&this._previousCallStatReportTimestamp+Ms<=t&&(this._reportCallStats(e),this._previousCallStatReportTimestamp=t)})}reportPerfStats(e){return c(this,null,function*(){let t=e.inbound.rtps.reduce((i,r)=>(r.kind==="video"&&(i.framesDecoded+=r.framesDecoded||0,i.framesReceived+=r.framesReceived||0),i),{framesDecoded:0,framesReceived:0});if(t.framesDecoded)try{let i=yield this._signaling.reportPerfStat(t);localStorage.setItem(Vn,i.estimatedPerformanceIndex)}catch(i){}})}_reportCallStats(e){let t={nack_received:0,pli_received:0,fir_received:0,frames_dropped:0,jitter_video:0,jitter_audio:0,interframe_delay_variance:0,nack_sent:0,pli_sent:0,fir_sent:0,inbound_video_count:0,inbound_audio_count:0};e.inbound.rtps.reduce((r,a)=>(a.kind==="video"?(a.jitter&&(r.jitter_video=r.jitter_video*r.inbound_video_count/(r.inbound_video_count+1)+a.jitter*1e3/(r.inbound_video_count+1),r.interframe_delay_variance=r.interframe_delay_variance*r.inbound_video_count/(r.inbound_video_count+1)+a.interframeDelayVariance*1e6/(r.inbound_video_count+1),r.inbound_video_count++),r.frames_dropped+=a.framesDropped,r.nack_received+=a.nackCount||0,r.pli_received+=a.pliCount||0,r.fir_received+=a.firCount||0):a.jitter&&(r.jitter_audio=r.jitter_audio*r.inbound_audio_count/(r.inbound_audio_count+1)+a.jitter*1e3/(r.inbound_audio_count+1),r.inbound_audio_count++),r),t),e.outbound.rtps.reduce((r,a)=>(a.kind==="video"&&(r.nack_sent+=a.nackCount||0,r.pli_sent+=a.pliCount||0,r.fir_sent+=a.firCount||0),r),t);let i={nack_sent:t.nack_sent-this._previousCallStatReport.nack_sent,nack_received:t.nack_received-this._previousCallStatReport.nack_received,pli_sent:t.pli_sent-this._previousCallStatReport.pli_sent,pli_received:t.pli_received-this._previousCallStatReport.pli_received,fir_sent:t.fir_sent-this._previousCallStatReport.fir_sent,fir_received:t.fir_received-this._previousCallStatReport.fir_received,frames_dropped:t.frames_dropped-this._previousCallStatReport.frames_dropped};t.jitter_video&&(i.jitter_video=t.jitter_video),t.jitter_audio&&(i.jitter_audio=t.jitter_audio),t.interframe_delay_variance&&(i.interframe_delay_variance=t.interframe_delay_variance),m.logCustom("callStat",i),this._previousCallStatReport=t}};var As=90,Ds=4294967295,De=class extends Q{constructor(e,t,i){super();this._pc=null;this._producerNotification=null;this._producerCommand=null;this._producerScreen=null;this._consumerScreen=null;this._isOpen=!1;this._reconnectionPrevented=!1;this._state=F.IDLE;this._statInterval=null;this._settingsInterval=null;this._statBytes={};this._ssrcMap={};this._producerOfferIsProcessing=!1;this._producerNextOffer=null;this._prevConsumerSettings={};this._captureSender=null;this._captureReceiver=null;this._participantIdRegistry=null;this._disabledSenders=new Set;this._rtpReceiversByStreamId={};this._producerSessionId="";this._signaling=e,this._mediaSource=t,this.subscribe(this._signaling,fe.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,ye.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,ye.SOURCE_CHANGED,this._applyConsumerSettings.bind(this)),this.subscribe(this._mediaSource,ye.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._perfStatReporter=new Bt(this,e),this._serverSettings=i,o.debug("ServerTransport: Created")}getState(){return this._state||F.IDLE}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==F.IDLE&&e!==F.CLOSED&&e!==F.FAILED&&this._startStatInterval()}open(){if(this._isOpen){o.log("ServerTransport: Already opened connections");return}this._isOpen=!0,this._openConnection()}close(e){this._isOpen=!1,this._closeConnection(),this.unsubscribe(),e?(o.error("ServerTransport: Closed",e),this._setState(F.FAILED)):(o.debug("ServerTransport: Closed"),this._setState(F.CLOSED))}removeParticipant(e){var t;(t=this._captureReceiver)==null||t.close(e)}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}updateSettings(e){ii(e,this._serverSettings)||(this._serverSettings=e,this._applyConsumerSettings())}_closeConnection(){this._stopStatInterval(),this._stopSettingsInterval(),this._removeCaptureSender(),this._removeCaptureReceiver(),this._pc&&(this._rtpReceiversByStreamId={},this._disabledSenders.forEach(e=>{var t;return(t=e.track)==null?void 0:t.stop()}),this._disabledSenders.clear(),this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.onsignalingstatechange=null,this._participantIdRegistry=null,De._closeDataChannel(this._producerNotification),De._closeDataChannel(this._producerCommand),De._closeDataChannel(this._producerScreen),De._closeDataChannel(this._consumerScreen),this._pc.close(),this._pc=null,this._producerOfferIsProcessing=!1,this._producerNextOffer=null),this._triggerEvent(N.PEER_CONNECTION_CLOSED)}static _closeDataChannel(e){e&&(e.onopen=null,e.onmessage=null,e.onerror=null,e.close())}_createDataChannel(e,t,i){o.debug(`[${t}] data channel opening`);let r=e.createDataChannel(t,{ordered:!0});r.onopen=()=>{o.debug(`[${t}] data channel opened`),r.onerror=a=>{o.error(`[${t}] data channel error`,a)},i(r)}}_openConnection(e=!1){o.debug("ServerTransport: Open single connection");let t={};y.baseChromeVersion()&&(t.sdpSemantics=De._isUnifiedPlanSupported()?"unified-plan":"plan-b"),this._pc=new RTCPeerConnection(t,{optional:[{googSuspendBelowMinBitrate:!1}]}),this._pc.ontrack=this._onAddTrack.bind(this,this._pc),this._pc.onconnectionstatechange=T.throttle(i=>{this._pc&&this._onConnectionStateChange(this._pc,i)},500),this._pc.onsignalingstatechange=De._onSignalingStateChange.bind(this,this._pc),p.producerNotificationDataChannel&&this._createDataChannel(this._pc,Ut.producerNotification,i=>{this._producerNotification=i,this._producerNotification.binaryType="arraybuffer",this._participantIdRegistry=new or,this._signaling.setParticipantIdRegistry(this._participantIdRegistry),this._signaling.setProducerNotificationDataChannel(i)}),p.producerCommandDataChannel&&this._createDataChannel(this._pc,Ut.producerCommand,i=>{this._producerCommand=i,this._signaling.setProducerCommandDataChannel(i)}),p.producerScreenDataChannel&&this._createDataChannel(this._pc,Ut.producerScreenShare,i=>{this._producerScreen=i,this._producerScreen.binaryType="arraybuffer",this._createCaptureReceiver()});try{this._mediaSource.addTrackToPeerConnection(this._pc),this._prevConsumerSettings={},this._applyConsumerSettings()}catch(i){o.error("ServerTransport: Unable to add media source tracks",i),m.log(_.ERROR,"addTrack-single"),this.close(i);return}p.consumerScreenDataChannel&&this._createDataChannel(this._pc,Ut.consumerScreenShare,i=>{this._consumerScreen=i,this._consumerScreen.binaryType="arraybuffer";let r=this._mediaSource.getScreenTrack();r&&this._createCaptureSender(r)}),e||this._allocateConsumer(),this._setState(F.OPENED),this._startStatInterval(),this._startSettingsInterval()}_reconnect(){this.getState()!==F.OPENED&&(this._setState(F.RECONNECTING),this._closeConnection(),this._openConnection(!0))}_signalActiveParticipants(e){this._triggerEvent(N.SIGNALLED_ACTIVE_PARTICIPANTS,e)}_signalStalledParticipants(e){this._triggerEvent(N.SIGNALLED_STALLED_PARTICIPANTS,e)}_signalSpeakerChanged(e){this._triggerEvent(N.SIGNALLED_SPEAKER_CHANGED,e)}_signalNetworkStatus(e){this._triggerEvent(N.NETWORK_STATUS,e)}_updateSSRCMap(e){e&&e.sdp.split(`
12
- `).forEach(t=>{let i=`a=ssrc:([0-9]+) label:(audio|video)-((?:[ug]?[\\d]+)|(?:mix)|(?:${ke.PARTICIPANT_AGNOSTIC_TRACK_PREFIX}-[0-9]+))`,r=new RegExp(i).exec(t);r&&(this._ssrcMap[r[1]]=r[3])})}_createCaptureSender(e){!e||!p.consumerScreenDataChannel||!this._consumerScreen||!this._mediaSource.getMediaSettings().isScreenSharingEnabled||(this._captureSender&&this._removeCaptureSender(),this._captureSender=new Et(e,this._consumerScreen))}_removeCaptureSender(){var e;(e=this._captureSender)==null||e.destroy(),this._captureSender=null}_createCaptureReceiver(){!p.producerScreenDataChannel||!this._producerScreen||!this._participantIdRegistry||(this._captureReceiver&&this._removeCaptureReceiver(),this._captureReceiver=new nt(null,this._producerScreen,this._participantIdRegistry,(e,t)=>{this._triggerEvent(N.REMOTE_STREAM_SECOND,e,t)},e=>{this._triggerEvent(N.REMOTE_STREAM_SECOND,e,null)}))}replayShare(e,t){var i;!this._participantIdRegistry||((i=this._captureReceiver)==null||i.destroy(),this._captureReceiver=new nt(t,e,this._participantIdRegistry,(r,a)=>{this._triggerEvent(N.REMOTE_STREAM_SECOND,r,a)},r=>{this._triggerEvent(N.REMOTE_STREAM_SECOND,r,null)}))}_removeCaptureReceiver(){var e;(e=this._captureReceiver)==null||e.destroy(),this._captureReceiver=null}_applyConsumerSettings(){let e=this._mediaSource.getMediaSettings().isScreenSharingEnabled&&!p.consumerScreenDataChannel?this._serverSettings.screenSharing:this._serverSettings.camera;if(e&&this._pc){let t=[];this._pc.getSenders().forEach(i=>{if(!i.track||i.track.kind!==me.video)return;let r=!this._disabledSenders.has(i),a=e.maxDimension!==0;if(r&&!a){o.log("Disabling video upload"),this._disabledSenders.add(i),i.replaceTrack(y.getBlackMediaTrack()).catch(d=>{o.error("Could not disable video upload",d)});return}let s=this._mediaSource.getSendVideoTrack();if(!r&&a&&s){o.log("Enabling video upload"),this._disabledSenders.delete(i);let d=i.track;d.enabled=s.enabled,i.replaceTrack(s).then(()=>d.stop()).catch(l=>{o.error("Could not enable video upload",l)})}T.applyVideoTrackSettings(e,i,s!=null?s:i.track,this._prevConsumerSettings,t)}),this._prevConsumerSettings=t}}_onScreenSharingStatus(e){e.track?this._createCaptureSender(e.track):this._removeCaptureSender()}_setState(e){this._state!==e&&(this._state=e,this._triggerEvent(N.STATE_CHANGED,e))}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}this._collectStat().then(t=>{this._reportStats(t),this._detectStaleTracks(t)}).catch(()=>{}),this._statInterval=window.setTimeout(e,p.statisticsInterval)};this._statInterval=window.setTimeout(e,p.statisticsInterval)}_stopStatInterval(){this._statInterval&&(window.clearTimeout(this._statInterval),this._statInterval=null),this._statBytes={}}_startSettingsInterval(){let e=2e3;if(this._settingsInterval)return;let t=()=>{if(!this._pc){this._stopSettingsInterval();return}this._applyConsumerSettings(),this._settingsInterval=window.setTimeout(t,e)};this._settingsInterval=window.setTimeout(t,e)}_stopSettingsInterval(){this._settingsInterval&&(window.clearTimeout(this._settingsInterval),this._settingsInterval=null)}_collectStat(){return c(this,null,function*(){if(!this._pc)return Promise.reject();let e=yield Lt(this._pc,this._lastStat,this._ssrcMap);return this._lastStat=e,e})}_reportStats(e){this._triggerEvent(N.REMOTE_DATA_STATS,{inbound:{topology:Pe.SERVER,transport:e.transport,rtps:e.rtps.filter(t=>t.type==="inbound-rtp")},outbound:{topology:Pe.SERVER,transport:e.transport,rtps:e.rtps.filter(t=>t.type==="outbound-rtp")}})}_detectStaleTracks(e){let t=e.rtps.find(s=>s.type==="inbound-rtp"&&s.kind==="audio"&&this._ssrcMap[s.ssrc]==="mix");if(!t)return;let i=ke.AUDIO_MIX,r=this._statBytes[i],a=!1;if(r){let s=t.bytesReceived-r.bytesReceived;s>=0&&s<=5&&(a=!0),r.stalled!==a&&this._triggerEvent(N.REMOTE_ALL_STALL,a)}this._statBytes[i]={bytesReceived:t.bytesReceived,stalled:a}}_allocateConsumer(){if(!this._signaling.ready)return;let e={estimatedPerformanceIndex:Bt.getEstimatedPerformanceIndex(),audioMix:!0,consumerUpdate:!0,producerNotificationDataChannelVersion:p.producerNotificationDataChannel?6:0,producerCommandDataChannelVersion:p.producerCommandDataChannel?2:0,consumerScreenDataChannelVersion:p.consumerScreenDataChannel?1:0,producerScreenDataChannelVersion:p.producerScreenDataChannel?1:0,onDemandTracks:!0,unifiedPlan:De._isUnifiedPlanSupported(),singleSession:!0,videoTracksCount:p.videoTracksCount};this._signaling.allocateConsumer(null,e)}_acceptProducer(e){return c(this,null,function*(){if(this._producerOfferIsProcessing){this._producerNextOffer=e,o.debug("[single] wait until other remote offer is processed");return}this._producerOfferIsProcessing=!0;let t=new RTCSessionDescription({type:"offer",sdp:e});if(o.debug("[single] set remote offer",{offer:t}),!this._pc)throw new Error("Interrupt allocation");this._pc.setRemoteDescription(t).catch(i=>{throw o.error("[single] unable to set remote offer",i),m.log(_.ERROR,"setRemoteDescription-single"),i}).then(()=>c(this,null,function*(){if(o.debug("[single] create local answer"),!this._pc)throw new Error("Interrupt allocation");return this._pc.createAnswer()})).catch(i=>{throw o.error("[single] unable to create answer",i),m.log(_.ERROR,"createAnswer-single"),i}).then(i=>(i.sdp=T.patchSDP(i.sdp,!1,y.isBrokenH264(),!1),i)).then(i=>c(this,null,function*(){if(o.debug("[single] set local answer",{answer:i}),!this._pc)throw new Error("Interrupt allocation");return yield this._pc.setLocalDescription(i),i})).catch(i=>{throw o.error("[single] unable to set local answer",i),m.log(_.ERROR,"setLocalDescription-single"),i}).then(i=>c(this,null,function*(){o.debug("[single] transmit local answer",{answer:i}),this._updateSSRCMap(t),yield this._signaling.acceptProducer(i,Object.keys(this._ssrcMap)),o.debug("[single] remote offer has been processed")})).catch(i=>{o.warn("[single] unable to send local answer",i),m.log(_.ERROR,"acceptProducer")}).then(()=>c(this,null,function*(){if(this._producerOfferIsProcessing=!1,this._producerNextOffer){o.debug("[single] there is other unprocessed remote offer, process it");let i=this._producerNextOffer;return this._producerNextOffer=null,this._acceptProducer(i)}})).catch(i=>this.close(i))})}_onSignalingNotification(e){return c(this,null,function*(){if(!!this._isOpen)switch(e.notification){case O.PRODUCER_UPDATED:yield this._onProducerUpdated(e);break;case O.REALLOC_CON:this._reconnect();break;case O.AUDIO_ACTIVITY:this._signalActiveParticipants(e.activeParticipants);break;case O.SPEAKER_CHANGED:this._signalSpeakerChanged(e.speaker);break;case O.STALLED_ACTIVITY:this._signalStalledParticipants(e.stalledParticipants);break;case O.NETWORK_STATUS:this._signalNetworkStatus(e.statuses);break}})}_onProducerUpdated(e){return c(this,null,function*(){this._producerSessionId&&this._producerSessionId!==e.sessionId&&this._reconnect(),p.breakVideoPayloadTypes&&(o.log("test mode enabled, video switched off"),this._signaling.requestTestMode("breakVideoPayloadTypes")),this._producerSessionId=e.sessionId,yield this._acceptProducer(e.description)})}_onAddTrack(e,t){o.debug("[single] remote track (added)",{track:t.track});let i=t.streams[0];i?(i.onremovetrack||(i.onremovetrack=a=>{this._triggerEvent(N.REMOTE_TRACK_REMOVED,i.id,i,a.track)}),i.getTracks().find(a=>a.id===t.track.id)||i.addTrack(t.track),this._rtpReceiversByStreamId[i.id]=t.receiver,this._triggerEvent(N.REMOTE_TRACK_ADDED,i.id,i,t.track)):o.error("[single] unable to get media stream from track event")}static _onSignalingStateChange(e,t){o.debug("[single] signaling state changed",{state:e.signalingState},t)}_onConnectionStateChange(e,t){switch(o.debug("[single] connection state changed",{state:e.connectionState},t),m.log(_.ICE_CONNECTION_STATE,e.connectionState),e.connectionState){case"failed":this._reconnectionPrevented?this.close(new Error("Ice connection failed")):this._reconnect();break;case"connecting":let i=this.getState();i===F.IDLE||i===F.OPENED?this._setState(F.CONNECTING):e.iceConnectionState==="checking"&&this._setState(F.RECONNECTING);break;case"disconnected":this._reconnectionPrevented?this.close(new Error("Ice connection disconnected")):this._setState(F.RECONNECTING);break;case"connected":this._setState(F.CONNECTED),T.getPeerConnectionHostInfo(e).then(r=>{r&&m.log(_.ICE_CONNECTION_TYPE,r.type)});break}}_onReplacedTrack(e,t){this._pc&&(p.consumerScreenDataChannel&&t&&(e=t),this._pc.getSenders().forEach(i=>{i.track&&i.track.kind===e.kind&&!this._disabledSenders.has(i)&&(i.track.enabled=e.enabled,i.replaceTrack(e).catch(r=>{o.error("ServerTransport: Unable to replace track",r),m.log(_.ERROR,"replaceTrack-single")}))})),this._applyConsumerSettings()}static _isUnifiedPlanSupported(){let e=y.baseChromeVersion();return e?p.isUnifiedPlanSupported("Chrome",e):p.isUnifiedPlanSupported(y.browserName(),y.browserVersion())}getStreamWaitingTimeMs(e,t){if(!this._pc)return m.log(_.PAT_WAITING_TIME_ERROR,"noConnection"),o.error("Cannot get stream waiting time, peer connection is not initialized"),0;let i=this._rtpReceiversByStreamId[e];if(!i)return m.log(_.PAT_WAITING_TIME_ERROR,"noReceiver"),o.error(`Cannot get stream waiting time, cannot find RTP receiver by stream ID: ${e}`),0;let r=i.getSynchronizationSources();if(!r||!r.length)return o.log(`Cannot get stream waiting time, ${e} receiver has no synchronization sources`),0;let s=r[0].rtpTimestamp;if(!Number.isInteger(s))return m.log(_.PAT_WAITING_TIME_ERROR,"timestampNotInteger"),o.error(`Cannot get stream waiting time, ${e} receiver's RTP timestamp is not an integer: ${s}`),0;let d=t-s&Ds,l=Math.ceil(d/As);return Math.min(100,Math.max(0,l))}};var N=(k=>(k.REMOTE_TRACK_ADDED="REMOTE_TRACK_ADDED",k.REMOTE_TRACK_REMOVED="REMOTE_TRACK_REMOVED",k.REMOTE_STREAM_SECOND="REMOTE_STREAM_SECOND",k.REMOTE_ALL_STALL="REMOTE_ALL_STALL",k.REMOTE_DATA_STATS="REMOTE_DATA_STATS",k.STATE_CHANGED="STATE_CHANGED",k.LOCAL_STATE_CHANGED="LOCAL_STATE_CHANGED",k.SIGNALLED_ACTIVE_PARTICIPANTS="SIGNALLED_ACTIVE_PARTICIPANTS",k.ACTIVE_PARTICIPANTS_NO_SIGNAL="ACTIVE_PARTICIPANTS_NO_SIGNAL",k.SIGNALLED_SPEAKER_CHANGED="SIGNALLED_SPEAKER_CHANGED",k.SIGNALLED_STALLED_PARTICIPANTS="SIGNALLED_STALLED_PARTICIPANTS",k.TOPOLOGY_CHANGED="TOPOLOGY_CHANGED",k.NETWORK_STATUS="NETWORK_STATUS",k.PEER_CONNECTION_CLOSED="PEER_CONNECTION_CLOSED",k))(N||{}),F=(d=>(d.IDLE="IDLE",d.OPENED="OPENED",d.CONNECTING="CONNECTING",d.RECONNECTING="RECONNECTING",d.CONNECTED="CONNECTED",d.CLOSED="CLOSED",d.FAILED="FAILED",d))(F||{}),Pe=(t=>(t.DIRECT="DIRECT",t.SERVER="SERVER",t))(Pe||{}),cr=class extends Q{constructor(e,t,i,r){super();this._allocated=[];this._opened=[];this._directTransport=null;this._serverTransport=null;this._dtListeners=[];this._stListeners=[];this._states={};this._localState="IDLE";this._signaling=t,this._mediaSource=i,this._topology=e,this._serverSettings=r,this.subscribe(this._signaling,fe.NOTIFICATION,this._onSignalingNotification.bind(this)),e==="SERVER"&&(this._serverTransport=this._createServerTransport())}updateSettings(e){this._serverSettings=e,this._directTransport&&this._directTransport.updateSettings(e),this._serverTransport&&this._serverTransport.updateSettings(e)}updateStatisticsInterval(){this._directTransport&&this._directTransport.updateStatisticsInterval(),this._serverTransport&&this._serverTransport.updateStatisticsInterval()}allocate(e,t=!1){if(this._allocated.indexOf(e)!==-1){o.warn(`The participant [${e}] has already had allocated transport`);return}this._allocated.push(e),this._topology==="DIRECT"&&!this._directTransport&&(this._directTransport=this._createDirectTransport(e,t)),this._topology==="SERVER"&&!this._serverTransport&&(this._serverTransport=this._createServerTransport())}open(e,t=null){let i=!1;for(let r of e){if(this._opened.indexOf(r)!==-1){o.warn(`The participant [${r}] has already had opened transport`);continue}if(this._allocated.indexOf(r)===-1){o.warn(`The participant [${r}] has no allocated transport`);continue}this._opened.push(r),i=!0}!i||(this._topology==="DIRECT"&&this._directTransport&&this._directTransport.open(t),this._topology==="SERVER"&&this._serverTransport&&(this._serverTransport.open(),this._setStates(e,this._serverTransport.getState()),this._setLocalState(this._serverTransport.getState())),o.debug("The transport has been opened",e))}close(e){var r;let t=this._allocated.indexOf(e),i=this._opened.indexOf(e);t<0&&o.warn(`The participant [${e}] transport has already deallocated`),this._topology==="DIRECT"&&this._directTransport&&(this._directTransport.close(),this._directTransport=null),this._topology==="SERVER"&&((r=this._serverTransport)==null||r.removeParticipant(e),this._setState(e,"CLOSED")),i>=0&&this._opened.splice(i,1),t>=0&&this._allocated.splice(t,1)}destroy(){this.unsubscribe(),this._dtListeners&&this._dtListeners.forEach(e=>{e.dispose()}),this._stListeners&&this._stListeners.forEach(e=>{e.dispose()}),this._directTransport&&(this._directTransport.close(),this._directTransport=null),this._serverTransport&&(this._serverTransport.close(),this._serverTransport=null),this._allocated=[],this._opened=[]}getTopology(){return this._topology}isAllocated(e){return this._allocated.indexOf(e)>=0}allocated(){return this._allocated.slice()}opened(){return this._opened.slice()}_setStates(e,t){let i=e.filter(r=>this._states[r]!==t?(this._states[r]=t,!0):!1);i.length&&this._triggerEvent("STATE_CHANGED",i,t)}_setState(e,t){this._states[e]!==t&&(this._states[e]=t,this._triggerEvent("STATE_CHANGED",[e],t))}_setLocalState(e){this._localState!==e&&(this._localState=e,this._triggerEvent("LOCAL_STATE_CHANGED",e))}_onSignalingNotification(e){if(e.notification===O.TOPOLOGY_CHANGED)return this._onTopologyChanged(e);if(e.notification===O.RECORD_STARTED)return this._onRecordStarted(e)}_onTopologyChanged(e){var t;if(e.topology!==this._topology){if(o.log(`Topology changed ${this._topology} -> ${e.topology}`),m.log(_.TOPOLOGY_CHANGE_REQUESTED,e.topology),this._topology=e.topology,this._topology==="SERVER"&&(this._serverTransport?this._serverTransport.allowRestart():(this._serverTransport=this._createServerTransport(),this._opened.length>0&&((t=this._directTransport)==null||t.preventRestart(),this._serverTransport.open()))),this._topology==="DIRECT"){let i=e.offerTo||[],r=e.offerToTypes||[],a=i.length&&r.length?T.composeId(i[0],r[0]):null;if(this._serverTransport&&this._serverTransport.preventRestart(),!this._allocated||this._allocated.length===0){o.error("Topology changed to DIRECT, but the list of allocated participants is empty");return}this._allocated.length>1&&o.warn("Topology changed to DIRECT, but the allocated participants count more then one");let s=this._allocated[0];if(this._directTransport)this._directTransport.allowRestart();else{let d=a===s;this._directTransport=this._createDirectTransport(s,d)}this._opened.indexOf(s)>=0&&this._directTransport.open()}this._triggerEvent("TOPOLOGY_CHANGED",this._topology)}}_onRecordStarted(e){this._serverTransport&&this._serverTransport.open()}_createDirectTransport(e,t=!1){let i=new st(e,t,this._signaling,this._mediaSource,this._serverSettings);return this._setLocalNoiseSuppression(!0),this._dtListeners&&this._dtListeners.length>0&&o.warn(`The list of direct listeners for the participant [${e}] is not empty`),this._dtListeners=[],this._dtListeners.push(i.addEventListener("REMOTE_TRACK_ADDED",this._onDirectRemoteTrackAdded.bind(this,e)),i.addEventListener("REMOTE_TRACK_REMOVED",this._onDirectRemoteTrackRemoved.bind(this,e)),i.addEventListener("REMOTE_DATA_STATS",this._onDirectRemoteDataStats.bind(this)),i.addEventListener("STATE_CHANGED",this._onDirectTransportChanged.bind(this,e)),i.addEventListener("NETWORK_STATUS",this._onTransportNetworkStatus.bind(this)),i.addEventListener("PEER_CONNECTION_CLOSED",this._onPeerConnectionClosed.bind(this,"DIRECT"))),i}_createServerTransport(){let e=new De(this._signaling,this._mediaSource,this._serverSettings);return this._setLocalNoiseSuppression(!1),this._stListeners&&this._stListeners.length>0&&o.warn("The list of server transport listeners is not empty"),this._stListeners=[],this._stListeners.push(e.addEventListener("REMOTE_TRACK_ADDED",this._onServerRemoteTrackAdded.bind(this)),e.addEventListener("REMOTE_TRACK_REMOVED",this._onServerRemoteTrackRemoved.bind(this)),e.addEventListener("REMOTE_ALL_STALL",this._onServerRemoteAllStall.bind(this)),e.addEventListener("REMOTE_DATA_STATS",this._onServerRemoteDataStats.bind(this)),e.addEventListener("STATE_CHANGED",this._onServerTransportChanged.bind(this)),e.addEventListener("ACTIVE_PARTICIPANTS_NO_SIGNAL",this._onTransportActiveParticipantsNoSignal.bind(this)),e.addEventListener("SIGNALLED_ACTIVE_PARTICIPANTS",this._onTransportActiveParticipants.bind(this)),e.addEventListener("SIGNALLED_SPEAKER_CHANGED",this._onTransportSpeakerChanged.bind(this)),e.addEventListener("SIGNALLED_STALLED_PARTICIPANTS",this._onTransportStalledParticipants.bind(this)),e.addEventListener("NETWORK_STATUS",this._onTransportNetworkStatus.bind(this)),e.addEventListener("REMOTE_STREAM_SECOND",this._onRemoteStreamSecond.bind(this)),e.addEventListener("PEER_CONNECTION_CLOSED",this._onPeerConnectionClosed.bind(this,"SERVER"))),e}_releaseDirectTransport(e){this._directTransport&&(e&&this._directTransport.close(),this._directTransport=null),this._dtListeners&&(this._dtListeners.forEach(t=>{t.dispose()}),this._dtListeners=[])}_releaseServerTransport(e){this._serverTransport&&(e&&this._serverTransport.close(),this._serverTransport=null),this._stListeners&&(this._stListeners.forEach(t=>{t.dispose()}),this._stListeners=[])}_setLocalNoiseSuppression(e){var t;p.noiseSuppression!==e&&(p.noiseSuppression=e,(t=this._mediaSource)==null||t.updateNoiseSuppression())}_onDirectTransportChanged(e,t){if(t==="CONNECTED"&&this._topology==="DIRECT"&&this._releaseServerTransport(!0),(t==="CLOSED"||t==="FAILED")&&(this._releaseDirectTransport(!1),this._topology==="DIRECT")){let i=this._opened.indexOf(e);i>=0&&this._opened.splice(i,1);let r=this._allocated.indexOf(e);r>=0&&this._allocated.splice(r,1)}this._topology==="DIRECT"&&(this._setState(e,t),this._setLocalState(t))}_onServerTransportChanged(e){let t=this._opened.slice();e==="CONNECTED"&&this._topology==="SERVER"&&this._releaseDirectTransport(!0),(e==="CLOSED"||e==="FAILED")&&(this._releaseServerTransport(!1),this._topology==="SERVER"&&(this._allocated=[],this._opened=[])),this._topology==="SERVER"&&(this._setStates(t,e),this._setLocalState(e))}_onTransportActiveParticipantsNoSignal(){this._triggerEvent("ACTIVE_PARTICIPANTS_NO_SIGNAL")}_onTransportActiveParticipants(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_ACTIVE_PARTICIPANTS",e)}_onTransportStalledParticipants(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_STALLED_PARTICIPANTS",e)}_onTransportSpeakerChanged(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_SPEAKER_CHANGED",e)}_onTransportNetworkStatus(e){this._triggerEvent("NETWORK_STATUS",e)}_onRemoteStreamSecond(e,t){this._triggerEvent("REMOTE_STREAM_SECOND",e,t)}_onPeerConnectionClosed(e){this._triggerEvent("PEER_CONNECTION_CLOSED",e)}_onServerRemoteAllStall(e){this._topology==="SERVER"&&this._triggerEvent("REMOTE_ALL_STALL",e)}_onServerRemoteDataStats(e){this._triggerEvent("REMOTE_DATA_STATS",e)}_onDirectRemoteTrackAdded(e,t,i){this._triggerEvent("REMOTE_TRACK_ADDED",e,t,i)}_onDirectRemoteTrackRemoved(e,t,i){this._triggerEvent("REMOTE_TRACK_REMOVED",e,t,i)}_onDirectRemoteDataStats(e){this._triggerEvent("REMOTE_DATA_STATS",e)}_onServerRemoteTrackAdded(e,t,i){this._triggerEvent("REMOTE_TRACK_ADDED",e,t,i)}_onServerRemoteTrackRemoved(e,t,i){this._triggerEvent("REMOTE_TRACK_REMOVED",e,t,i)}getStreamWaitingTimeMs(e,t){return this._topology!=="SERVER"?(m.log(_.PAT_WAITING_TIME_ERROR,"wrongTopology"),o.error(`Cannot get stream waiting time, incorrect topology: ${this._topology}`),0):this._serverTransport?this._serverTransport.getStreamWaitingTimeMs(e,t):(m.log(_.PAT_WAITING_TIME_ERROR,"noTransport"),o.error("Cannot get stream waiting time, server transport is not initialized"),0)}replayShare(e,t){var i;(i=this._serverTransport)==null||i.replayShare(e,t)}};var ct=(e=>(e.VOLUMES_DETECTED="VOLUMES_DETECTED",e))(ct||{}),dr=class extends Q{constructor(e){super();this._detector=null;this._interval=null;this.subscribe(e,N.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(e,N.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(e,N.SIGNALLED_ACTIVE_PARTICIPANTS,this._onSignalledActiveParticipants.bind(this)),this.subscribe(e,N.ACTIVE_PARTICIPANTS_NO_SIGNAL,this._onActiveParticipantsNoSignal.bind(this))}destroy(){var e;this._interval&&(window.clearTimeout(this._interval),this._interval=null),this.unsubscribe(),(e=this._detector)==null||e.destroy(),this._detector=null}_onRemoteTrackAdded(e,t,i){var r;if(i.kind===me.audio&&((r=this._detector)==null||r.destroy(),this._detector=new Nt(e,t),!this._interval)){let a=()=>{this._collectVolumes(),this._interval=window.setTimeout(a,p.voiceParams.interval)};this._interval=window.setTimeout(a,p.voiceParams.interval)}}_onRemoteTrackRemoved(e,t,i){i.kind===me.audio&&(!this._detector||this._detector.stream!==t||(this._detector.destroy(),this._detector=null))}_collectVolumes(){if(!this._detector)return;let e={},t=this._detector.trackId,i=this._detector.getLevel();if(t===ke.AUDIO_MIX){if(this._activeParticipants)for(let r of this._activeParticipants)e[r]=i}else e[t]=i;this._triggerEvent("VOLUMES_DETECTED",e)}_onSignalledActiveParticipants(e){this._activeParticipants=e}_onActiveParticipantsNoSignal(){this._activeParticipants=null}};var pr=(e=>(e.SPEAKER_CHANGED="SPEAKER_CHANGED",e))(pr||{}),lr=class extends Q{constructor(e,t){super();this._speakerId=null;this._serverAudioActivityAvailable=!1;this.subscribe(e,ct.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this.subscribe(t,N.SIGNALLED_SPEAKER_CHANGED,this._onServerSpeakerChanged.bind(this)),this.subscribe(t,N.SIGNALLED_ACTIVE_PARTICIPANTS,this._onReceivedServerAudioActivity.bind(this)),this.subscribe(t,N.ACTIVE_PARTICIPANTS_NO_SIGNAL,this._onStoppedReceivingServerAudioActivity.bind(this))}destroy(){this.unsubscribe()}_onVolumesDetected(e){if(this._serverAudioActivityAvailable)return;let t=0,i=null;if(Object.keys(e).forEach(r=>{let a=e[r].smoothed;a>t&&a>p.voiceParams.threshold&&(t=a,i=r)}),i&&i!==this._speakerId){let r=this._speakerId&&e.hasOwnProperty(this._speakerId)?e[this._speakerId].smoothed:0;t>r*p.voiceParams.speakerLevelMultiplier&&(this._speakerId=i,this._triggerEvent("SPEAKER_CHANGED",i))}}_onServerSpeakerChanged(e){this._serverAudioActivityAvailable&&this._triggerEvent("SPEAKER_CHANGED",e)}_onReceivedServerAudioActivity(){this._serverAudioActivityAvailable=!0}_onStoppedReceivingServerAudioActivity(){this._serverAudioActivityAvailable=!1}};var ci=class extends Q{constructor(e,t,i){super();this._states={};this._volumes={};this._participants={};this._connectionTimeout=0;this._volumeTimeout=0;this._transport=e,this._participants=i,this.subscribe(e,N.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(t,ct.VOLUMES_DETECTED,this._onVolumesDetected.bind(this))}destroy(){this.unsubscribe(),this._connectionTimeout&&window.clearTimeout(this._connectionTimeout),this._volumeTimeout&&window.clearTimeout(this._volumeTimeout)}onChangeRemoteMediaSettings(e,t){t.isAudioEnabled||(this._volumes[e]=1),t.isAudioEnabled&&(this._volumes[e]=0)}_onTransportStateChanged(e,t){e.forEach(i=>this._states[i]=t),t===F.OPENED&&(this._connectionTimeout||(this._connectionTimeout=window.setTimeout(this._onConnectionTimeout.bind(this),p.specListenerParams.connectionTimeout)),this._volumeTimeout||(this._volumeTimeout=window.setTimeout(this._onVolumeTimeout.bind(this),p.specListenerParams.volumeTimeout))),t===F.FAILED&&this._connectionTimeout&&(o.warn("Transport failed, send callSpecError"),m.log(_.CALL_SPEC_ERROR,`${this._transport.getTopology()}_CONNECTION_TIMEOUT`))}_onVolumesDetected(e){Object.keys(e).forEach(t=>{this._volumes[t]=Math.max(e[t].real,this._volumes[t]||0)})}_onConnectionTimeout(){let e=i=>i!==F.CONNECTED;(()=>Object.values(this._states).filter(e).length>0)()&&(o.warn("There is not connected transport, send callSpecError"),m.log(_.CALL_SPEC_ERROR,`${this._transport.getTopology()}_CONNECTION_TIMEOUT`)),this._connectionTimeout=0}_onVolumeTimeout(){let e=[];Object.keys(this._volumes).forEach(t=>{if(this._volumes[t]>0)return;let i="UNKNOWN",r=this._participants[t];r&&r.platform&&(i=r.platform),e.indexOf(i)<0&&(e.push(i),m.log(_.CALL_SPEC_ERROR,`${this._transport.getTopology()}_VOLUME_TIMEOUT_${i}`))}),e.length&&o.warn("There is silent participant, send callSpecError"),this._volumeTimeout=0}};var ws=1e3,Os=1e4;var H=class extends Q{constructor(e,t,i){super();this._mediaSource=null;this._conversation=null;this._state="IDLE";this._participantState=j.CALLED;this._participants={};this._transport=null;this._debugInfo=null;this._volumesDetector=null;this._speakerDetector=null;this._localVolumeDetector=null;this._specListener=null;this._activeSpeakerId=null;this._lastSignalledActiveSpeakerId=null;this._serverSettings={camera:null,screenSharing:null};this._lastStalled={};this._remoteAllStalled=!1;this._audioFix=null;this._streamByStreamId=new Map;this._streamIdByStreamDescription=new Map;this._streamWaitTimerByStreamDescription=new Map;this._sequenceNumberByStreamDescription=new Map;this._cooldownTimestampByStreamDescription=new Map;this._cooldownQueueCleanupTimer=null;m.create(e,i),this._api=e,this._signaling=t,this._onUnload=()=>{this._conversation&&this._api&&this._api.hangupConversation(this._conversation.id),m.destroy()},window.addEventListener("unload",this._onUnload),this._audioOutput=new ri,p.videoTracksCount>0&&(this._cooldownQueueCleanupTimer=window.setInterval(this._cleanupCooldownQueue.bind(this),ws))}static current(){return H._current}static hangupAfterInit(){H._activationMutex&&!H._current&&(H._delayedHangup=!0)}static id(){var e,t;return((t=(e=H._current)==null?void 0:e._conversation)==null?void 0:t.id)||null}onStart(e,t,i,r="",a=!1,s=!1){return c(this,null,function*(){if(H._activationMutex)throw m.log(_.ERROR,"startCall"),o.warn("Conversation: there is already running activation"),new x(P.FAILED);H._activationMutex=!0;try{this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(i);let d=this._mediaSource.getMediaSettings();t===Le.CHAT||e.length>1?this._logWithMediaSettings(_.OUTGOING_MULTIPARTY_CALL,d):this._logWithMediaSettings(_.OUTGOING_CALL,d);let l=yield this._startConversation(e,t,We.OUTGOING,i,r,a,s);if(!this._conversation)throw new x(P.UNKNOWN_ERROR);if(this._participantState=j.ACCEPTED,this._signaling.changeMediaSettings(d),yield this._registerParticipants(l.conversation.participants),this._processConnectionData(l),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),H._delayedHangup)throw new x(P.CANCELED);o.debug("Outgoing call",{opponentIds:e,opponentType:t,mediaOptions:i});let u=Object.values(this._participants),g;return p.batchParticipantsOnStart&&(g=T.mapSharedParticipants(u)),E.onLocalStream(this._mediaSource.getStream(),this._mediaSource.getMediaSettings()),E.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,g),E.onLocalStatus(J.WAITING),this._toggleJoinAvailability(),this._changeFeatureSet(),this._changeNeedRate(),H._current=this,this._conversation.concurrent?yield this._acceptConcurrent():p.batchParticipantsOnStart||this._setParticipantsStatus(u,J.WAITING),this._conversation}catch(d){throw this._close(d,"Unable to start conversation"),d}finally{H._activationMutex=!1}})}onJoin(e){return c(this,null,function*(){if(H._activationMutex)throw m.log(_.ERROR,"joinCall"),o.warn("Conversation: there is already running activation"),new x(P.FAILED);H._activationMutex=!0,this._state="PROCESSING";try{this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(e.mediaOptions);let t=this._mediaSource.getMediaSettings();this._logWithMediaSettings(_.JOIN_CONVERSATION,t);let i=yield this._joinConversation(e);if(!this._conversation)throw new x(P.UNKNOWN_ERROR);return E.onLocalStream(this._mediaSource.getStream(),t),this._conversation.waitingHall?(o.log("In waiting hall"),H._current=this,H._activationMutex=!1,this._signaling.readyToSend(),E.onLocalStatus(J.WAITING_HALL),this._conversation):this._onJoinPart2(i)}catch(t){throw H._activationMutex=!1,this._close(t,"Unable to join conversation"),t}})}_onJoinPart2(e){return c(this,null,function*(){o.debug("Join conversation part 2"),H._activationMutex=!0;try{if(this._participantState=j.ACCEPTED,!this._conversation||!this._mediaSource)throw new x(P.UNKNOWN_ERROR);if(this._signaling.changeMediaSettings(this._mediaSource.getMediaSettings()),yield this._registerParticipants(e.conversation.participants),this._processConnectionData(e),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),H._delayedHangup)throw new x(P.CANCELED);let t=Object.values(this._participants),i;return p.batchParticipantsOnStart&&(i=T.mapSharedParticipants(t)),E.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,i),E.onLocalStatus(J.WAITING),this._toggleJoinAvailability(),this._changeNeedRate(),this._state="ACTIVE",this._changeFeatureSet(),H._current=this,p.batchParticipantsOnStart||this._setParticipantsStatus(t,J.WAITING),this._openTransport(t,!1),this._conversation}catch(t){throw this._close(t,"Unable to join conversation"),t}finally{H._activationMutex=!1}})}onPush(r){return c(this,arguments,function*(e,t=X.USER,i){if(H._activationMutex)throw o.warn("Conversation: there is already running activation"),new x(P.REJECTED);H._activationMutex=!0;try{let a=yield this._prepareConversation(e,t,i);if(this._mediaSource=this._createMediaSource(),!this._conversation)throw new x(P.UNKNOWN_ERROR);if(!a.conversation.participants.find(d=>{var l;return d.state===j.CALLED&&d.id===((l=this._conversation)==null?void 0:l.userId)}))throw o.log("Push rejected (there is an active call)"),m.log(_.PUSH,"rejected"),new x(P.REJECTED);if(yield this._registerParticipants(a.conversation.participants),this._processConnectionData(a),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),m.log(_.PUSH,"accepted"),H._current=this,H._delayedHangup)throw new x(P.CANCELED);H._activationMutex=!1}catch(a){throw H._activationMutex=!1,this._close(a,"Unable to handle inbound call push"),a}})}_isInWaitingHall(e){if(!e.conversation||(e.conversation.options||[]).indexOf(Gt.WAITING_HALL)<0)return!1;let t=(e.conversation.participants||[]).find(i=>T.comparePeerId(i.peerId,e.peerId));return t&&t.restricted||!1}_acceptConcurrent(){return c(this,null,function*(){if(!this._mediaSource||!this._conversation)throw new x(P.UNKNOWN_ERROR);this._state="PROCESSING";let e=this._mediaSource.getMediaSettings();this._logWithMediaSettings(_.ACCEPT_CONCURRENT,e),o.debug("Concurrent call",{conversationId:this._conversation.id});try{yield this._signaling.acceptCall(this._mediaSource.getMediaSettings()),E.onCallAccepted(),this._state="ACTIVE",this._participantState=j.ACCEPTED,this._changeFeatureSet(),this._openTransport(Object.values(this._participants),!0)}catch(t){this._close(t,"Unable to accept concurrent call")}})}accept(e){return c(this,null,function*(){if(this._state!=="IDLE")throw m.log(_.ERROR,"acceptIncoming"),o.error("Unable to accept a call - invalid state"),new Error("Unable to accept a call - invalid state");if(!this._mediaSource||!this._conversation)throw new x(P.UNKNOWN_ERROR);this._state="PROCESSING",o.debug("Accept incoming call",e);try{yield this._mediaSource.request(e);let t=this._mediaSource.getMediaSettings();this._logWithMediaSettings(_.ACCEPT_INCOMING,t),this._signaling.changeMediaSettings(t),yield this._signaling.acceptCall(t),this._participantState=j.ACCEPTED;let i=Object.values(this._participants),r;p.batchParticipantsOnStart&&(r=T.mapSharedParticipants(i)),E.onCallAccepted(),E.onLocalStream(this._mediaSource.getStream(),t),E.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,r),E.onLocalStatus(J.WAITING),this._toggleJoinAvailability(),this._changeNeedRate();let a=Object.values(this._conversation.muteStates);return(a.includes(je.MUTE)||a.includes(je.MUTE_PERMANENT))&&(yield this._processMuteState(Object.keys(this._conversation.muteStates))),this._state="ACTIVE",this._changeFeatureSet(),p.batchParticipantsOnStart||this._setParticipantsStatus(i,J.WAITING),this._openTransport(i,!0),this._conversation}catch(t){throw this._close(t,"Unable to accept call"),t}})}decline(){return c(this,null,function*(){var e;if(this._state!=="IDLE")throw m.log(_.ERROR,"declineIncoming"),o.error("Unable to decline a call - invalid state"),new Error("Unable to decline a call - invalid state");this._state="PROCESSING",o.debug("Decline incoming call"),this._logWithMediaSettings(_.DECLINE_INCOMING,(e=this._mediaSource)==null?void 0:e.getMediaSettings()),this._participantState=j.HUNGUP,this._signaling.ready&&(yield this._signaling.hangup(P.REJECTED)),this._close(new x(P.REJECTED))})}hangup(){return c(this,null,function*(){o.debug("Hangup");let e=this._state==="ACTIVE"?P.HUNGUP:P.CANCELED;m.log(_.HANGUP,e),this._signaling.ready?(yield this._signaling.hangup(e),this._close(new x(e))):E.onHangup(new x(P.HUNGUP),this._conversation&&this._conversation.id)})}addParticipant(e,t){return c(this,null,function*(){if(!this._signaling.ready){this._close(new x(P.UNKNOWN_ERROR),"Unable to add participant");return}let i=yield this._signaling.addParticipant(e,t),r=null;i.type==="error"&&(i.error==="call-unfeasible"?r=i.status:r=P.UNKNOWN_ERROR);let a=i.participant;yield this._onAddParticipant(e,a,r)})}removeParticipant(e,t=!1){return c(this,null,function*(){this._signaling.ready&&(yield this._signaling.removeParticipant(e,t),this._onRemoveParticipant(e))})}setVolume(e){this._audioOutput.volume=e}updateStatisticsInterval(){this._transport&&this._transport.updateStatisticsInterval()}_openTransport(e,t){if(!this._transport)return;let i=[];for(let r of e)(r.state===j.CALLED||r.state===j.ACCEPTED)&&this._transport&&!this._transport.isAllocated(r.id)&&this._transport.allocate(r.id,t),this._transport&&r.state===j.ACCEPTED&&i.push(r.id);i.length&&this._transport.open(i)}_close(e,t){t&&o.error(t,e),o.debug("Close conversation",e),e.error?this._signaling.ready&&this._signaling.hangup(P.FAILED):m.log(_.ERROR,e.hangup),H._activationMutex=!1;let i=this._conversation&&this._conversation.id;if([P.CANCELED,P.NOT_FRIENDS,P.CALLEE_IS_OFFLINE,P.CALLER_IS_BLOCKED].indexOf(e.hangup)!==-1||e.hangup===P.REJECTED&&!e.remote){E.onHangup(e,i),this.destroy();return}if(e.hangup===P.HUNGUP&&(!e.remote||this._participantState===j.CALLED)){E.onHangup(e,i),this.destroy();return}if(e.hangup===P.MISSED&&!e.remote){E.onHangup(e,i),this.destroy();return}if(e.hangup===P.SOCKET_CLOSED&&H._current&&!this._conversation){this._cleanupSignaling(),this._cleanupMediaSource();return}if(e.hangup===P.BUSY&&!e.remote){this._cleanupSignaling(),this._cleanupMediaSource();return}this._state="CLOSE",this._participantState=j.HUNGUP,this._changeFeatureSet(),this._cleanupMediaSource(),this._cleanupParticipants(),this._cleanupParticipantAgnosticStreams(),this._cleanupTransport(),this._cleanupSpeakerDetector(),this._cleanupSpecListener(),this._cleanupSignaling(),this._api.cleanup(),m.destroy(),this._conversation=null,H._current=null,H._delayedHangup=!1,E.onHangup(e||new x(P.UNKNOWN_ERROR),i),this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null)}destroy(){let e=this._conversation&&this._conversation.id;o.debug("Destroy conversation",{conversationId:e}),this._cleanupMediaSource(),this._cleanupParticipants(),this._cleanupParticipantAgnosticStreams(),this._cleanupTransport(),this._cleanupSpeakerDetector(),this._cleanupSpecListener(),this._cleanupSignaling(),this._api.cleanup(),this._cleanupListeners(),m.destroy(),this._conversation=null,H._current=null,H._delayedHangup=!1,this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null)}_getConversationParams(e){return c(this,null,function*(){let t=yield this._api.getConversationParams(e);o.debug("Api.getConversationParams",t);let i=[],{turn_server:r,stun_server:a}=t;if(a&&i.push(a),r){let s=r.urls.filter((d,l,u)=>u.indexOf(d)===l);s.forEach(d=>s.push(`${d}?transport=tcp`)),i.push({urls:s,username:r.username,credential:r.credential})}p.iceServers=i,p.wssBase=t.endpoint,p.wssToken=t.token,t.client_type&&(p.clientType=t.client_type)})}_startConversation(e,t,i,r,a="",s=!1,d=!1){return c(this,null,function*(){let l=T.uuid();o.debug("Conversation: start",{conversationId:l,opponentIds:e,opponentType:t,direction:i});let u=r.includes(le.VIDEO),g=yield this._api.startConversation(l,e,t,u,a,s,d);o.debug("Api.startConversation",g),yield this._getConversationParams(g.id);let f=yield this._connectSignaling(Ue.START,g);return yield this._setConversation(g,f,i),f})}_joinConversation(e){return c(this,null,function*(){let{conversationId:t,mediaOptions:i,chatId:r,joinLink:a}=e;o.debug("Conversation: join",{conversationId:t,joinLink:a});let s=i.includes(le.VIDEO),d;if(t)d=yield this._api.joinConversation(t,s,r);else if(a)d=yield this._api.joinConversationByLink(a,s);else throw new x(P.UNKNOWN_ERROR);o.debug("Api.joinConversation",d),yield this._getConversationParams(d.id);let l=yield this._connectSignaling(Ue.JOIN,d);return yield this._setConversation(d,l,We.JOINING),l})}_prepareConversation(r){return c(this,arguments,function*(e,t=X.USER,i){o.debug("Conversation: push",{conversationId:e,type:t,peerId:i}),yield this._getConversationParams(e);let a=this._api.getUserId();if(!a)throw new x(P.UNKNOWN_ERROR);let s={id:e,peerId:i,endpoint:`${p.wssBase}?userId=${a}&entityType=${t}&conversationId=${e}&token=${p.wssToken}`,is_concurrent:!1,p2p_forbidden:!1},d=yield this._connectSignaling(Ue.ACCEPT,s);return H._current&&(H._current._participantState===j.ACCEPTED||H._current._participantState===j.CALLED)?(o.log("Push rejected (busy)"),m.log(_.PUSH,"busy"),this._signaling.ready&&this._signaling.hangup(P.BUSY),Promise.reject({hangup:P.BUSY})):(H._current&&(H._current.destroy(),H._current=null),yield this._setConversation(s,d,We.INCOMING,t),d)})}_createParticipant(e){return c(this,null,function*(){let t=Object.assign({id:null,externalId:null,mediaSettings:Ee(),participantState:{},state:j.CALLED,status:null,remoteStream:null,mediaSource:null,platform:null,clientType:null,roles:[],networkRating:1,lastRequestedLayouts:{},muteStates:{},unmuteOptions:[]},e);return e.externalId?this._api.cacheExternalId(t.id,e.externalId):t.externalId=yield this._getUserId(t.id),t})}_getUserId(e){return c(this,null,function*(){try{return yield this._api.userId(e)}catch(t){throw this._close(new x(P.NETWORK_ERROR),t),t}})}_setConversation(a,s,d){return c(this,arguments,function*(e,t,i,r=X.USER){let l=t.conversation.participants.map(W=>W.id);yield this._api.prepareUserIds(l);let u=this._api.getUserId();if(!u){let W=(t.conversation.participants||[]).find(K=>T.comparePeerId(K.peerId,t.peerId));if(!W)throw new x(P.UNKNOWN_ERROR);u=Number(W.id),W.idType&&(r=W.idType),this._api.setUserId(u)}let g=T.composeId(u,r),f=yield this._getUserId(g);this._conversation={userId:u,compositeUserId:g,externalId:f,acceptTime:t.conversation.acceptTime,features:t.conversation.features||[],id:t.conversation.id||e.id,participantsLimit:t.conversation.participantsLimit||30,topology:t.conversation.topology||Pe.DIRECT,direction:i,concurrent:t.isConcurrent||e.is_concurrent||!1,needRate:!1,chatId:t.conversation.multichatId,roles:[],recordInfo:null,joinLink:e.join_link,pinnedParticipantId:null,mediaModifiers:t.mediaModifiers,options:[],muteStates:{},unmuteOptions:[],networkRating:1,waitingHall:this._isInWaitingHall(t)},this._signaling.setConversationId(e.id),e.p2p_forbidden&&(p.forceRelayPolicy=e.p2p_forbidden),m.log(_.RELAY_POLICY,p.forceRelayPolicy?"1":"0"),this._changeFeatureSet(),this._logDevices()})}_updateConversation(e){if(!this._conversation)throw new x(P.UNKNOWN_ERROR);this._conversation.acceptTime=e.conversation.acceptTime,this._conversation.features=e.conversation.features||[],this._conversation.participantsLimit=e.conversation.participantsLimit||30,this._conversation.topology=e.conversation.topology||Pe.DIRECT,this._conversation.concurrent=e.isConcurrent||!1,this._conversation.chatId=e.conversation.multichatId,this._conversation.mediaModifiers=e.mediaModifiers,this._conversation.waitingHall=!1}_createMediaSource(){let e=new Ni;return this.subscribe(e,ye.SOURCE_CHANGED,this._onLocalMediaStreamChanged.bind(this)),this.subscribe(e,ye.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._audioFix=new xt(e),e}_connectSignaling(e,t){return c(this,null,function*(){return this._signaling.setEndpoint(t.endpoint),this.subscribe(this._signaling,fe.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._signaling,fe.FAILED,this._onSignalingFailed.bind(this)),this.subscribe(this._signaling,fe.RECONNECT,this._onSignalingReconnect.bind(this)),this._signaling.connect(e,t)})}_registerParticipants(e){return c(this,null,function*(){if(!!this._conversation)for(let t of e){let i=T.composeParticipantId(t);if(i===this._conversation.compositeUserId){this._conversation.roles=t.roles||[],this._conversation.roles.length&&(o.debug(`Local roles changed: ${t.roles}`),E.onLocalRolesChanged(this._conversation.roles)),t.muteStates&&(yield this._onMuteParticipant({muteStates:t.muteStates,unmuteOptions:t.unmuteOptions,mediaOptions:Object.keys(t.muteStates)}));continue}if(t.state===j.HUNGUP||t.state===j.REJECTED){this._participants[t.id]&&this._removeParticipant(this._participants[t.id],P.HUNGUP);continue}this._participants[i]=yield this._createParticipant({id:i,externalId:t.externalId&&re.fromSignaling(t.externalId),mediaSettings:Ee(t.mediaSettings),participantState:T.mapParticipantState(t),state:t.state,roles:t.roles||[],status:p.batchParticipantsOnStart?J.WAITING:null,muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[]}),t.roles&&t.roles.length&&(o.debug(`Roles for participant [${i}] changed: ${t.roles}`),E.onRolesChanged(this._participants[i].externalId,t.roles))}})}_processConnectionData(e){T.isEmptyObject(this._conversation.muteStates)&&e.conversation.muteStates&&this._onMuteParticipant({muteStates:e.conversation.muteStates,unmuteOptions:e.unmuteOptions,mediaOptions:Object.keys(e.conversation.muteStates),muteAll:!0}),e.conversation.pinnedParticipantId&&this._onPinParticipant(e.conversation.pinnedParticipantId),this._onRecordInfo(e.conversation.recordInfo),this._onOptionsChanged(e.conversation.options),e.chatRoom&&e.chatRoom.totalCount&&this._onChatRoomUpdated(Ht.ATTENDEE,e.chatRoom.totalCount,e.chatRoom.firstParticipants)}_allocateTransport(){if(!this._conversation||!this._mediaSource)return;this._transport=new cr(this._conversation.topology,this._signaling,this._mediaSource,this._serverSettings),this._debugInfo=new ni,this.subscribe(this._transport,N.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(this._transport,N.LOCAL_STATE_CHANGED,this._onTransportLocalStateChanged.bind(this)),this.subscribe(this._transport,N.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(this._transport,N.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(this._transport,N.REMOTE_ALL_STALL,this._onRemoteAllStall.bind(this)),this.subscribe(this._transport,N.REMOTE_DATA_STATS,this._onRemoteDataStats.bind(this)),this.subscribe(this._transport,N.SIGNALLED_STALLED_PARTICIPANTS,this._onRemoteSignalledStall.bind(this)),this.subscribe(this._transport,N.ACTIVE_PARTICIPANTS_NO_SIGNAL,this._onRemoteActivityNoSignal.bind(this)),this.subscribe(this._transport,N.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this)),this.subscribe(this._transport,N.NETWORK_STATUS,this._onNetworkStatus.bind(this)),this.subscribe(this._transport,N.REMOTE_STREAM_SECOND,this._onRemoteStreamSecond.bind(this)),this.subscribe(this._transport,N.PEER_CONNECTION_CLOSED,this._onPeerConnectionClosed.bind(this));let e=this._conversation.direction===We.OUTGOING&&!this._conversation.concurrent;for(let t of Object.values(this._participants))(t.state===j.ACCEPTED||t.state===j.CALLED)&&this._transport.allocate(t.id,e)}_createSpeakerDetector(){this._transport&&(this._volumesDetector=new dr(this._transport),this.subscribe(this._volumesDetector,ct.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this._speakerDetector=new lr(this._volumesDetector,this._transport),this.subscribe(this._speakerDetector,pr.SPEAKER_CHANGED,this._onSpeakerChanged.bind(this)),this._localVolumeDetector=new ai(this._mediaSource))}_createSpecListener(){this._transport&&this._volumesDetector&&(this._specListener=new ci(this._transport,this._volumesDetector,this._participants))}_logDevices(){let e=y.getCameras().length,t=y.getMicrophones().length;o.debug("Cameras: "+e+(y.hasCameraPermission()?"✔":"✖")+", Microphones: "+t+(y.hasMicrophonePermission()?"✔":"✖")),m.log(_.DEVICES,`${e}_${t}`)}_logWithMediaSettings(e,t){m.log(e,[(t==null?void 0:t.isAudioEnabled)&&"audio",(t==null?void 0:t.isVideoEnabled)&&"video"].filter(Boolean).join("_"))}_removeParticipant(e,t){var i;e.state===j.CALLED||e.state===j.ACCEPTED||this._state==="CLOSE"||!this._participants[e.id]||(t===P.HUNGUP?this._setParticipantsStatus([e],J.HANGUP):this._setParticipantsStatus([e],J.ERROR,t),(i=e.mediaSource)==null||i.disconnect(),this._conversation&&this._conversation.pinnedParticipantId===e.id&&(this._conversation.pinnedParticipantId=null),this.updateDisplayLayout([{uid:e.externalId,mediaType:Se.CAMERA,stopStream:!0}]),delete this._participants[e.id],E.onRemoteRemoved(e.externalId))}_cleanupListeners(){this.unsubscribe(),window.removeEventListener("unload",this._onUnload)}_cleanupMediaSource(){this._mediaSource&&(this._mediaSource.destroy(),this._mediaSource=null)}_cleanupParticipants(){Object.values(this._participants).forEach(e=>{var t,i,r;(t=e.remoteStream)==null||t.getTracks().forEach(a=>a.stop()),(i=e.secondStream)==null||i.getTracks().forEach(a=>a.stop()),(r=e.mediaSource)==null||r.disconnect()}),this._participants={},this._audioOutput&&this._audioOutput.destroy()}_cleanupParticipantAgnosticStreams(){o.debug("cleaning up participant-agnostic streams"),this._streamByStreamId.forEach(e=>{e.getTracks().forEach(t=>{t.stop()})}),this._streamByStreamId=new Map,this._streamWaitTimerByStreamDescription.forEach(e=>{window.clearTimeout(e)}),this._streamWaitTimerByStreamDescription=new Map,this._streamIdByStreamDescription=new Map,this._sequenceNumberByStreamDescription=new Map,this._cooldownTimestampByStreamDescription=new Map}_cleanupTransport(){this._transport&&(this._transport.destroy(),this._transport=null),this._debugInfo&&(this._debugInfo=null)}_cleanupSpeakerDetector(){this._speakerDetector&&(this._speakerDetector.destroy(),this._speakerDetector=null),this._volumesDetector&&(this._volumesDetector.destroy(),this._volumesDetector=null),this._localVolumeDetector&&(this._localVolumeDetector.destroy(),this._localVolumeDetector=null)}_cleanupSpecListener(){this._specListener&&(this._specListener.destroy(),this._specListener=null)}_cleanupSignaling(){this._signaling.close(),this._signaling.cleanup()}_onAddParticipant(e,t,i){return c(this,null,function*(){o.debug(`Add new participant [${e}]`);let r=this._participants[e];if(r&&(r.state===j.ACCEPTED||r.state===j.CALLED)){o.warn(`Participant [${r.id}:${r.state}] is already in conversation`);return}r||(this._participants[e]=yield this._createParticipant({id:e,externalId:t.externalId&&re.fromSignaling(t.externalId),mediaSettings:Ee(t.mediaSettings),state:t.state,roles:t.roles||[],muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[]}),r=this._participants[e]),this._setParticipantsStatus([r],J.WAITING),i?(r.state=j.HUNGUP,this._removeParticipant(r,i)):this._transport&&(r.state=j.CALLED,this._transport.allocate(r.id,!0),m.log(_.ADD_PARTICIPANT))})}_onRemoveParticipant(e){o.debug(`Remove participant [${e}]`);let t=this._participants[e];if(!t){o.warn(`Participant [${e}] isn't in conversation`);return}this._transport&&this._transport.close(t.id),m.log(_.REMOVE_PARTICIPANT)}changeDevice(e){return c(this,null,function*(){return e==="audiooutput"?this._audioOutput.changeOutput():this._mediaSource?(e==="audioinput"&&(this._audioFix=new xt(this._mediaSource)),this._mediaSource.changeDevice(e)):Promise.reject(ne.UNKNOWN)})}toggleScreenCapturing(e){return c(this,null,function*(){return this._mediaSource?this._mediaSource.toggleScreenCapturing(e):Promise.reject(ne.UNKNOWN)})}setVideoStream(e,t=!1){return c(this,null,function*(){if(this._mediaSource)return this._mediaSource.setVideoStream(e,t)})}setAudioStream(e){return c(this,null,function*(){if(this._mediaSource)return this._mediaSource.setAudioStream(e)})}toggleLocalVideo(e){return c(this,null,function*(){if(this._mediaSource)return m.log(_.MEDIA_STATUS,e?"video_1":"video_0"),this._mediaSource.toggleVideo(e)})}toggleLocalAudio(e){return c(this,null,function*(){if(this._mediaSource)return m.log(_.MEDIA_STATUS,e?"audio_1":"audio_0"),this._mediaSource.toggleAudio(e)})}changePriorities(e){return c(this,null,function*(){if(e.length<2||!this._signaling.ready)return;let t={},i={};for(let r of e){let a=typeof r.uid=="object"?r.uid:re.fromId(r.uid),s=re.toString(a);i[s]=r.priority}for(let r of Object.values(this._participants)){let a=re.toString(r.externalId);i.hasOwnProperty(a)&&(t[r.id]=i[a])}yield this._signaling.changePriorities(t)})}changeParticipantState(e){return c(this,null,function*(){for(let[t,i]of Object.entries(e))if(t.length>5||i.length>5)throw new Error("key/value max length is 5 chars, mappings with empty values (null or empty string) are discarded");yield this._signaling.changeParticipantState(e)})}updateDisplayLayout(e){return c(this,null,function*(){if(e.length<1||!this._signaling.ready)return;o.log(`Update display layout [${this._signaling.getNextCommandSequenceNumber()}]`,e);let t={};for(let r of e){let a=typeof r.uid=="object"?r.uid:re.fromId(r.uid),s=re.toString(a),d=this._api.getCachedOkIdByExternalId(a);if(!d){o.log(`Unknown participant external ID ${s}`);continue}let l=Qe({participantId:d,mediaType:r.mediaType,streamName:r.streamName}),u=this._participants[d];u&&(u.lastRequestedLayouts[l]=r),H._isStopStreaming(r)?this._streamIdByStreamDescription.has(l)&&!this._cooldownTimestampByStreamDescription.has(l)&&this._cooldownTimestampByStreamDescription.set(l,Date.now()):(this._cooldownTimestampByStreamDescription.delete(l),!this._streamIdByStreamDescription.has(l)&&p.videoTracksCount>0&&this._streamIdByStreamDescription.set(l,null),t[l]=H._layoutToString(r))}let i=this._cooldownTimestampByStreamDescription.keys();for(;this._streamIdByStreamDescription.size>p.videoTracksCount;){let r=i.next();if(r.done){o.error("Cannot accommodate all streaming requests: tracks available "+p.videoTracksCount+"; requested streams: "+Array.from(this._streamIdByStreamDescription.keys()));break}this._stopStreaming(r.value),t[r.value]=H._layoutToString({stopStream:!0})}yield this._sendUpdateDisplayLayout(t)})}_stopStreaming(e){if(this._cooldownTimestampByStreamDescription.delete(e),this._sequenceNumberByStreamDescription.set(e,this._signaling.getNextCommandSequenceNumber()),this._streamWaitTimerByStreamDescription.has(e)&&(o.log("Client asked to stop streaming before stream became available",e),window.clearTimeout(this._streamWaitTimerByStreamDescription.get(e)),this._streamWaitTimerByStreamDescription.delete(e)),this._streamIdByStreamDescription.get(e)){let i=Mt(e),r=this._participants[i.participantId];r?(i.streamName&&(i.mediaType===Se.STREAM||i.mediaType===Se.SCREEN)?E.onRemoteLive(r.externalId,i.streamName,null):E.onRemoteStream(r.externalId,null),m.log(_.PAT_DEALLOCATED)):o.log(`Cannot find participant to stop streaming: ${i.participantId}`)}this._streamIdByStreamDescription.delete(e)}_sendUpdateDisplayLayout(e){return c(this,null,function*(){if(Object.keys(e).length===0)return;let t=yield this._signaling.updateDisplayLayout(e);if(!t)return;let i=[];for(let[r,a]of Object.entries(t.errorCodeByParticipantId||{})){let s=Mt(r),d=this._participants[s.participantId];if(d){let l;typeof a!="number"?(o.warn(`Unexpected error code ${a} received for participant ${s.participantId}`),l=Hr.UNKNOWN_ERROR):l=Gr(a),i.push({externalId:d.externalId,errorReason:l})}}if(i&&i.length)throw new di("Could not allocate one or more participants",i)})}_cleanupCooldownQueue(){let e={},t=this._cooldownTimestampByStreamDescription.entries();do{let i=t.next();if(i.done)break;let r=i.value;if(r[1]+Os>Date.now())break;let s=r[0];this._stopStreaming(s),e[s]=H._layoutToString({stopStream:!0})}while(!0);this._sendUpdateDisplayLayout(e)}static _isStopStreaming(e){return e.stopStream}static _layoutToString(e){if(H._isStopStreaming(e))return"ss";let t="";return e.priority!==void 0&&(t+="p="+e.priority),e.width!==void 0&&e.height!==void 0&&(t!==""&&(t+=":"),t+="sz="+Math.round(e.width)+"x"+Math.round(e.height)),e.fit!==void 0&&(t!==""&&(t+=":"),t+="fit="+e.fit),e.keyFrame&&(t!==""&&(t+=":"),t+="kf"),t}_onParticipantSourcesUpdate(e){if(this._conversation){o.log("Received participant sources update notification",e);for(let t of e)this._waitForStreamIfNeeded(t)}}_onParticipantPromoted(e){return c(this,null,function*(){o.log("Promoted in waiting hall",!e.demote),e.demote?(o.log("Kicked from waiting hall"),this._close(new x(P.REMOVED))):(this._updateConversation(e),yield this._onJoinPart2(e))})}_onChatRoomUpdated(r){return c(this,arguments,function*(e,t=0,i=[]){o.log(`Chat room updated: ${e}`);let a=[],s=[];i.length&&(i.forEach(d=>{if(d.externalId){let l=re.fromSignaling(d.externalId);a.push(l),this._api.cacheExternalId(d.id.id,l)}else s.push(T.decomposeId(d.id.id).id)}),s.length&&!a.length&&(a=yield this._api.getExternalIdsByOkIds(s))),E.onChatRoomUpdated(e,t,a)})}_waitForStreamIfNeeded(e){var d,l;let t=this._matchStreamDescription(e.participantStreamDescription);if(!t||p.producerScreenTrack&&t.mediaType===Se.SCREEN)return;let i=Qe(t),r=this._sequenceNumberByStreamDescription.get(i);if(r&&r>e.sequenceNumber){o.warn(`Participant ${t.participantId} received outdated PAT response: sequence number ${e.sequenceNumber}; last sent sequence number for given participant is ${r}`),m.log(_.PAT_OUTDATED_RESPONSE);return}let a=e.streamId,s=e.rtpTimestamp?this._getWaitingTime(a,e.rtpTimestamp):0;if(s<=0){this._streamWaitTimerByStreamDescription.delete(i);let u=t.participantId,g=this._participants[u];if(!g){m.log(_.PAT_ERROR,"participantMissing"),o.error(`Could not find participant by ID: ${u}`);return}let f=this._streamByStreamId.get(a);if(!f){m.log(_.PAT_ERROR,"streamNotFound"),o.error(`Could not find stream by ID: ${a}`);return}m.log(_.PAT_ALLOCATED),this._streamIdByStreamDescription.set(i,a);let W=(d=e.participantStreamDescription)==null?void 0:d.mediaType;if(W===Se.STREAM||W===Se.MOVIE)((l=e.participantStreamDescription)==null?void 0:l.streamName)&&E.onRemoteLive(g.externalId,e.participantStreamDescription.streamName,f);else{let K=(p.producerScreenTrack?null:g.secondStream)||f;E.onRemoteStream(g.externalId,K)}}else{o.debug(`Waiting for ${s} until stream ${a} for ${i} is switched`);let u=window.setTimeout(this._waitForStreamIfNeeded.bind(this,e),s);this._streamWaitTimerByStreamDescription.set(i,u)}}_matchStreamDescription(e){if(!e)return null;if(this._streamIdByStreamDescription.has(Qe(e)))return e;let t=e.participantId;if(e.mediaType){let i={participantId:t,mediaType:null};if(this._streamIdByStreamDescription.has(Qe(i)))return i}else{let i={participantId:t,mediaType:Se.CAMERA};if(this._streamIdByStreamDescription.has(Qe(i)))return i;let r={participantId:t,mediaType:Se.SCREEN};if(this._streamIdByStreamDescription.has(Qe(r)))return r}return o.error("Received unrequested allocation",e),null}_getWaitingTime(e,t){if(this._transport)return this._transport.getStreamWaitingTimeMs(e,t);throw new Error("transport is not initialized")}_isCallAdmin(){return this._conversation?T.includesOneOf(this._conversation.roles,[Ye.ADMIN,Ye.CREATOR]):!1}_checkAdminRole(){if(!!this._conversation&&!T.includesOneOf(this._conversation.roles,[Ye.ADMIN,Ye.CREATOR]))throw new Error("You don't have the required permission")}grantRoles(e,t,i){return c(this,null,function*(){this._checkAdminRole(),yield this._signaling.grantRoles(e,t,i)})}muteParticipant(){return c(this,arguments,function*(e=null,t,i=[]){this._checkAdminRole(),yield this._signaling.muteParticipant(e,t,i)})}pinParticipant(e,t){return c(this,null,function*(){this._checkAdminRole(),yield this._signaling.pinParticipant(e,t)})}updateMediaModifiers(e){return c(this,null,function*(){this._signaling.ready&&this._conversation&&(this._conversation.mediaModifiers=e,yield this._signaling.updateMediaModifiers(e))})}changeOptions(e){return c(this,null,function*(){if(this._signaling.ready&&this._conversation){this._checkAdminRole(),yield this._signaling.changeOptions(e);let t=Ar(this._conversation.options,e);this._onOptionsChanged(t)}})}getWaitingHall(e,t,i){return c(this,null,function*(){if(!this._signaling)return Promise.reject();let r=null;e&&(r=Un(e));let a=yield this._signaling.getWaitingHall(r,t,i);if(a.error)return Promise.reject(a.message);let s=a.participants||[],d=[],l=[],u=null;return s.length&&(s.forEach(g=>{if(g.externalId){let f=re.fromSignaling(g.externalId);d.push(f),this._api.cacheExternalId(g.id.id,f)}else l.push(T.decomposeId(g.id.id).id)}),l.length&&!d.length&&(d=yield this._api.getExternalIdsByOkIds(l)),a.hasMore&&(u=Ln(s[s.length-1].id))),{participants:d,pageMarker:u,totalCount:a.totalCount||0}})}promoteParticipant(e,t){return c(this,null,function*(){this._signaling&&(yield this._signaling.promoteParticipant(e,t))})}chatMessage(e,t=null){return c(this,null,function*(){this._signaling.ready&&(yield this._signaling.chatMessage(e,t))})}chatHistory(e){return c(this,null,function*(){if(this._signaling.ready){let t=yield this._signaling.chatHistory(e);for(let i=t.messages.length-1;i>=0;i--){let r=t.messages[i];yield this._onChatMessage(r)}}})}customData(e,t=null){return c(this,null,function*(){this._signaling.ready&&(yield this._signaling.customData(e,t))})}createJoinLink(){return c(this,null,function*(){if(this._conversation){let t=(yield this._api.createJoinLink(this._conversation.id)).join_link;if(t)return this._conversation.joinLink=t,t}return Promise.reject()})}removeJoinLink(){return c(this,null,function*(){if(this._conversation&&(yield this._api.removeJoinLink(this._conversation.id)).success){delete this._conversation.joinLink;return}return Promise.reject()})}addMovie(e){return c(this,null,function*(){var r;let t={movieId:e,participantId:(r=this._conversation)==null?void 0:r.compositeUserId},i=yield this._signaling.addMovie(t);if(i.error)throw new Error(i.error);return{movieId:i.movieId,streamType:i.streamType}})}updateMovie(e,t,i,r){return c(this,null,function*(){var d;let a={movieId:e,participantId:(d=this._conversation)==null?void 0:d.compositeUserId};(t||t===0)&&(a.gain=t),i&&(a.offset=i),typeof r!==void 0&&(a.pause=r);let s=yield this._signaling.updateMovie(a);if(s.error)throw new Error(s.error)})}removeMovie(e){return c(this,null,function*(){var r;let t={movieId:e,participantId:(r=this._conversation)==null?void 0:r.compositeUserId},i=yield this._signaling.removeMovie(t);if(i.error)throw new Error(i.error)})}startStream(e=!1,t=null,i=null,r="DIRECT_LINK",a=null){return c(this,null,function*(){let s={movieId:i,name:t,privacy:r,groupId:a,streamMovie:!e},d=yield this._signaling.startStream(s);return d.error?Promise.reject(d.message):d})}stopStream(){return c(this,null,function*(){let e=yield this._signaling.stopStream();return e.error?Promise.reject():e})}recordSetRole(e,t){return c(this,null,function*(){let i=yield this._signaling.recordSetRole(e,t);if(i.error)throw new Error(i.error)})}getStreamInfo(){return c(this,null,function*(){let e=yield this._signaling.getRecordStatus();return{movieId:e.recordMovieId,preview:e.recordMoviePreviewUrl}})}setLocalResolution(e,t,i){return c(this,null,function*(){var r;if(e<p.videoMinWidth||t<p.videoMinHeight)throw new Error("Sizes received are less than the `videoMinWidth` or `videoMinHeight`");if(i==null?void 0:i.effect){if(i.effect.width<p.videoMinWidth||i.effect.height<p.videoMinHeight)throw new Error("Sizes of effect received are less than the `videoMinWidth` or `videoMinHeight`");p.videoEffectMaxHeight=i.effect.height,p.videoEffectMaxWidth=i.effect.width}return p.videoMaxWidth=e,p.videoMaxHeight=t,(r=this._mediaSource)==null?void 0:r.setResolution(e,t)})}videoEffect(e){return c(this,null,function*(){var t;return(t=this._mediaSource)==null?void 0:t.videoEffect(e)})}_onLocalMediaStreamChanged(e){return c(this,null,function*(){var t;!this._conversation||(o.debug("Local media stream changed",e.mediaSettings),E.onLocalStreamUpdate(e.mediaSettings,e.kind),this._signaling.ready&&!((t=this._conversation)==null?void 0:t.waitingHall)&&(yield this._signaling.changeMediaSettings(e.mediaSettings)))})}_onScreenSharingStatus(e){return c(this,null,function*(){var t;if(o.log("Screen sharing changed",e.track,e.mediaSettings),p.consumerScreenTrack){let i=e.track?new MediaStream([e.track]):null;E.onScreenStream(i,e.mediaSettings),this._signaling.ready&&!((t=this._conversation)==null?void 0:t.waitingHall)&&(yield this._signaling.changeMediaSettings(e.mediaSettings))}})}_changeRemoteMediaSettings(e,t){o.debug(`Remote media settings changed [${e}]`,t);let i=this._participants[e];!i||(i.mediaSettings=t,this._state==="ACTIVE"&&E.onRemoteMediaSettings(i.externalId,t),this._specListener&&this._specListener.onChangeRemoteMediaSettings(e,t))}_changeRemoteParticipantState(e,t){o.debug(`Remote participant state changed [${e}]`,t);let i=this._participants[e];!i||(i.participantState=t||{},this._state==="ACTIVE"&&(p.participantStateMapped?E.onRemoteParticipantState(i.externalId,i.participantState):E.onRemoteParticipantState(i.externalId,T.mapLegacyParticipantState(i.participantState))))}_onSignalingNotification(e){switch(e.notification){case O.ACCEPTED_CALL:return this._onAcceptedCall(e);case O.HUNGUP:return this._onHungup(e);case O.PARTICIPANT_ADDED:return this._onAddedParticipant(e);case O.PARTICIPANT_JOINED:return this._onJoinedParticipant(e);case O.CLOSED_CONVERSATION:return this._onClosedConversation(e);case O.MEDIA_SETTINGS_CHANGED:return this._onMediaSettingsChanged(e);case O.PARTICIPANT_STATE_CHANGED:return this._onParticipantStateChanged(e);case O.RATE_CALL_DATA:return this._onNeedRate();case O.FEATURE_SET_CHANGED:return this._onFeatureSetChanged(e);case O.MULTIPARTY_CHAT_CREATED:return this._onMultipartyChatCreated(e);case O.FORCE_MEDIA_SETTINGS_CHANGE:return this._onForceMediaSettingsChange(e);case O.SETTINGS_UPDATE:return this._onSettingsUpdate(e);case O.VIDEO_QUALITY_UPDATE:return this._onVideoQualityUpdate(e);case O.REGISTERED_PEER:return this._onPeerRegistered(e);case O.SWITCH_MICRO:return this._onMicSwitched(e);case O.CHAT_MESSAGE:return this._onChatMessage(e);case O.CUSTOM_DATA:return this._onCustomData(e);case O.RECORD_STARTED:return this._onRecordInfo(e.recordInfo);case O.RECORD_STOPPED:return this._onRecordInfo(null);case O.ROLES_CHANGED:return this._onRolesChanged(e.participantId,e.roles||[]);case O.MUTE_PARTICIPANT:return this._onMuteParticipant(e);case O.PIN_PARTICIPANT:return this._onPinParticipant(e.participantId,e.unpin);case O.OPTIONS_CHANGED:return this._onOptionsChanged(e.options||[]);case O.PARTICIPANT_SOURCES_UPDATE:return this._onParticipantSourcesUpdate(e.participantUpdateInfos);case O.PROMOTE_PARTICIPANT:return this._onParticipantPromoted(e);case O.CHAT_ROOM_UPDATED:return this._onChatRoomUpdated(e.eventType,e.totalCount,e.firstParticipants)}}_onSignalingReconnect(e){return c(this,null,function*(){if(!this._conversation)return;e.conversation.acceptTime&&(this._conversation.acceptTime=e.conversation.acceptTime),e.conversation.participantsLimit&&(this._conversation.participantsLimit=e.conversation.participantsLimit),e.conversation.features&&(this._conversation.features=e.conversation.features,this._changeFeatureSet()),e.conversation.pinnedParticipantId!==this._conversation.pinnedParticipantId&&(e.conversation.pinnedParticipantId?this._onPinParticipant(e.conversation.pinnedParticipantId,!1):this._conversation.pinnedParticipantId&&this._onPinParticipant(this._conversation.pinnedParticipantId,!0)),e.conversation.state;let t=null;if(e.conversation.participants){let i=Object.keys(this._participants),r=[];for(let a of e.conversation.participants){let s=T.composeParticipantId(a),d=a.roles||[];if(s===this._conversation.compositeUserId){t=Ee(a.mediaSettings),bt(this._conversation.roles,d)||this._onRolesChanged(s,d);continue}r.push(s);let l=this._participants[s];if(!l)yield this._onJoinedParticipant({participantId:a.id,participant:a,mediaSettings:a.mediaSettings});else{let u=Ee(a.mediaSettings);_n(u,l.mediaSettings)||this._changeRemoteMediaSettings(s,u);let g=T.mapParticipantState(a),f=l.participantState;T.isEqualParticipantState(g,f)||this._changeRemoteParticipantState(s,g),bt(d,l.roles)||this._onRolesChanged(l.id,d)}}for(let a of i)r.indexOf(a)<0&&this._removeParticipant(this._participants[a],P.HUNGUP)}this._onMuteParticipant({muteStates:e.conversation.muteStates,unmuteOptions:e.unmuteOptions,mediaOptions:[]},t),this._onRecordInfo(e.conversation.recordInfo),this._onOptionsChanged(e.conversation.options)})}_onSignalingFailed(e){o.error("Signaling failed",e),this._close(e)}_onAcceptedCall(e){return c(this,null,function*(){let t=T.composeMessageId(e),i=T.getPeerIdString(e.peerId);if(o.debug(`Participant accepted call [${t}]`),this._conversation&&t===this._conversation.compositeUserId){this._close(new x(P.MISSED),"Call accepted on other device");return}let r=this._participants[t];r||(this._participants[t]=yield this._createParticipant({id:t,mediaSettings:Ee(e.mediaSettings)}),r=this._participants[t]),r.state=j.ACCEPTED,r.mediaSettings=Ee(e.mediaSettings),this._logWithMediaSettings(_.ACCEPTED_OUTGOING,r.mediaSettings),this._conversation&&this._conversation.direction===We.OUTGOING&&(this._state==="IDLE"||this._state==="PROCESSING")&&(this._state="ACTIVE",this._changeFeatureSet()),this._state==="ACTIVE"&&this._transport&&this._transport.open([r.id],i),this._changeRemoteMediaSettings(t,r.mediaSettings),this._changeRemoteParticipantState(t)})}_onHungup(e){o.debug(`Participant hungup [${e.participantId}]`,{reason:e.reason});let t=T.composeMessageId(e);if(this._conversation&&this._conversation.compositeUserId===t){this._close(new x(e.reason));return}let i=this._participants[t];if(!i){o.warn(`Participant [${t}] isn't in conversation`);return}this._transport&&this._transport.close(t),i.state=e.reason===P.REJECTED?j.REJECTED:j.HUNGUP,this._state!=="CLOSE"&&this._removeParticipant(i,P.HUNGUP)}_onAddedParticipant(e){return c(this,null,function*(){var r,a;o.debug(`Participant added [${e.participantId}]`);let t=T.composeMessageId(e),i=this._participants[t];if(i&&i.state!==j.HUNGUP&&i.state!==j.REJECTED){o.debug(`Participant [${t}] is already in conversation and is active`);return}i||(this._participants[t]=yield this._createParticipant({id:t,externalId:e.participant.externalId&&re.fromSignaling(e.participant.externalId),mediaSettings:Ee(e.participant.mediaSettings),state:e.participant.state,participantState:T.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},unmuteOptions:e.participant.unmuteOptions||[]}),i=this._participants[t]),i.state=j.CALLED,i.mediaSettings=Ee((r=e.participant)==null?void 0:r.mediaSettings),i.participantState=T.mapParticipantState(e.participant),i.roles=((a=e.participant)==null?void 0:a.roles)||[],this._setParticipantsStatus([i],J.WAITING),this._state==="ACTIVE"&&this._transport&&this._transport.allocate(i.id,!0),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState)})}_onJoinedParticipant(e){return c(this,null,function*(){var r;o.debug(`Participant joined [${e.participantId}]`);let t=T.composeMessageId(e),i=this._participants[t];if(i&&i.state===j.ACCEPTED){o.warn(`Participant [${t}] is already in conversation and is active`);return}i||(this._participants[t]=yield this._createParticipant({id:t,externalId:e.participant.externalId&&re.fromSignaling(e.participant.externalId),mediaSettings:Ee(e.participant.mediaSettings),state:e.participant.state,participantState:T.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},unmuteOptions:e.participant.unmuteOptions||[]}),i=this._participants[t]),this._conversation&&this._conversation.direction===We.OUTGOING&&(this._state==="IDLE"||this._state==="PROCESSING")&&(this._state="ACTIVE",this._changeFeatureSet()),i.state=j.ACCEPTED,i.mediaSettings=Ee(e.mediaSettings),i.participantState=T.mapParticipantState(e.participant),i.roles=e.participant.roles||[],((r=this._transport)==null?void 0:r.isAllocated(i.id))?this._setParticipantsStatus([i],J.CONNECTED):this._setParticipantsStatus([i],J.WAITING),this._state==="ACTIVE"&&this._transport&&(this._transport.isAllocated(i.id)||this._transport.allocate(i.id,!0),this._transport.open([i.id])),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState)})}_onClosedConversation(e){this._toggleJoinAvailability(),this._close(new x(e.reason,{remote:!0}))}_onMediaSettingsChanged(e){let t=T.composeMessageId(e);this._changeRemoteMediaSettings(t,Ee(e.mediaSettings))}_onParticipantStateChanged(e){let t=T.composeMessageId(e);this._changeRemoteParticipantState(t,T.mapParticipantState(e))}_onNeedRate(){this._conversation&&(this._conversation.needRate=!0,this._changeNeedRate())}_onFeatureSetChanged(e){this._conversation&&(this._conversation.features=e.features,this._changeFeatureSet())}_onMultipartyChatCreated(e){this._conversation&&(this._conversation.chatId=e.chatId,this._toggleJoinAvailability(),E.onMultipartyChatCreated(this._conversation))}_onForceMediaSettingsChange(e){return c(this,null,function*(){if(!this._mediaSource)return;let t=this._mediaSource.getMediaSettings(),i=Ee(e.mediaSettings);t.isAudioEnabled!==i.isAudioEnabled&&(yield this._mediaSource.toggleAudio(i.isAudioEnabled)),t.isVideoEnabled!==i.isVideoEnabled&&(yield this._mediaSource.toggleVideo(i.isVideoEnabled)),p.consumerScreenTrack&&t.isScreenSharingEnabled!==i.isScreenSharingEnabled&&(yield this._mediaSource.toggleScreenCapturing(i.isScreenSharingEnabled))})}_onSettingsUpdate(e){let t={camera:e.camera,screenSharing:e.screenSharing};this._serverSettings=ar(this._serverSettings,t),this._transport&&this._transport.updateSettings(this._serverSettings)}_onVideoQualityUpdate(e){let t=Math.round(e.quality.maxBitrate/1024),i=e.quality.maxDimension,r={camera:Object.assign({},this._serverSettings.camera,{maxBitrateK:t,maxDimension:i}),screenSharing:null};this._serverSettings=ar(this._serverSettings,r),o.log("Got video quality update notification",this._serverSettings),this._transport&&this._transport.updateSettings(this._serverSettings)}_onPeerRegistered(e){let t=T.composeMessageId(e);this._participants[t]&&(this._participants[t].clientType=e.clientType,this._participants[t].platform=e.platform)}_onMicSwitched(e){return c(this,null,function*(){E.onDeviceSwitched(le.AUDIO,!e.mute),yield this.toggleLocalAudio(!e.mute)})}_onChatMessage(e){return c(this,null,function*(){let t=T.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getUserId(t),E.onChatMessage(e.message,i,e.direct)})}_onCustomData(e){return c(this,null,function*(){if(e.data.hasOwnProperty("sdk"))return;let t=T.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getUserId(t),E.onCustomData(e.data,i,e.direct)})}_onRecordInfo(e){return c(this,null,function*(){if(!this._conversation)return;let t=!1;if(!this._conversation.recordInfo!=!e?t=!0:this._conversation.recordInfo&&e&&(t=this._conversation.recordInfo.recordMovieId!==e.recordMovieId),t)if(e){let i=yield this._getUserId(e.initiator);E.onRecordStarted(i,e.recordMovieId,e.recordStartTime,e.recordType,e.recordExternalMovieId,e.recordExternalOwnerId)}else E.onRecordStopped();this._conversation.recordInfo=e})}_onRolesChanged(e,t){if(this._conversation&&e===this._conversation.compositeUserId&&!bt(this._conversation.roles,t)){o.debug(`Local roles changed: ${t}`),this._conversation.roles=t,E.onLocalRolesChanged(t),this._processMuteState(Object.keys(this._conversation.muteStates));return}let i=this._participants[e];i&&!bt(i.roles,t)&&(o.debug(`Roles for participant [${e}] changed: ${t}`),i.roles=t,E.onRolesChanged(i.externalId,t))}_onMuteParticipant(e,t=null){return c(this,null,function*(){if(!this._conversation)return;let i=e.muteStates||{},r=e.unmuteOptions||[],a=e.mediaOptions||[],s=e.adminId?this._participants[e.adminId]:null;if(e.participantId&&e.participantId!==this._conversation.compositeUserId){if(!this._isCallAdmin()){o.warn(`Not admin got mute states for participant [${e.participantId}]`);return}let d=this._participants[e.participantId];d&&(o.debug(`Mute states for participant [${e.participantId}] changed`,i),E.onMuteStates(i,r,a,e.muteAll,e.unmute,d.externalId,s==null?void 0:s.externalId));return}T.isObjectsEquals(this._conversation.muteStates,i)&&T.isArraysEquals(this._conversation.unmuteOptions,r)&&!a.length||(this._conversation.muteStates=i,this._conversation.unmuteOptions=r,e.adminId!==this._conversation.compositeUserId&&(yield this._processMuteState(a,e.muteAll,e.unmute,t,s)))})}_processMuteState(){return c(this,arguments,function*(e=[],t=!1,i=!1,r=null,a=null){if(!this._conversation||!this._mediaSource||this._participantState!==j.ACCEPTED)return;let s=Object.assign({},this._conversation.muteStates),d=this._conversation.unmuteOptions,l=this._mediaSource.getMediaSettings(),u=Object.entries(s);for(let[g,f]of u)if(!(f!==je.MUTE&&f!==je.MUTE_PERMANENT)&&(this._isCallAdmin()&&f===je.MUTE_PERMANENT&&(s[g]=je.MUTE),!(!e.includes(g)||i)))switch(g){case le.VIDEO:l.isVideoEnabled&&!(r==null?void 0:r.isVideoEnabled)&&(E.onDeviceSwitched(le.VIDEO,!1),yield this.toggleLocalVideo(!1));break;case le.AUDIO:l.isAudioEnabled&&!(r==null?void 0:r.isAudioEnabled)&&(E.onDeviceSwitched(le.AUDIO,!1),yield this.toggleLocalAudio(!1));break;case le.SCREEN_SHARING:l.isScreenSharingEnabled&&!(r==null?void 0:r.isScreenSharingEnabled)&&(E.onDeviceSwitched(le.SCREEN_SHARING,!1),yield this.toggleScreenCapturing(!1));break}E.onMuteStates(s,d,e,t,i,null,a==null?void 0:a.externalId)})}_onPinParticipant(e,t=!1){if(!this._conversation)return;let i=this._conversation.pinnedParticipantId;i&&i!==e&&(this._participants[i]?E.onPinnedParticipant(this._participants[i].externalId,!0):this._conversation.compositeUserId===i&&E.onLocalPin(!0)),this._participants[e]?E.onPinnedParticipant(this._participants[e].externalId,t):this._conversation.compositeUserId===e&&E.onLocalPin(t),this._conversation.pinnedParticipantId=t?null:e}_onOptionsChanged(e){this._conversation&&!Mr(this._conversation.options,e)&&(this._conversation.options=e,E.onOptionsChanged(e))}_onNetworkStatus(e){if(this._conversation){let t=[];for(let[i,r]of Object.entries(e)){let a;if(i===this._conversation.compositeUserId||i==="")a=this._conversation.networkRating;else if(this._participants[i])a=this._participants[i].networkRating;else continue;if(a!==r)if(i===this._conversation.compositeUserId||i==="")this._conversation.networkRating=r,E.onLocalNetworkStatusChanged(r);else{let s=this._participants[i];s.networkRating=r,t.push({uid:s.externalId,rating:r})}}if(t.length===0)return;o.log("Received network status update: ",e),E.onNetworkStatusChanged(t)}}_onRemoteStreamSecond(e,t){let i=this._participants[e];if(!!i){if(p.producerScreenTrack){E.onRemoteScreenStream(i.externalId,t);return}if(i.secondStream=t,p.videoTracksCount>0){let r=e;if(!this._streamIdByStreamDescription.has(r)){o.error("Received remote stream notification for a participant that has no track associated with it",r);return}let a=this._streamIdByStreamDescription.get(r);if(!a||this._streamWaitTimerByStreamDescription.has(r)){o.log("Delaying secondary stream start/stop until main stream becomes available",r);return}let s=this._streamByStreamId.get(a);if(!s){m.log(_.PAT_ERROR,"streamNotFound"),o.error(`Could not find stream by ID: ${a}`);return}E.onRemoteStream(i.externalId,i.secondStream||s)}else{let r=t||i.remoteStream;r&&E.onRemoteStream(i.externalId,r)}}}_onPeerConnectionClosed(e){e===Pe.SERVER&&this._cleanupParticipantAgnosticStreams()}_changeFeatureSet(){if(this._conversation){let e=this._state==="ACTIVE",t=this._conversation.features.includes(br.ADD_PARTICIPANT);E.onCallState(e,t,this._conversation)}}_changeNeedRate(){this._conversation&&this._conversation.needRate&&E.onRateNeeded()}_onVolumesDetected(e){let t=[];for(let[i,r]of Object.entries(e)){let a=this._participants[i];a&&a.externalId&&t.push({uid:a.externalId,volume:r.real})}E.onVolumesDetected(t)}_onSpeakerChanged(e){this._activeSpeakerId=e,this._participants[e]&&this._lastSignalledActiveSpeakerId!==e&&(E.onSpeakerChanged(this._participants[e].externalId),this._lastSignalledActiveSpeakerId=e)}_onTransportStateChanged(e,t){return c(this,null,function*(){o.debug(`Transport state has changed: ${t}`,e);let i;if(t===F.CONNECTED?i=J.CONNECTED:t===F.CONNECTING||t===F.OPENED?i=J.CONNECTING:t===F.RECONNECTING&&(i=J.RECONNECT),!i)return;let r=e.reduce((a,s)=>{if(s in this._participants){let d=this._participants[s];a.push(d),t===F.CONNECTED&&(d.remoteStream||(d.mediaSettings&&this._changeRemoteMediaSettings(s,d.mediaSettings),this._changeRemoteParticipantState(s,d.participantState)),this._updateDisplayLayoutFromCache(s))}else o.warn(`Participant [${s}] isn't in conversation`);return a},[]);!r.length||this._setParticipantsStatus(r,i)})}_onTransportLocalStateChanged(e){return c(this,null,function*(){o.debug(`Local transport state has changed: ${e}`),e===F.CONNECTED&&E.onLocalStatus(J.CONNECTED),e===F.CONNECTING&&E.onLocalStatus(J.CONNECTING),e===F.RECONNECTING&&E.onLocalStatus(J.RECONNECT),e===F.FAILED&&this._transport&&this._transport.allocated().length===0&&(this._signaling.ready&&(yield this._signaling.hangup(P.FAILED)),this._close(new x(P.FAILED),"Transport failed"))})}_onRemoteTrackAdded(e,t,i){return c(this,null,function*(){if(e.endsWith(ke.AUDIO_MIX))o.debug("Remote audio mix track added"),this._audioOutput.add(i);else if(e.startsWith(ke.PARTICIPANT_AGNOSTIC_TRACK_PREFIX))o.debug(`Participant-agnostic track added: ${e}`),this._streamByStreamId.set(e,t);else{o.debug(`Remote track added on the participant [${e}]`,{kind:i.kind});let r=this._participants[e];if(r||(o.warn(`Conversation: track added before participant [${e}]`),this._participants[e]=yield this._createParticipant({id:e}),r=this._participants[e],this._setParticipantsStatus([r],J.WAITING),this._activeSpeakerId===e&&this._lastSignalledActiveSpeakerId!==e&&(E.onSpeakerChanged(r.externalId),this._lastSignalledActiveSpeakerId=e)),this._transport&&!this._transport.isAllocated(r.id)&&this._transport.allocate(r.id,!1),i.kind===me.audio&&this._audioOutput.add(i),r.remoteStream!==t){if(r.remoteStream=t,r.secondStream)return;E.onRemoteStream(r.externalId,t)}r.mediaSettings&&this._changeRemoteMediaSettings(e,r.mediaSettings),p.batchParticipantsOnStart||this._changeRemoteParticipantState(e,r.participantState)}})}_onRemoteTrackRemoved(e,t,i){switch(o.debug(`[${e}] remote track (removed)`,{track:i}),i.kind){case me.audio:this._removeAudioTrack(e,t,i);break;case me.video:case me.screen:this._removeVideoTrack(e,t,i);break}}_removeAudioTrack(e,t,i){if(e!==ke.AUDIO_MIX){let r=this._participants[e];if(!r||r.remoteStream&&r.remoteStream!==t)return}this._audioOutput.remove(i)}_removeVideoTrack(e,t,i){}_onRemoteActivityNoSignal(){this._onRemoteSignalledStall([]),this._onRemoteAllStall(!1)}_onTopologyChanged(e){this._conversation&&(this._conversation.topology=e,this._changeFeatureSet())}_onRemoteAllStall(e){if(this._remoteAllStalled===e)return;this._remoteAllStalled=e;let t=[],i=[];for(let r in this._participants)if(this._participants.hasOwnProperty(r)){let a=this._participants[r];e||this._lastStalled[r]?t.push(a):i.push(a)}t.length&&this._setParticipantsStatus(t,J.RECONNECT),i.length&&this._setParticipantsStatus(i,J.CONNECTED)}_onRemoteSignalledStall(e){let t={},i=[],r=[];e.forEach(a=>{if(t[a]=!0,!this._lastStalled[a]){let s=this._participants[a];s&&!this._remoteAllStalled&&i.push(s)}delete this._lastStalled[a]}),Object.keys(this._lastStalled).forEach(a=>{let s=this._participants[a];s&&!this._remoteAllStalled&&r.push(s)}),i.length&&this._setParticipantsStatus(i,J.RECONNECT),r.length&&this._setParticipantsStatus(r,J.CONNECTED),this._lastStalled=t}_onRemoteDataStats(e){this._debugInfo&&this._debugInfo.onRemoteDataStats(e,this._participants),this._fixAudioDevice(e.outbound.rtps)}_fixAudioDevice(e){var t;!y.hasMicrophone()||!this._audioFix||!((t=this._mediaSource)==null?void 0:t.getMediaSettings().isAudioEnabled)||this._audioFix.fix(e)}_toggleJoinAvailability(){let e=this._conversation&&this._conversation.chatId,t=e&&this._state!=="CLOSE"||!1;e&&(o.debug("Toggle join availability",{available:t,chatId:e}),E.onJoinStatus(t,e))}_updateDisplayLayoutFromCache(e){return c(this,null,function*(){var i;if(((i=this._transport)==null?void 0:i.getTopology())!==Pe.SERVER)return;let t=this._participants[e];t&&t.lastRequestedLayouts&&Object.keys(t.lastRequestedLayouts).length&&(yield this.updateDisplayLayout(Object.values(t.lastRequestedLayouts)))})}_setParticipantsStatus(e,t,i=null){if(!e.length)return;let r=e.reduce((a,s)=>(s.status!==t&&(s.status=t,p.batchParticipantsOnStart?a.push(s.externalId):E.onParticipantStatus(s.externalId,t,i)),a),[]);!r.length||p.batchParticipantsOnStart&&E.onRemoteStatus(r,t,i)}replayShare(e){var t;(t=this._transport)==null||t.replayShare(e,this)}getRandomParticipant(){let e=Object.values(this._participants);for(let t of e)return t;return null}},L=H;L._delayedHangup=!1;var di=class extends Error{constructor(e,t){super(e);Object.setPrototypeOf(this,di.prototype),this.participantErrors=t}};var pi;function ks(){return c(this,null,function*(){var n;if(p.apiEnv!=="AUTO")return p.apiEndpoint;try{let e=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT1hcGkuX2VuZHBvaW50Lm9rLnJ1JnR5cGU9VFhU"),i=yield(yield fetch(e,{method:"GET",mode:"cors",cache:"no-cache"})).json(),r=(n=i==null?void 0:i.Answer[0])==null?void 0:n.data;if(!r)throw new Error("Wrong DNS response");return o.debug("Resolved API endpoint",r),r}catch(e){return o.warn("Failed to resolve API endpoint using DNS, default is used",e),p.apiEndpoint}})}function Hn(){if(!p.apiAppId||!p.apiKey)throw new x(ne.API,{message:"Required arguments apiAppId/apiAppKey not passed"})}function ur(n,e={},t=!1){if(!window.Blob||!window.navigator.sendBeacon)return;let i=Wn(n,e,t),r=new window.Blob([i],{type:"application/x-www-form-urlencoded"});window.navigator.sendBeacon(`${pi}/fb.do`,r)}function Gn(i){return c(this,arguments,function*(n,e={},t=!1){pi||(pi=yield ks());let r=Wn(n,e,t);return xs(r)})}function xs(n){return c(this,null,function*(){return new Promise((e,t)=>{let i=new XMLHttpRequest;i.open("POST",`${pi}/fb.do`,!0),i.setRequestHeader("Content-type","application/x-www-form-urlencoded"),i.onreadystatechange=()=>{if(i.readyState!==XMLHttpRequest.DONE)return;let r;try{r=JSON.parse(i.responseText)}catch(a){r={result:i.responseText}}i.status!==200||r.hasOwnProperty("error_msg")?t(r):e(r)},i.send(n)})})}function Wn(n,e={},t=!1){e.method=n,e.format="JSON",e.application_key||(e.application_key=p.apiKey),t||(ie.sessionKey?e.session_key=ie.sessionKey:ie.accessToken&&(e.access_token=ie.accessToken));for(let[r,a]of Object.entries(e))typeof a=="object"&&(e[r]=JSON.stringify(a));let i="";for(let[r,a]of Object.entries(e))i&&(i+="&"),i+=`${r}=${encodeURIComponent(a)}`;return i}var Ls=10,Us=700,Bs=3e3,Ft=class extends pt{constructor(){super(...arguments);this._userId=null;this._externalUidsCache={}}_callUnsafe(r){return c(this,arguments,function*(e,t={},i=!1){let a=s=>c(this,null,function*(){try{return yield Gn(e,t,i)}catch(d){if(!d.hasOwnProperty("error_msg")&&(s++,o.debug(`${e} network error, attempt ${s}...`),s<Ls))return yield T.delay(Math.min(s*Us,Bs)),a(s);throw o.warn(e,"error",d),d}});return a(0)})}_call(r){return c(this,arguments,function*(e,t={},i=!1){try{return yield this._callUnsafe(e,t,i)}catch(a){o.warn("Api call error",a);let s=ne.API;switch(a.error_code){case 102:case 103:case 104:return yield this.authorize(),this._callUnsafe(e,t,i);case 1101:s=P.SERVICE_DISABLED;break;case 1102:s=P.CALLEE_IS_OFFLINE;break;case 1103:s=P.NOT_FRIENDS;break;case 1104:case 1106:s=P.EXTERNAL_API_ERROR;break}throw new x(s,{message:a.error_msg,code:a.error_code})}})}userId(e){return c(this,null,function*(){let t=T.decomposeId(e).id;return ie.isEmpty()?re.fromId(String(t)):(this._externalUidsCache.hasOwnProperty(t)||Object.assign(this._externalUidsCache,yield this._getExternalIdsByOkIds([t])),re.fromString(this._externalUidsCache[t]))})}prepareUserIds(e){return c(this,null,function*(){ie.isEmpty()||Object.assign(this._externalUidsCache,yield this._getExternalIdsByOkIds(e))})}authorize(){return c(this,null,function*(){if(!this._uuid){let t=qe.get("uuid");t||(t=T.uuid(),qe.set("uuid",t)),this._uuid=String(t)}let e={session_data:{version:2,device_id:this._uuid,client_version:p.appVersion,client_type:"SDK_JS"}};return p.authToken&&(e.session_data.auth_token=p.authToken,e.session_data.version=3),this._callUnsafe("auth.anonymLogin",e,!0).then(t=>{t.uid&&(this._userId=Number(t.uid)),ie.sessionKey=t.session_key,ie.sessionSecretKey=t.session_secret_key}).catch(t=>{throw t.error_code===401&&E.onTokenExpired(),new x(ne.AUTH,{message:t.error_msg,code:t.error_code})})})}log(e){let t={collector:"ok.mobile.apps.video",data:JSON.stringify({application:`${p.appName}:${p.sdkVersion}`,platform:p.platform,items:e})};ur("log.externalLog",t)}init(){Hn()}joinConversation(e,t=!1,i){return c(this,null,function*(){let r={conversationId:e,isVideo:t};return i&&(r.chatId=i),this._call("vchat.joinConversation",r)})}createConversation(e,t="",i=!1){return c(this,null,function*(){let r={conversationId:e,createJoinLink:!0,isVideo:!1};return t&&(r.payload=t),p.domain&&(r.domainId=p.domain),i&&(r.requireAuthToJoin=!0),this._startConversation(r)})}startConversation(e,t,i,r=!1,a="",s=!1,d=!1){return c(this,null,function*(){let l={conversationId:e,isVideo:r};if(t&&t.length)switch(i){case Le.USER:l.uids=t.join(",");break;case Le.GROUP:l.gid=t[0];break;case Le.CHAT:l.chatId=t[0];break}return s&&(l.createJoinLink=!0),a&&(l.payload=a),p.domain&&(l.domainId=p.domain),d&&(l.requireAuthToJoin=!0),this._startConversation(l)})}_startConversation(e){return c(this,null,function*(){return this._call("vchat.startConversation",e)})}createJoinLink(e){return c(this,null,function*(){return this._call("vchat.createJoinLink",{conversationId:e})})}removeJoinLink(e){return c(this,null,function*(){return this._call("vchat.removeJoinLink",{conversationId:e})})}getAnonymTokenByLink(e,t){return c(this,null,function*(){let i={joinLink:e};t&&(i.anonymName=t);let r=yield this._call("vchat.getAnonymTokenByLink",i);return this._userId=Number(r.uid),r.token})}joinConversationByLink(e,t=!1){return c(this,null,function*(){let i={joinLink:e,isVideo:t};return p.anonymToken&&(i.anonymToken=p.anonymToken),this._call("vchat.joinConversationByLink",i)})}getOkIdsByExternalIds(e){return c(this,null,function*(){let t=re.fromIds(e),i=[],r={methods:[]},a=[],s=Object.keys(this._externalUidsCache),d=Object.values(this._externalUidsCache);for(let u of t){let g=re.toString(u),f=d.indexOf(g);f>-1?i.push(Number(s[f])):(a.push(g),r.methods.push({"vchat.getOkIdByExternalId":{params:{externalId:u.id,anonym:u.type===at.ANONYM},onError:"SKIP"}}))}return r.methods.length&&(yield this._call("batch.executeV2",r)).forEach((u,g)=>{if(u.ok){let f=Number(u.ok.ok_id);this._externalUidsCache[f]=a[g],i.push(f)}}),i})}getExternalIdsByOkIds(e){return c(this,null,function*(){let t=[],i=[];for(let a of e)this._externalUidsCache.hasOwnProperty(a)?t.push(re.fromString(this._externalUidsCache[a])):i.push(a);if(!i.length)return t;let r=yield this._getExternalIdsByOkIds(i);Object.assign(this._externalUidsCache,r);for(let a of i)r.hasOwnProperty(a)&&t.push(re.fromString(r[a]));return t})}getCachedOkIdByExternalId(e){let t=Object.keys(this._externalUidsCache),i=Object.values(this._externalUidsCache),r=re.toString(e),a=i.indexOf(r);return a>-1?T.composeId(t[a],X.USER):null}cacheExternalId(e,t){let i=T.decomposeId(e).id;this._externalUidsCache[i]=re.toString(t)}getConversationParams(e){return c(this,null,function*(){let t={};return p.anonymToken&&(t.anonymToken=p.anonymToken),e&&(t.conversationId=e),this._call("vchat.getConversationParams",t)})}getUserId(){return this._userId}setUserId(e){this._userId=e}hangupConversation(e){let t={conversationId:e,reason:P.HUNGUP};p.anonymToken&&(t.anonymToken=p.anonymToken),ur("vchat.hangupConversation",t)}removeHistoryRecords(e){return c(this,null,function*(){yield this._call("vchat.removeHistoryRecords",{recordIds:e.join(",")})})}cleanup(){}_getExternalIdsByOkIds(e){return c(this,null,function*(){let t={};try{let i=yield this._call("vchat.getExternalIdsByOkIds",{uids:e.join(",")});if(i.external_ids)for(let[r,a]of Object.entries(i.external_ids))t[r]=re.fromIdToString(a,at.USER);if(i.anonym_ids)for(let[r,a]of Object.entries(i.anonym_ids))t[r]=re.fromIdToString(a,at.ANONYM);return t}catch(i){return t}})}getTokenForAnonym(e,t){return c(this,null,function*(){let i={id:e};return t&&(i.application_key=t),(yield this._callUnsafe("auth.getTokenForAnonym",i,!0)).token})}call(i){return c(this,arguments,function*(e,t={}){return this._call(e,t)})}};var jn=(A=>(A.RECOVER="recover",A.ACCEPT_CALL="accept-call",A.ADD_PARTICIPANT="add-participant",A.REMOVE_PARTICIPANT="remove-participant",A.HANGUP="hangup",A.TRANSMIT_DATA="transmit-data",A.ACCEPT_PRODUCER="accept-producer",A.ALLOCATE_CONSUMER="allocate-consumer",A.CHANGE_MEDIA_SETTINGS="change-media-settings",A.CHANGE_PARTICIPANT_STATE="change-participant-state",A.CHANGE_STREAM_PRIORITIES="change-streams-priorities",A.UPDATE_DISPLAY_LAYOUT="update-display-layout",A.REPORT_PERF_STAT="report-perf-stat",A.RECORD_START="record-start",A.RECORD_STOP="record-stop",A.RECORD_SET_ROLE="record-set-role",A.RECORD_GET_STATUS="record-get-status",A.SWITCH_MICRO="switch-micro",A.SWITCH_TOPOLOGY="switch-topology",A.REQUEST_REALLOC="request-realloc",A.CHAT_MESSAGE="chat-message",A.CHAT_HISTORY="chat-history",A.CUSTOM_DATA="custom-data",A.GRANT_ROLES="grant-roles",A.MUTE_PARTICIPANT="mute-participant",A.PIN_PARTICIPANT="pin-participant",A.UPDATE_MEDIA_MODIFIERS="update-media-modifiers",A.CHANGE_OPTIONS="change-options",A.GET_WAITING_HALL="get-waiting-hall",A.PROMOTE_PARTICIPANT="promote-participant",A.REQUEST_TEST_MODE="request-test-mode",A.ADD_MOVIE="add-movie",A.UPDATE_MOVIE="update-movie",A.REMOVE_MOVIE="remove-movie",A))(jn||{}),G=jn;var Kn="open",$n=[()=>p.producerScreenTrack,()=>p.videoTracksCount>0,()=>!0,()=>p.filteredMessages,()=>p.consumerScreenTrack,()=>!0,()=>p.movieShare],Fs=10,we=class extends ut{constructor(){super(...arguments);this.socket=null;this.sequence=1;this.lastStamp=0;this.websocketCommandsQueue=[];this.datachannelCommandsQueue=[];this.incomingCache=[];this.responseHandlers={};this.reconnectCount=0;this.conversationResolve=null;this.conversationReject=null;this.connected=!1;this.listenersReady=!1;this.postfix="&platform="+p.platform+"&appVersion="+p.appVersion+"&version="+p.protocolVersion+"&device="+p.device+"&capabilities="+we._getCapabilityFlags();this.peerId=null;this.conversationId=null;this.reconnectTimer=0;this.connectionMessageWaitTimer=0;this.doctorTimer=0;this.participantIdRegistry=null;this.producerNotificationDataChannel=null;this.producerCommandDataChannel=null}static _getCapabilityFlags(){let e=0;for(let t=0;t<$n.length;t++)$n[t]()&&(e|=1<<t);return e.toString(16).toUpperCase()}get ready(){return this.socket!==null}setEndpoint(e){this.endpoint=e}setConversationId(e){this.conversationId=e}setParticipantIdRegistry(e){this.participantIdRegistry=e}setProducerNotificationDataChannel(e){this.producerNotificationDataChannel=e,this.producerNotificationDataChannel.onmessage=t=>{var r;let i=(r=this.participantIdRegistry)==null?void 0:r.handleMessage(t.data);i&&this._handleMessage(i)}}setProducerCommandDataChannel(e){this.producerCommandDataChannel=e,this.producerCommandDataChannel.onmessage=this._onMessage.bind(this),this._handleCommandsQueue(this.datachannelCommandsQueue)}cleanup(){this.datachannelCommandsQueue=[]}connect(e){return c(this,null,function*(){return this.postfix+=`&clientType=${p.clientType}`,new Promise((t,i)=>{if(this.socket&&this.socket.readyState<WebSocket.CLOSING){m.log(_.SOCKET_ACTION,"already_opened"),i(Error("Socket already opened"));return}this.conversationResolve=r=>{t(r),this.conversationResolve=null,this.conversationReject=null},this.conversationReject=r=>{i(r),this.conversationResolve=null,this.conversationReject=null},this._connect(e)})})}_send(r){return c(this,arguments,function*(e,t={},i=0){if(t.participantId){let a=T.decomposeId(t.participantId);t=Object.assign({},t,{participantId:a.id,participantType:a.type})}return this._sendRaw(e,t,i)})}_sendRaw(r){return c(this,arguments,function*(e,t={},i=0){let a=s=>{var l;if(this._isDataChannelCommand(e))this.datachannelCommandsQueue.push(s),((l=this.producerCommandDataChannel)==null?void 0:l.readyState)===Kn&&this._handleCommandsQueue(this.datachannelCommandsQueue);else{if(!this.socket){m.log(_.SOCKET_ACTION,"not_opened"),o.warn("Socket not opened"),s.reject(new Error(`Socket not opened [${e}]`),!0);return}this.socket.readyState>WebSocket.OPEN&&(m.log(_.SOCKET_ACTION,"invalid_state"),o.warn(`Socket is not opened, state ${this.socket.readyState}`)),this.websocketCommandsQueue.push(s),this.socket&&this.socket.readyState===WebSocket.OPEN&&this._handleCommandsQueue(this.websocketCommandsQueue)}};return new Promise((s,d)=>{let l=(g,f=!1)=>{!i||f?d(g):(o.debug("Resending a signaling message",e,u.sequence),i--,a(u))},u={sequence:this.sequence++,name:e,params:t,responseTimer:0,resolve:s,reject:l};a(u)})})}_isDataChannelCommand(e){return this.producerCommandDataChannel?e===G.UPDATE_DISPLAY_LAYOUT||e===G.REPORT_PERF_STAT:!1}static _isDataChannelResponseRequired(e){return e===G.UPDATE_DISPLAY_LAYOUT||e===G.REPORT_PERF_STAT}getNextCommandSequenceNumber(){return this.sequence}hangup(e){return c(this,null,function*(){return this._send(G.HANGUP,{reason:e}).catch(()=>{})})}sendCandidate(e,t){return c(this,null,function*(){return this._send(G.TRANSMIT_DATA,{participantId:e,data:{candidate:t}})})}requestTestMode(e){return c(this,null,function*(){return this._send(G.REQUEST_TEST_MODE,{consumerCommand:e})})}sendSdp(e,t){return c(this,null,function*(){return this._send(G.TRANSMIT_DATA,{participantId:e,data:{sdp:t}})})}acceptCall(e){return c(this,null,function*(){return this._send(G.ACCEPT_CALL,{mediaSettings:e})})}changeMediaSettings(e){return c(this,null,function*(){return this._send(G.CHANGE_MEDIA_SETTINGS,{mediaSettings:e},Fs)})}changeParticipantState(e){return c(this,null,function*(){return this._send(G.CHANGE_PARTICIPANT_STATE,{participantState:{state:e}})})}addParticipant(e,t){return c(this,null,function*(){return this._send(G.ADD_PARTICIPANT,Er({participantId:e},t))})}removeParticipant(e,t=!1){return c(this,null,function*(){return this._send(G.REMOVE_PARTICIPANT,{participantId:e,ban:t})})}allocateConsumer(e,t){return c(this,null,function*(){let i={capabilities:t};return e&&(i.description=e.sdp),this._send(G.ALLOCATE_CONSUMER,i)})}acceptProducer(e,t){return c(this,null,function*(){let i={description:e.sdp};return t&&(i.ssrcs=t),this._send(G.ACCEPT_PRODUCER,i)})}changePriorities(e){return c(this,null,function*(){return this._send(G.CHANGE_STREAM_PRIORITIES,{typedPriorities:e}).catch(()=>{})})}updateDisplayLayout(e){return c(this,null,function*(){return this._send(G.UPDATE_DISPLAY_LAYOUT,{layouts:e})})}addMovie(e){return c(this,null,function*(){return this._send(G.ADD_MOVIE,e)})}updateMovie(e){return c(this,null,function*(){return this._send(G.UPDATE_MOVIE,e)})}removeMovie(e){return c(this,null,function*(){return this._send(G.REMOVE_MOVIE,e)})}startStream(e){return c(this,null,function*(){return this._send(G.RECORD_START,e)})}stopStream(){return c(this,null,function*(){return this._send(G.RECORD_STOP)})}recordSetRole(e,t){return c(this,null,function*(){return this._send(G.RECORD_SET_ROLE,{participantId:e,role:t})})}getRecordStatus(){return c(this,null,function*(){return this._send(G.RECORD_GET_STATUS)})}switchTopology(e,t=!1){return c(this,null,function*(){return this._send(G.SWITCH_TOPOLOGY,{topology:e,force:t})})}requestRealloc(){return c(this,null,function*(){return this._send(G.REQUEST_REALLOC)})}reportPerfStat(e){return c(this,null,function*(){return this._send(G.REPORT_PERF_STAT,{report:e})})}chatMessage(e,t=null){return c(this,null,function*(){return this._send(G.CHAT_MESSAGE,{message:e,participantId:t})})}chatHistory(e){return c(this,null,function*(){return this._send(G.CHAT_HISTORY,{count:e})})}customData(e,t){return c(this,null,function*(){return this._send(G.CUSTOM_DATA,{data:e,participantId:t})})}grantRoles(e,t,i){return c(this,null,function*(){let r={participantId:e,roles:t};return i&&(r.revoke=!0),this._sendRaw(G.GRANT_ROLES,r)})}muteParticipant(e,t,i){return c(this,null,function*(){return this._sendRaw(G.MUTE_PARTICIPANT,{participantId:e,muteStates:t,requestedMedia:i})})}pinParticipant(e,t){return c(this,null,function*(){let i={participantId:e};return t&&(i.unpin=!0),this._sendRaw(G.PIN_PARTICIPANT,i)})}updateMediaModifiers(e){return c(this,null,function*(){return this._send(G.UPDATE_MEDIA_MODIFIERS,{mediaModifiers:e})})}changeOptions(e){return c(this,null,function*(){return this._send(G.CHANGE_OPTIONS,{options:e})})}getWaitingHall(e=null,t,i=!1){return c(this,null,function*(){let r={};return e&&(r.fromId=e),t&&(r.count=t),i&&(r.backward=i),this._send(G.GET_WAITING_HALL,r)})}promoteParticipant(e,t=!1){return c(this,null,function*(){let i={participantId:e};return t&&(i.demote=t),this._sendRaw(G.PROMOTE_PARTICIPANT,i)})}close(){this.socket&&this.socket.readyState<WebSocket.CLOSING&&this._closeSocket(),this._stopWaitConnectionMessage(),this._stopDoctor(),clearTimeout(this.reconnectTimer)}readyToSend(){this.listenersReady=!0,this._handleCachedMessages()}_connect(e){if(this.socket&&this.socket.readyState<WebSocket.CLOSING)return;let t="";e&&(t+=`&tgt=${e}`),e===Ue.RETRY&&this.lastStamp&&(t+=`&recoverTs=${this.lastStamp}`),o.debug("Connecting to "+this.endpoint+this.postfix+t),this.socket=new WebSocket(this.endpoint+this.postfix+t),this.socket.onopen=this._onOpen.bind(this),this.socket.onmessage=this._onMessage.bind(this),this.socket.onerror=this._onError.bind(this),this.socket.onclose=this._onClose.bind(this),this._startDoctor()}_disconnect(){this.socket&&this.socket.readyState<WebSocket.CLOSING&&(this.socket.onopen=null,this.socket.onmessage=null,this.socket.onerror=null,this.socket.onclose=null,this.socket.close(),this.socket=null),this._stopWaitConnectionMessage(),this._stopDoctor(),clearTimeout(this.reconnectTimer)}_onOpen(){o.debug("Socket opened"),m.log(_.SOCKET_ACTION,"opened"),this._waitConnectionMessage(),this._startDoctor()}_onMessage(e){if(this._startDoctor(),e.data==="ping"){this.socket&&this.socket.readyState===WebSocket.OPEN&&this.socket.send("pong");return}try{this._handleMessage(JSON.parse(e.data))}catch(t){m.log(_.SOCKET_ACTION,"parse_error"),o.error("Unable to parse message",t,e.data)}}_handleMessage(e){var t;e.type==="notification"?e.notification==="connection"?(o.debug("Signaling connected",e),this.connected=!0,this.reconnectCount=0,this.endpoint=e.endpoint,e.peerId&&this.peerId!==e.peerId.id&&(this.postfix+=`&peerId=${e.peerId.id}`,this.peerId=e.peerId.id),this._stopWaitConnectionMessage(),this.conversationResolve?this.conversationResolve(e):(this._triggerEvent(fe.RECONNECT,e),e.conversation.topology&&this._triggerEvent(fe.NOTIFICATION,{type:"notification",notification:O.TOPOLOGY_CHANGED,topology:e.conversation.topology})),this.lastStamp&&this._handleCachedMessages(),(t=e.recoverMessages)==null||t.forEach(i=>this._handleMessage(i)),this._handleCommandsQueue(this.websocketCommandsQueue)):!this.connected||!this.listenersReady?this.incomingCache.push(e):this._triggerEvent(fe.NOTIFICATION,e):e.type==="response"&&this.responseHandlers[e.sequence]?this._handleCommandResponse(!0,e):e.type==="error"&&this.responseHandlers[e.sequence]?(m.log(_.SOCKET_ACTION,`error-${e.error}`),this._handleCommandResponse(!1,e)):e.type==="error"?(m.log(_.SOCKET_ACTION,`error-${e.error}`),e.error==="service-unavailable"?this._reconnect():e.error==="conversation-ended"?this.conversationReject?this.conversationReject(new x(P.SOCKET_CLOSED,{message:`Unable to connect to the signaling: ${e.error}`})):this._triggerEvent(fe.NOTIFICATION,{notification:O.CLOSED_CONVERSATION,reason:e.reason}):this.connected||e.error==="invalid-token"?this._throwError(new Error(`Signaling error: ${e.error}`)):e.sequence||(this.conversationReject&&this.conversationReject(new x(ne.SIGNALING_FAILED,{message:`Unable to connect to the signaling: ${e.error}`})),this._closeSocket())):(m.log(_.SOCKET_ACTION,"unknown_message"),o.warn("Unhandled message",e)),this.lastStamp=e.stamp||this.lastStamp}_handleCachedMessages(){let e=[...this.incomingCache];for(this.incomingCache=[];e.length>0;){let t=e.shift();this._handleMessage(t)}}_throwError(e){this._triggerEvent(fe.FAILED,e)}_onError(e){m.log(_.SOCKET_ACTION,"error"),o.error("Signaling error",e)}_onClose(e){m.log(_.SOCKET_ACTION,"closed"),o.debug("Connection closed",{code:e.code,reason:e.reason}),this.connected=!1,this._stopDoctor(),this.socket&&this.reconnectCount++<we.RECONNECT_MAX_COUNT?this._reconnect():this.socket&&this._closeSocket(new Error("Connection closed"))}_closeSocket(e=null){!this.socket||(this._disconnect(),Object.values(this.responseHandlers).forEach(t=>{window.clearTimeout(t.responseTimer),e&&t.reject(new Error("Connection closed"),!0)}),this.websocketCommandsQueue=[],this.responseHandlers={},this.lastStamp=0,e&&this._throwError(new Error("Connection closed")))}_reconnect(){let e=Math.min(we.RECONNECT_MAX_DELAY,we.RECONNECT_DELAY*Math.pow(2,this.reconnectCount-1));o.log(`Reconnect websocket after ${e}ms (${this.reconnectCount})`),m.log(_.SOCKET_ACTION,"reconnect"),this.reconnectTimer=window.setTimeout(this._connect.bind(this,Ue.RETRY),e)}_handleCommandResponse(e,t){var r;if(!this.responseHandlers.hasOwnProperty(t.sequence))return;let i=this.responseHandlers[t.sequence];window.clearTimeout(i.responseTimer),e?(delete this.responseHandlers[t.sequence],i.resolve(t)):((r=this.socket)==null?void 0:r.readyState)===WebSocket.OPEN?(delete this.responseHandlers[t.sequence],m.log(_.SOCKET_ACTION,"response-timeout"),i.reject(new Error(t.error||`Response timeout [${i.name}]`))):i.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,t),we.WAIT_RESPONSE_DELAY)}_handleCommandsQueue(e){var t,i;for(;e.length>0;){let r=e.shift(),a=Object.assign({command:r.name,sequence:r.sequence},r.params);if(this._isDataChannelCommand(r.name)){if(((t=this.producerCommandDataChannel)==null?void 0:t.readyState)!==Kn){r.reject(new Error(`Invalid data channel state: ${(i=this.producerCommandDataChannel)==null?void 0:i.readyState}`));return}we._isDataChannelResponseRequired(r.name)&&(r.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,a),we.WAIT_RESPONSE_DELAY),this.responseHandlers[r.sequence]=r),this.producerCommandDataChannel.send(JSON.stringify(a))}else{if(!this.socket||this.socket.readyState!==WebSocket.OPEN){r.reject(new Error("Invalid state or socket already closed"));continue}r.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,a),we.WAIT_RESPONSE_DELAY),this.responseHandlers[r.sequence]=r,this.socket.send(JSON.stringify(a))}}}_waitConnectionMessage(){this.connectionMessageWaitTimer=window.setTimeout(()=>{this.conversationReject&&this.conversationReject(new x(ne.SIGNALING_FAILED,{message:"Unable to connect to the signaling: connection timeout"}))},we.WAIT_CONNECTION_DELAY)}_stopWaitConnectionMessage(){window.clearTimeout(this.connectionMessageWaitTimer),this.connectionMessageWaitTimer=0}_startDoctor(){this._stopDoctor(),this.doctorTimer=window.setTimeout(()=>{o.warn("Socket is dead, trying to reconnect"),this._disconnect(),this._connect(Ue.RETRY)},we.WAIT_MESSAGE_DELAY)}_stopDoctor(){window.clearTimeout(this.doctorTimer),this.doctorTimer=0}},xe=we;xe.RECONNECT_DELAY=p.signalingReconnectDelay,xe.RECONNECT_MAX_DELAY=p.signalingReconnectMaxDelay,xe.RECONNECT_MAX_COUNT=p.signalingReconnectMaxCount,xe.WAIT_CONNECTION_DELAY=p.waitConnectionDelay,xe.WAIT_RESPONSE_DELAY=p.waitResponseDelay,xe.WAIT_MESSAGE_DELAY=p.waitMessageDelay;var qn=(t=>(t.KING="KING",t.PAWN="PAWN",t))(qn||{}),Jn=qn;var Ct,ae,Vt=null,Vs={getCameras:y.getCameras,getMicrophones:y.getMicrophones,getOutput:y.getOutput,hasCamera:y.hasCamera,hasMicrophone:y.hasMicrophone,getSavedCamera:y.getSavedCamera,getSavedMicrophone:y.getSavedMicrophone,getSavedOutput:y.getSavedOutput,hasCameraPermission:y.hasCameraPermission,hasMicrophonePermission:y.hasMicrophonePermission,hasPermissions:y.hasPermissions,getUserMedia:y.getUserMedia,getUserVideo:y.getUserVideo,getUserAudio:y.getUserAudio,saveDeviceId:y.saveDeviceId,isBrowserSupported:y.isBrowserSupported,isScreenCapturingSupported:y.isScreenCapturingSupported,os:y.os,isMobile:y.isMobile,browserName:y.browserName,browserVersion:y.browserVersion,baseChromeVersion:y.baseChromeVersion,getAudioContext:y.getAudioContext};function Yn(n){ae=n}function zn(n){Ct=n}function Hs(n){Vt=n}function Gs(n){p.videoEffects=n}function Ws(n){return c(this,null,function*(){if(p.set(n),y.browserName()==="Sferum"&&(p.platform=`SFERUM:${y.browserVersion()}`),ae||Yn(new Ft),Ct||zn(()=>new xe),p.debug&&(hr.default.disableLog(!1),o.toggle(!0)),o.log(`Calls SDK ${p.sdkVersion}`,n),yield y.init(),!y.isBrowserSupported())throw new x(ne.UNSUPPORTED);ae.init()})}function js(a){return c(this,arguments,function*(n,e=[le.AUDIO],t="",i=!1,r=!1){let s=[],d=[];if(Array.isArray(n)?s=n.length?n:[]:n&&(s=[n]),s.length&&(d=yield ae.getOkIdsByExternalIds(s),!d.length))throw new x(P.CALLEE_IS_OFFLINE);return Qn(d,Le.USER,e,t,i,r)})}function Qn(s){return c(this,arguments,function*(n,e=Le.USER,t,i="",r=!1,a=!1){if(L.current())throw o.error("There is already active call"),new x(P.FAILED);return new L(ae,Ct(),Vt).onStart(n,e,t,i,r,a)})}function Ks(n){return c(this,null,function*(){return Xn(n)})}function Xn(i){return c(this,arguments,function*(n,e=X.USER,t){if(n===L.id())throw new Error("Push has already been processed");return new L(ae,Ct(),Vt).onPush(n,e,t)})}function $s(n,e){return c(this,null,function*(){return ae.getTokenForAnonym(n,e)})}function qs(t){return c(this,arguments,function*(n,e={}){return ae.call(n,e)})}function Js(n){return c(this,null,function*(){return n&&(p.authToken=n),ae.authorize()})}function Ys(){return c(this,arguments,function*(n=[le.AUDIO]){let e=L.current();if(e)return e.accept(n);throw new Error("Conversation not found")})}function zs(){return c(this,null,function*(){let n=L.current();if(n)return n.decline()})}function Qs(t){return c(this,arguments,function*(n,e=[le.AUDIO]){return Zn(n,e)})}function Zn(n,e,t){return c(this,null,function*(){if(L.current())throw o.error("There is already active call"),new x(P.FAILED);return new L(ae,Ct(),Vt).onJoin({conversationId:n,mediaOptions:e,chatId:t})})}function Xs(i){return c(this,arguments,function*(n,e=[le.AUDIO],t){if(L.current())throw o.error("There is already active call"),new x(P.FAILED);return t&&(p.anonymToken=t),new L(ae,Ct(),Vt).onJoin({joinLink:n,mediaOptions:e})})}function Zs(){return c(this,null,function*(){let n=L.current();if(n)return n.hangup();L.hangupAfterInit()})}function eo(n,e){return c(this,null,function*(){let t=yield ae.getOkIdsByExternalIds([n]);if(!t.length)throw new Error("User not found");return ea(t[0],e)})}function ea(n,e){return c(this,null,function*(){let t=L.current();t&&(yield t.addParticipant(T.composeId(n,X.USER),e))})}function to(n,e=!1){return c(this,null,function*(){let t=yield ae.getOkIdsByExternalIds([n]);return ta(t[0],e)})}function ta(n,e=!1){return c(this,null,function*(){let t=L.current();t&&(yield t.removeParticipant(T.composeId(n,X.USER),e))})}function io(n,e){return c(this,null,function*(){let t=yield y.saveDeviceId(n,e),i=L.current();return t&&i?i.changeDevice(n):Promise.reject()})}function ro(n){return c(this,null,function*(){let e=L.current();return e?e.toggleScreenCapturing(n):Promise.reject()})}function no(n,e=!1){return c(this,null,function*(){let t=L.current();t&&(yield t.setVideoStream(n,e))})}function ao(n){return c(this,null,function*(){let e=L.current();e&&(yield e.toggleLocalVideo(n))})}function so(n){return c(this,null,function*(){let e=L.current();e&&(yield e.toggleLocalAudio(n))})}function oo(n,e,t){return c(this,null,function*(){let i=L.current();if(i)return i.setLocalResolution(n,e,t)})}function co(n){return c(this,null,function*(){let e=L.current();e&&(yield e.changePriorities(n))})}function po(n){return c(this,null,function*(){let e=L.current();e&&(yield e.changeParticipantState(n))})}function lo(n){return c(this,null,function*(){let e=L.current();e&&(yield e.updateDisplayLayout(n))})}function uo(n,e,t=!1){return c(this,null,function*(){let i=yield ae.getOkIdsByExternalIds([n]);return ia(i[0],e,t)})}function ia(n,e,t=!1){return c(this,null,function*(){let i=L.current();i&&(yield i.grantRoles(T.composeId(n,X.USER),e,t))})}function ho(){return c(this,arguments,function*(n=null,e,t=[]){let i=null;return n&&(i=(yield ae.getOkIdsByExternalIds([n]))[0]),ra(i,e,t)})}function ra(){return c(this,arguments,function*(n=null,e,t=[]){let i=L.current();if(i){let r=n?T.composeId(n,X.USER):null;yield i.muteParticipant(r,e,t)}})}function mo(n,e=!1){return c(this,null,function*(){let t=yield ae.getOkIdsByExternalIds([n]);return na(t[0],e)})}function na(n,e=!1){return c(this,null,function*(){let t=L.current();t&&(yield t.pinParticipant(T.composeId(n,X.USER),e))})}function go(n){return c(this,null,function*(){let e=L.current();e&&(yield e.updateMediaModifiers(n))})}function _o(n){return c(this,null,function*(){let e=L.current();e&&(yield e.changeOptions(n))})}function fo(n,e=null){return c(this,null,function*(){let t=null;return e&&(t=(yield ae.getOkIdsByExternalIds([e]))[0]),aa(n,t)})}function aa(n,e=null){return c(this,null,function*(){let t=L.current();if(t){let i=e?T.composeId(e,X.USER):null;yield t.chatMessage(n,i)}})}function So(n=10){return c(this,null,function*(){let e=L.current();if(e)return e.chatHistory(n)})}function vo(n,e=null){return c(this,null,function*(){let t=null;return e&&(t=(yield ae.getOkIdsByExternalIds([e]))[0]),sa(n,t)})}function sa(n,e=null){return c(this,null,function*(){let t=L.current();if(t){let i=e?T.composeId(e,X.USER):null;yield t.customData(n,i)}})}function Eo(n="",e=!1){return c(this,null,function*(){return(yield ae.createConversation(T.uuid(),n,e)).join_link})}function To(){return c(this,null,function*(){let n=L.current();return n?n.createJoinLink():Promise.reject()})}function Co(){return c(this,null,function*(){let n=L.current();return n?n.removeJoinLink():Promise.reject()})}function Io(n,e){return c(this,null,function*(){return ae.getAnonymTokenByLink(n,e)})}function yo(n){let e=L.current();e&&e.setVolume(n)}function Ro(n){p.forceRelayPolicy=n}function bo(n=!1,e=null,t=null,i="DIRECT_LINK",r=null){return c(this,null,function*(){let a=L.current();return a?a.startStream(n,e,t,i,r):Promise.reject()})}function Po(){return c(this,null,function*(){let n=L.current();return n?n.stopStream():Promise.reject()})}function Mo(n,e){return c(this,null,function*(){let t=L.current();if(t){let i=yield ae.getOkIdsByExternalIds([n]);return t.recordSetRole(T.composeId(i[0],X.USER),e)}return Promise.reject()})}function Ao(){return c(this,null,function*(){let n=L.current();return n?n.getStreamInfo():Promise.reject()})}function Do(n){return c(this,null,function*(){let e=L.current();return e?e.addMovie(n):Promise.reject()})}function wo(n,e,t,i){return c(this,null,function*(){let r=L.current();return r?r.updateMovie(n,e,t,i):Promise.reject()})}function Oo(n){return c(this,null,function*(){let e=L.current();return e?e.removeMovie(n):Promise.reject()})}function ko(n){p.statisticsInterval=n;let e=L.current();if(e)return e.updateStatisticsInterval()}function xo(n){hr.default.disableLog(!n),o.toggle(n)}function No(n,...e){!p.debugLog||o.send(n,"[external]",...e)}function Lo(n){return c(this,null,function*(){let e=L.current();if(e)return e.videoEffect(n)})}function Uo(n){return c(this,null,function*(){let e=L.current();e&&(yield e.setAudioStream(n))})}function Bo(n=null,e,t=!1){return c(this,null,function*(){let i=L.current();if(!i)throw new Error("Conversation not found");return i.getWaitingHall(n,e,t)})}function Fo(n,e=!1){return c(this,null,function*(){let t=L.current();if(!t)throw new Error("Conversation not found");let i=yield ae.getOkIdsByExternalIds([n]);return t.promoteParticipant(T.composeId(i[0],X.USER),e)})}function Vo(n){return c(this,null,function*(){yield ae.removeHistoryRecords(n)})}function Ho(){return L.current()}
13
- /*!
14
- * The buffer module from node.js, for the browser.
15
- *
16
- * @author Feross Aboukhadijeh <https://feross.org>
17
- * @license MIT
18
- */
19
- /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
7
+ var ga=Object.create;var ht=Object.defineProperty;var fa=Object.getOwnPropertyDescriptor;var Sa=Object.getOwnPropertyNames,Gi=Object.getOwnPropertySymbols,va=Object.getPrototypeOf,Wi=Object.prototype.hasOwnProperty,Ea=Object.prototype.propertyIsEnumerable;var ji=Math.pow,Ki=(a,e,t)=>e in a?ht(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,$i=(a,e)=>{for(var t in e||(e={}))Wi.call(e,t)&&Ki(a,t,e[t]);if(Gi)for(var t of Gi(e))Ea.call(e,t)&&Ki(a,t,e[t]);return a};var qi=a=>ht(a,"__esModule",{value:!0});var Ta=(a,e)=>{qi(a);for(var t in e)ht(a,t,{get:e[t],enumerable:!0})},Ia=(a,e,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Sa(e))!Wi.call(a,i)&&i!=="default"&&ht(a,i,{get:()=>e[i],enumerable:!(t=fa(e,i))||t.enumerable});return a},He=a=>Ia(qi(ht(a!=null?ga(va(a)):{},"default",a&&a.__esModule&&"default"in a?{get:()=>a.default,enumerable:!0}:{value:a,enumerable:!0})),a);var c=(a,e,t)=>new Promise((i,r)=>{var n=l=>{try{d(t.next(l))}catch(h){r(h)}},s=l=>{try{d(t.throw(l))}catch(h){r(h)}},d=l=>l.done?i(l.value):Promise.resolve(l.value).then(n,s);d((t=t.apply(a,e)).next())});Ta(exports,{Api:()=>bt,BaseApi:()=>Ze,BaseLogger:()=>et,BaseSignaling:()=>tt,CallDirection:()=>Ne,CallType:()=>De,ChatRoomEventType:()=>Dt,ConversationOption:()=>At,DebugMessageType:()=>Pi,ExternalIdType:()=>Je,FacingMode:()=>Ei,FatalError:()=>Z,HangupReason:()=>O,HangupType:()=>M,MediaOption:()=>re,MediaTrackKind:()=>se,MediaType:()=>fe,MuteState:()=>xe,ParticipantState:()=>G,ParticipantStatus:()=>q,RecordRole:()=>ia,Signaling:()=>Pe,SignalingCommandType:()=>H,SignalingConnectionType:()=>Ae,SignalingNotification:()=>A,UserRole:()=>Ge,UserType:()=>Q,Utils:()=>E,acceptCall:()=>Dn,addMovie:()=>ds,addParticipant:()=>Nn,addParticipantInternal:()=>ca,apiCall:()=>bn,authorize:()=>Mn,browser:()=>En,callInternal:()=>na,callTo:()=>yn,captureScreen:()=>Un,changeConversationOptions:()=>Yn,changeDevice:()=>Ln,changeParticipantState:()=>Wn,changePriorities:()=>Gn,changeVideoEffect:()=>_s,chatHistory:()=>Qn,chatMessage:()=>zn,chatMessageInternal:()=>ma,createJoinLink:()=>es,customData:()=>Xn,customDataInternal:()=>ha,debug:()=>ms,debugMessage:()=>hs,declineCall:()=>An,forceRelayPolicy:()=>as,getAnonymTokenByLink:()=>is,getStreamInfo:()=>cs,getTokenForAnonym:()=>Pn,getWaitingHall:()=>fs,grantRoles:()=>Kn,grantRolesInternal:()=>pa,hangup:()=>wn,init:()=>Cn,joinCall:()=>On,joinCallByLink:()=>kn,joinCallInternal:()=>oa,muteParticipant:()=>$n,muteParticipantInternal:()=>la,pinParticipant:()=>qn,pinParticipantInternal:()=>ua,processPush:()=>Rn,processPushInternal:()=>sa,promoteParticipant:()=>Ss,recordSetRole:()=>os,removeHistoryRecords:()=>vs,removeJoinLink:()=>ts,removeMovie:()=>ls,removeParticipant:()=>xn,removeParticipantInternal:()=>da,setApi:()=>ra,setAudioStream:()=>gs,setLocalResolution:()=>Hn,setLogger:()=>Tn,setMediaModifiers:()=>Jn,setSignalingFactory:()=>aa,setStatisticsInterval:()=>us,setVideoEffects:()=>In,setVideoStream:()=>Bn,setVolume:()=>rs,startConversation:()=>Zn,startStream:()=>ns,stopStream:()=>ss,toggleLocalAudio:()=>Fn,toggleLocalVideo:()=>Vn,updateDisplayLayout:()=>jn,updateMovie:()=>ps});var Ui=He(require("webrtc-adapter"));var Ze=class{createJoinLink(e){return c(this,null,function*(){return{join_link:"nop"}})}removeJoinLink(e){return c(this,null,function*(){return{success:!0}})}getAnonymTokenByLink(e,t){return c(this,null,function*(){return""})}log(e){}prepareUserIds(e){return c(this,null,function*(){})}getCachedOkIdByExternalId(e){return null}cacheExternalId(e,t){}hangupConversation(e){}removeHistoryRecords(e){return c(this,null,function*(){})}cleanup(){}getTokenForAnonym(e,t){return c(this,null,function*(){return""})}call(i){return c(this,arguments,function*(e,t={}){return null})}};var et=class{log(e,t,i=!1){}destroy(){}};var z=class{constructor(){this._handlers={};this._listeners=[]}_triggerEvent(e,...t){if(!!this._handlers.hasOwnProperty(e))for(let i of this._handlers[e])i.apply(this,t)}addEventListener(e,t){if(typeof t!="function")throw new Error("Listener should be a function");return this._handlers.hasOwnProperty(e)||(this._handlers[e]=[]),this._handlers[e].push(t),{dispose:this.removeEventListener.bind(this,e,t)}}removeEventListener(e,t){if(!this._handlers.hasOwnProperty(e))return;t||delete this._handlers[e];let i=this._handlers[e].indexOf(t);i>=0&&this._handlers[e].splice(i,1)}subscribe(e,t,i){let r=e.addEventListener(t,i);this._listeners.push(r)}unsubscribe(){this._listeners.forEach(e=>{e.dispose()})}};var tt=class extends z{get ready(){return!0}setParticipantIdRegistry(e){}requestRealloc(){}setEndpoint(e){}setConversationId(e){}readyToSend(){}cleanup(){}requestTestMode(e){}getNextCommandSequenceNumber(){return 0}};var Ji=(i=>(i.INCOMING="INCOMING",i.OUTGOING="OUTGOING",i.JOINING="JOINING",i))(Ji||{}),Ne=Ji;var Yi=(i=>(i.USER="USER",i.GROUP="GROUP",i.CHAT="CHAT",i))(Yi||{}),De=Yi;var zi=(t=>(t.ATTENDEE="ATTENDEE",t.HAND_UP="HAND_UP",t))(zi||{}),Dt=zi;var Qi=(t=>(t.ADD_PARTICIPANT="ADD_PARTICIPANT",t.RECORD="RECORD",t))(Qi||{}),Xi=Qi;var Zi=(i=>(i.REQUIRE_AUTH_TO_JOIN="REQUIRE_AUTH_TO_JOIN",i.AUDIENCE_MODE="AUDIENCE_MODE",i.WAITING_HALL="WAITING_HALL",i))(Zi||{}),At=Zi;function er(a,e){if(a.length!==e.length)return!1;for(let t of a)if(!e.includes(t))return!1;return!0}function tr(a,e){let t=new Set(a);for(let[i,r]of Object.entries(e))r?t.add(i):t.delete(i);return Array.from(t)}var ir=(x=>(x.CAMERA_PERMISSION="camera",x.MIC_PERMISSION="mic",x.CAMERA_ACCESS="cameralock",x.MIC_ACCESS="miclock",x.MIC_NOT_FOUND="nomic",x.SCREEN_PERMISSION="screenpermission",x.SCREEN_ACCESS="screenlock",x.CONNECTION="connection",x.NETWORK="network",x.UNKNOWN="unknown",x.UNSUPPORTED="unsupported",x.SIGNALING_FAILED="signalingfailed",x.API="api",x.AUTH="auth",x))(ir||{}),Z=ir;var rr=(K=>(K.CANCELED="CANCELED",K.REJECTED="REJECTED",K.REMOVED="REMOVED",K.HUNGUP="HUNGUP",K.MISSED="MISSED",K.BUSY="BUSY",K.FAILED="FAILED",K.NETWORK_ERROR="NETWORK_ERROR",K.KILLED="KILLED",K.BANNED="BANNED",K.CALLER_IS_BLOCKED="CALLER_IS_BLOCKED",K.NOT_FRIENDS="NOT_FRIENDS",K.CALLEE_IS_OFFLINE="CALLEE_IS_OFFLINE",K.UNKNOWN_ERROR="UNKNOWN_ERROR",K.UNSUPPORTED="UNSUPPORTED",K.OLD_VERSION="OLD_VERSION",K.SERVICE_DISABLED="SERVICE_DISABLED",K.EXTERNAL_API_ERROR="EXTERNAL_API_ERROR",K.SOCKET_CLOSED="SOCKET_CLOSED",K.ENDED="ENDED",K))(rr||{}),M=rr;var ar=(i=>(i.AUDIO="AUDIO",i.VIDEO="VIDEO",i.SCREEN_SHARING="SCREEN_SHARING",i))(ar||{}),re=ar;var nr=(i=>(i.UNMUTE="UNMUTE",i.MUTE="MUTE",i.MUTE_PERMANENT="MUTE_PERMANENT",i))(nr||{}),xe=nr;var sr=(r=>(r.CALLED="CALLED",r.ACCEPTED="ACCEPTED",r.REJECTED="REJECTED",r.HUNGUP="HUNGUP",r))(sr||{}),G=sr;var or=(r=>(r.START="start",r.ACCEPT="accept",r.JOIN="join",r.RETRY="retry",r))(or||{}),Ae=or;var cr=(i=>(i.NOTIFICATION="NOTIFICATION",i.FAILED="FAILED",i.RECONNECT="RECONNECT",i))(cr||{}),ue=cr;var dr=(k=>(k.TRANSMITTED_DATA="transmitted-data",k.ACCEPTED_CALL="accepted-call",k.HUNGUP="hungup",k.PARTICIPANT_ADDED="participant-added",k.PARTICIPANT_JOINED="participant-joined",k.CLOSED_CONVERSATION="closed-conversation",k.MEDIA_SETTINGS_CHANGED="media-settings-changed",k.PARTICIPANT_STATE_CHANGED="participant-state-changed",k.RATE_CALL_DATA="rate-call-data",k.FEATURE_SET_CHANGED="feature-set-changed",k.TOPOLOGY_CHANGED="topology-changed",k.PRODUCER_UPDATED="producer-updated",k.CONSUMER_ANSWERED="consumer-answered",k.MULTIPARTY_CHAT_CREATED="multiparty-chat-created",k.FORCE_MEDIA_SETTINGS_CHANGE="force-media-settings-change",k.SETTINGS_UPDATE="settings-update",k.VIDEO_QUALITY_UPDATE="video-quality-update",k.REGISTERED_PEER="registered-peer",k.SWITCH_MICRO="switch-micro",k.RECORD_STARTED="record-started",k.RECORD_STOPPED="record-stopped",k.REALLOC_CON="realloc-con",k.AUDIO_ACTIVITY="audio-activity",k.SPEAKER_CHANGED="speaker-changed",k.STALLED_ACTIVITY="stalled-activity",k.CHAT_MESSAGE="chat-message",k.CUSTOM_DATA="custom-data",k.ROLES_CHANGED="roles-changed",k.MUTE_PARTICIPANT="mute-participant",k.PIN_PARTICIPANT="pin-participant",k.OPTIONS_CHANGED="options-changed",k.NETWORK_STATUS="network-status",k.PARTICIPANT_SOURCES_UPDATE="participant-sources-update",k.PROMOTE_PARTICIPANT="promote-participant",k.CHAT_ROOM_UPDATED="chat-room-updated",k.PROMOTION_APPROVED="promotion-approved",k.JOIN_LINK_CHANGED="join-link-changed",k))(dr||{}),A=dr;var pr=(u=>(u.ERROR="callError",u.DEVICES="callDevices",u.CALL_SPEC_ERROR="callSpecError",u.ICE_CONNECTION_STATE="callIceConnectionState",u.ICE_CONNECTION_TYPE="callIceConnectionType",u.ICE_RESTART="callIceRestart",u.PUSH="callPush",u.OUTGOING_CALL="callStart",u.OUTGOING_MULTIPARTY_CALL="callStartMultiparty",u.JOIN_CONVERSATION="callJoinConversation",u.ACCEPTED_OUTGOING="callAcceptedOutgoing",u.ACCEPT_INCOMING="callAcceptIncoming",u.DECLINE_INCOMING="callDeclineIncoming",u.ACCEPT_CONCURRENT="callAcceptConcurrent",u.HANGUP="callHangup",u.MEDIA_STATUS="callMediaStatus",u.DEVICE_CHANGED="callDeviceChanged",u.SOCKET_ACTION="callSocketAction",u.ADD_PARTICIPANT="callAddParticipant",u.REMOVE_PARTICIPANT="callRemoveParticipant",u.POOR_CONNECTION="callPoorConnection",u.TOPOLOGY_CHANGE_REQUESTED="callTopologyChangeRequested",u.RELAY_POLICY="callForceRelay",u.PAT_ALLOCATED="patAllocate",u.PAT_DEALLOCATED="patDeallocate",u.PAT_ERROR="patError",u.PAT_WAITING_TIME_ERROR="patWaitingTimeError",u.PAT_OUTDATED_RESPONSE="patOutdatedResponse",u))(pr||{}),g=pr;var lr=(t=>(t.AUDIO_MIX="audio-mix",t.PARTICIPANT_AGNOSTIC_TRACK_PREFIX="pat",t))(lr||{}),ye=lr;var ur=(t=>(t.NO_AVAILABLE_TRACKS="no-available-tracks",t.UNKNOWN_ERROR="unknown-error",t))(ur||{}),mr=ur;function hr(a){switch(a){case 1:return"no-available-tracks";default:return"unknown-error"}}var _r=(t=>(t.CREATOR="CREATOR",t.ADMIN="ADMIN",t))(_r||{}),Ge=_r;function _t(a,e){if(a.length!==e.length)return!1;for(let t of a)if(!e.includes(t))return!1;return!0}var gr=(t=>(t.USER="USER",t.GROUP="GROUP",t))(gr||{}),Q=gr;var ei=class{constructor(){this._items=[]}get length(){return this._items.length}push(e){this._items.push(e)}shift(){return this._items.shift()||null}bisect(){let e=this.length>1?Math.floor(this.length/2):1;this._items=this._items.slice(e)}clear(){this._items=[]}toString(){return this._items.length?JSON.stringify(this._items,(e,t)=>t instanceof Error?String(t):t):""}};var fr=2*1024*1024,Ca=512*1024,gt=100*1024,ya=5,ti="_okcls_logs_session_",Ra=3e4,Sr=class{constructor(){this._items=[];this._itemsSize=0;this._storageSize=fr;try{let e=window.localStorage;for(let t of Object.keys(e)){if(t.indexOf(ti)!==0)continue;let i=e.getItem(t);if(!i){Tr(t);continue}let r=Er(i);this.add(t,r)}}catch(e){console.error("Storage is blocked",e),this._storageSize=0}this._items.sort((e,t)=>e.date-t.date),this.cleanup(gt)}get size(){return this._itemsSize}get length(){return this._items.length}get available(){return Math.max(this._storageSize-this._itemsSize,0)}get items(){return this._items}set storageSize(e){this._storageSize=e}add(e,t){let i=parseInt(e.replace(ti,""),10);this._itemsSize+=t,this._items.push({key:e,size:t,date:i})}deleteOldestItem(){let e=this._items.shift();e&&(Tr(e.key),this._itemsSize-=e.size)}cleanup(e){for(;this.length&&(this.size>fr||this.length>ya-1||this.size+e>this.available);)this.deleteOldestItem()}};function vr(){return`${ti}${Date.now()}`}function Er(a){return new Blob([a]).size}function Tr(a){try{window.localStorage.removeItem(a)}catch(e){console.error("Failed to remove log from storage",e)}}function ii(){let a=We.toString();if(!_e.available||!a)return;let e=Er(a);_e.cleanup(e);try{window.localStorage.setItem(Ot,a)}catch(t){if(console.warn("Failed to write log to storage",t),_e.storageSize=_e.size+e,_e.cleanup(gt+e),_e.available>=gt+e){ii();return}if(e>gt){We.bisect(),ii();return}_e.storageSize=0;return}e>Ca&&(_e.add(Ot,e),Ot=vr(),We.clear(),_e.cleanup(gt))}function ri(){!_e.available||!We.length||ii()}function Pa(a=!1){let e=[];try{let r=window.localStorage;for(let s of _e.items){let d=r.getItem(s.key);e.push(d)}let n=We.toString();n&&e.push(n)}catch(r){console.error("Storage is blocked",r)}let t=`[${e.join(",")}]`;if(a)return t;let i=`logs_${Date.now()}.json`;return ba(t,i),i}function ba(a,e){let t=document.createElement("a"),i=new Blob([a],{type:"text/json"});t.href=URL.createObjectURL(i),t.download=e,t.click()}function Ir(a,e){!_e.available||(We.push({t:Date.now(),l:a,d:e}),ni||(ni=window.setTimeout(()=>{ni=null,ri()},Ra)))}function ai(){_e||(_e=new Sr,We=new ei,Ot=vr(),window.addEventListener("beforeunload",ri))}var _e,We,Ot,ni=null;window.__VKCallsSDKLogs__=(a=!1)=>(_e||ai(),ri(),Pa(a));var si=He(require("@vkontakte/libvpx"));var me=(s=>(s.INIT="init",s.READY="ready",s.FRAME="frame",s.ERROR="error",s.DEBUG="debug",s.LOG_ERROR="log_error",s))(me||{});var m=class extends et{constructor(e,t){super();this._batchInterval=3e3;this._batch=[];this._batchTimeout=null;this._api=e,this._externalLogger=t}_send(e){this._api.log(e)}_sendBatch(){this._stopTimeout(),this._batch.length>0&&(this._send(this._batch),this._batch=[],this._startTimeout())}_startTimeout(){this._batchTimeout=window.setTimeout(()=>this._sendBatch(),this._batchInterval)}_stopTimeout(){this._batchTimeout&&(clearTimeout(this._batchTimeout),this._batchTimeout=null)}_onUnload(){this._sendBatch(),this._stopTimeout()}log(e,t,i=!1){let r={};typeof t!="undefined"&&(r.param=t),this._logInternal(e,r,i),this._externalLogger&&this._externalLogger.log(e,t,i)}logCustom(e,t,i=!1){this._logInternal(e,t,i)}_logInternal(e,t,i){let r={type:1,time:0,operation:e,timestamp:Date.now(),custom:t,uid:this._api.getUserId()};this._batch.push(r),(i||!this._batchTimeout)&&this._sendBatch()}destroy(){this._sendBatch(),this._stopTimeout(),this._externalLogger&&this._externalLogger.destroy()}static create(e,t){m._instance||(m._instance=new m(e,t))}static log(e,t,i=!1){m._instance&&m._instance.log(e,t,i)}static logCustom(e,t,i=!1){m._instance&&m._instance.logCustom(e,t,i)}static destroy(){m._instance&&m._instance.destroy(),m._instance=null}};var Oe=class{constructor(){this._worker=null}_createWorker(s,d){return c(this,arguments,function*(e,t,i=[],r={},n=[]){return new Promise((l,h)=>{let P=i.join(","),b=new Blob([e,`exports.default(${P});`],{type:"application/javascript; charset=utf-8"}),j=window.URL.createObjectURL(b);this._worker=new Worker(j),this._worker.onmessage=W=>{switch(W.data.type){case me.READY:l();break;case me.ERROR:h(W.data.error);break;case me.FRAME:t(W.data);break;case me.DEBUG:o.debug(W.data.message);break;case me.LOG_ERROR:m.log(g.ERROR,W.data.message);break}},this._sendToWorker(me.INIT,r,n)})})}_removeWorker(){var e;(e=this._worker)==null||e.terminate(),this._worker=null}_sendToWorker(e,t={},i=[]){var r;(r=this._worker)==null||r.postMessage(Object.assign({type:e},t),i)}static isBrowserSupported(){throw new Error("Not implemented")}};var it=class extends Oe{init(e){return c(this,null,function*(){o.debug("LibVPxDecoder started"),yield this._createWorker('var exports=(()=>{var y=Object.defineProperty;var E=a=>y(a,"__esModule",{value:!0});var M=(a,p)=>{E(a);for(var e in p)y(a,e,{get:p[e],enumerable:!0})};var D={};M(D,{default:()=>V});var t=(s=>(s.INIT="init",s.READY="ready",s.FRAME="frame",s.ERROR="error",s.DEBUG="debug",s.LOG_ERROR="log_error",s))(t||{});var V=(a,p)=>{let e=null,n=null,g=!0;function b(){return a({locateFile:p}).then(r=>n=r)}function s(r,m,l,R,x){if(!n){self.postMessage({type:t.LOG_ERROR,message:"decoder-init-fail-libvpx"}),self.postMessage({type:t.FRAME,error:"Fatal initialization error"});return}if(g!==l&&(g=l,e&&(e=null,self.postMessage({type:t.DEBUG,message:`LibVPxDecoder codec changed to ${l?"VP9":"VP8"} - reinitialize`}))),!e&&(self.postMessage({type:t.DEBUG,message:`LibVPxDecoder codec ${l?"VP9":"VP8"}`}),e=new n.VpxDecoder,e.debug(x),!e.init(l?n.VpxType.VP9:n.VpxType.VP8))){e=null,self.postMessage({type:t.FRAME,error:"Decoder failed to create"});return}try{e.allocateBuffer(m.byteLength).set(new Uint8Array(m))}catch(o){self.postMessage({type:t.DEBUG,message:o}),e=null,self.postMessage({type:t.FRAME,error:String(o)});return}if(!(e.decode()&&e.nextImage())){self.postMessage({type:t.FRAME,error:"Decode failed"});return}let d=e.getImageBuffer();if(!d){self.postMessage({type:t.FRAME,error:"No decoded data"});return}let c=e.getImageWidth(),f=e.getImageHeight();e.nextImage()&&(self.postMessage({type:t.DEBUG,message:"LibVPxDecoder dropped frame"}),self.postMessage({type:t.LOG_ERROR,message:"LibVPxDecoder-drop"}));let i=new Uint8ClampedArray(d.byteLength);if(i.set(d),R){let o=new ImageData(i,c,f);createImageBitmap(o,0,0,c,f).then(u=>{self.postMessage({type:t.FRAME,data:u},[u]),u.close()})}else self.postMessage({type:t.FRAME,data:i.buffer,width:c,height:f},[i.buffer])}b().then(()=>{self.onmessage=r=>{switch(r.data.type){case t.FRAME:s(r.data.timestamp,r.data.data,r.data.isVP9,r.data.useImageBitmap,r.data.debug);break}},self.postMessage({type:t.READY})}).catch(r=>{self.postMessage({type:t.ERROR,error:String(r)})})};return D;})();\n',t=>{if(t.error)o.warn("LibVPxDecoder",t.error);else if(t.data instanceof ArrayBuffer){let i=new ImageData(new Uint8ClampedArray(t.data),t.width,t.height);e(i)}else e(t.data)},[si.default,si.default.getUrl])})}decodeFrame(e,t,i,r){let n="ImageBitmap"in window;this._sendToWorker(me.FRAME,{timestamp:e,data:t.buffer,isVP9:i,keyFrame:r,useImageBitmap:n,debug:o.enabled()},[t.buffer])}destroy(){this._removeWorker(),o.debug("LibVPxDecoder destroyed")}static isBrowserSupported(){return"WebAssembly"in window&&"Worker"in window}};var je=class extends Oe{init(e){return c(this,null,function*(){o.debug("WebCodecsDecoder started"),yield this._createWorker('var exports=(()=>{var l=Object.defineProperty;var f=e=>l(e,"__esModule",{value:!0});var E=(e,d)=>{f(e);for(var a in d)l(e,a,{get:d[a],enumerable:!0})};var y={};E(y,{default:()=>g});var c=(a=>(a.VP9="vp09.00.50.08",a.VP8="vp8",a))(c||{}),o=(t=>(t.INIT="init",t.READY="ready",t.FRAME="frame",t.ERROR="error",t.DEBUG="debug",t.LOG_ERROR="log_error",t))(o||{});var g=()=>{let e=null,d=!0;function a(){self.postMessage({type:o.READY})}function p(r,m,t,n=!1){if(!e||d!==t){if(!n){self.postMessage({type:o.DEBUG,message:"WebCodecsDecoder dropped frame - waiting for keyframe"});return}d=t,e?self.postMessage({type:o.DEBUG,message:`WebCodecsDecoder codec changed to ${t?"VP9":"VP8"}`}):(self.postMessage({type:o.DEBUG,message:`WebCodecsDecoder codec ${t?"VP9":"VP8"}`}),e=new VideoDecoder({output:s=>{("createImageBitmap"in s?s.createImageBitmap():createImageBitmap(s)).then(i=>{self.postMessage({type:o.FRAME,data:i}),i.close()}).finally(()=>s.close())},error:s=>{e&&e.state!=="closed"&&e.close(),e=null,self.postMessage({type:o.FRAME,error:"WebCodecsDecoder failed, reinitialize"})}})),e.configure({codec:t?c.VP9:c.VP8})}let u=new EncodedVideoChunk({type:n?"key":"delta",timestamp:r,data:m});e.decode(u)}self.onmessage=r=>{switch(r.data.type){case o.INIT:a();break;case o.FRAME:p(r.data.timestamp,r.data.data,r.data.isVP9,r.data.keyFrame);break}}};return y;})();\n',t=>{t.error?o.warn("WebCodecsDecoder",t.error):e(t.data)})})}decodeFrame(e,t,i,r=!1){this._sendToWorker(me.FRAME,{timestamp:e,data:t.buffer,isVP9:i,keyFrame:r},[t.buffer])}destroy(){this._removeWorker(),o.debug("WebCodecsDecoder destroyed")}static isBrowserSupported(){return"VideoDecoder"in window&&"Worker"in window&&"VideoFrame"in window&&"ImageBitmap"in window&&"createImageBitmap"in window}};var oi="_okcls_",rt=(()=>{try{let a=Date.now().toString(),e=window.localStorage,t=!1;return e.setItem(a,a),t=e.getItem(a)===a,e.removeItem(a),t?e:null}catch(a){return null}})();function Da(a){let e=rt?rt.getItem(oi+a):null;if(e===null)return null;try{return JSON.parse(e)}catch(t){return null}}function Aa(a,e){try{rt&&rt.setItem(oi+a,JSON.stringify(e))}catch(t){}}function Oa(a){rt&&rt.removeItem(oi+a)}var ci;(i=>{function a(r){return Da(r)||null}i.get=a;function e(r,n){Aa(r,n)}i.set=e;function t(r){Oa(r)}i.remove=t})(ci||(ci={}));var Ue=ci;var at=He(require("big-integer"));function Cr(a,e){if(a.isAudioEnabled!==e.isAudioEnabled||a.isVideoEnabled!==e.isVideoEnabled||a.isScreenSharingEnabled!==e.isScreenSharingEnabled||a.videoStreams.length!==e.videoStreams.length)return!1;for(let t of a.videoStreams)if(!e.videoStreams.find(i=>i.id===t.id&&i.source===t.source))return!1;return!0}function he(a){return Object.assign({isAudioEnabled:!1,isVideoEnabled:!1,isScreenSharingEnabled:!1,videoStreams:[]},a||{})}var yr=a=>a.stop(),Rr=a=>a.getTracks().forEach(yr),di=a=>a.getVideoTracks().forEach(yr),Pr=a=>a.getVideoTracks()[0].clone();var O=class extends Error{constructor(e,t){super();this.name="HangupReason",this.code=t&&t.code||0,this.remote=t&&t.remote||!1,Object.values(M).indexOf(e)>-1?this.hangup=e:this.error=e;let i=[];this.error&&i.push("error"),this.remote&&i.push("remote"),this.code&&i.push(`code: ${this.code}`),t&&t.message&&i.push(`message: '${t.message}'`),this.message=e+(i.length?` (${i.join(", ")})`:""),Error.captureStackTrace&&Error.captureStackTrace(this,O)}};var Se=(i=>(i.SOURCE_CHANGED="SOURCE_CHANGED",i.TRACK_REPLACED="TRACK_REPLACED",i.SCREEN_STATUS="SCREEN_STATUS",i))(Se||{}),se=(i=>(i.audio="audio",i.video="video",i.screen="screen",i))(se||{}),pi=class extends z{constructor(){super();this._stream=null;this._trackVideoStreamBackup=null;this._screenTrack=null;this._sendVideoTrack=null;this._mediaSettings=he();this._videoStatusOnScreenCapturingEnabled=!1;this._effect=null;this._initDeviceChangeListener()}request(){return c(this,arguments,function*(e=[re.AUDIO]){if(this._stream)return;let t=e.includes(re.VIDEO),i=e.includes(re.AUDIO);if(!y.isBrowserSupported())throw new O(Z.UNSUPPORTED);try{this._stream=yield y.getUserMedia(t,i),this._mediaSettings.isVideoEnabled=t&&this._stream.getVideoTracks().filter(r=>r.enabled).length>0||!1,this._mediaSettings.isAudioEnabled=i&&this._stream.getAudioTracks().filter(r=>r.enabled).length>0||!1}catch(r){throw new O(r)}})}getStream(){return this._stream}getScreenTrack(){return this._screenTrack}getSendVideoTrack(e=!1){return this._sendVideoTrack&&!e?this._sendVideoTrack:this._stream?this._stream.getVideoTracks()[0]:null}_getSendAudioTrack(){var e;return((e=this._stream)==null?void 0:e.getAudioTracks()[0])||null}addTrackToPeerConnection(e,t=!1){let i=this.getStream(),r=this._getSendAudioTrack(),n=this.getSendVideoTrack(t);if(!i||!r&&!n)throw new Error("No local stream found");r&&e.addTrack(r,i),n&&e.addTrack(n,i)}getMediaSettings(){return this._mediaSettings}changeDevice(e){return c(this,null,function*(){switch(e){case"videoinput":return this._changeVideoInput();case"audioinput":return this._changeAudioInput();default:return Promise.reject()}})}setVideoStream(e,t){return c(this,null,function*(){return t?this._changeScreen(e):this._changeVideoInput(e)})}_initDeviceChangeListener(){if(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices||!navigator.mediaDevices.addEventListener)return;let e=!1,t=!1,i=E.throttle(()=>{t&&this._changeVideoInput().catch(()=>{}),e&&this._changeAudioInput().catch(()=>{}),e=!1,t=!1},1e3);navigator.mediaDevices.addEventListener("devicechange",()=>c(this,null,function*(){if(!this._stream)return;let r=this._stream.getAudioTracks()[0],n=r&&r.enabled&&r.getSettings(),s=n&&n.groupId,d=this._stream.getVideoTracks()[0],l=d&&d.enabled&&d.getSettings(),h=l&&l.groupId;if(!s&&!h)return;let P=yield navigator.mediaDevices.enumerateDevices();!e&&s&&(e=!P.find(b=>b.groupId===s)),!t&&h&&(t=!P.find(b=>b.groupId===h)),i()}))}_changeVideoInput(e=null){return c(this,null,function*(){try{let t=e?"stream":"video",i=e||(yield y.getUserVideo(void 0,!!this._effect));if(!this._stream)i.getTracks().forEach(r=>r.stop());else{p.consumerScreenTrack||this._disableScreenCapture();let r=this._getVideoEffectTrack(i),n=yield this._videoEffect(this._effect,r);this._stopLocalTrack("video"),m.log(g.DEVICE_CHANGED,t),o.log("Video stream changed"),yield this._replaceLocalTrack(n),this._mediaSettings.isVideoEnabled=!0,this._triggerEvent("SOURCE_CHANGED",{kind:"video",mediaSettings:this._mediaSettings})}}catch(t){throw m.log(g.ERROR,"change_video"),o.warn("Camera change failed",t),t}})}_getVideoEffectTrack(e){let t;return this._effect?(this._trackVideoStreamBackup||(this._trackVideoStreamBackup=Pr(e)),t=this._trackVideoStreamBackup.clone(),di(e)):this._trackVideoStreamBackup?(t=this._trackVideoStreamBackup.clone(),this._stopAndRemoveTrackVideoStreamBackup(),di(e)):t=e.getVideoTracks()[0],t}setAudioStream(e){return c(this,null,function*(){return this._changeAudioInput(e)})}_changeAudioInput(e=null){return c(this,null,function*(){try{if(e=e||(yield y.getUserAudio()),!this._stream)e.getTracks().forEach(t=>t.stop());else{let t=e.getAudioTracks()[0];this._stopLocalTrack("audio"),m.log(g.DEVICE_CHANGED,"audio"),o.log("Audio stream changed"),yield this._replaceLocalTrack(t),this._mediaSettings.isAudioEnabled=!0,this._triggerEvent("SOURCE_CHANGED",{kind:"audio",mediaSettings:this._mediaSettings})}}catch(t){throw m.log(g.ERROR,"change_audio"),o.error("Microphone change failed",t),t}})}_changeScreen(e){return c(this,null,function*(){try{if(e=e||(yield y.getScreenMedia()),e.addEventListener("inactive",()=>{this._mediaSettings.isScreenSharingEnabled&&this.toggleScreenCapturing(!1)},!1),!this._stream)e.getTracks().forEach(t=>t.stop());else{let t=e.getVideoTracks()[0],i=p.consumerScreenTrack?t:yield this._videoEffect(null,t);m.log(g.DEVICE_CHANGED,"screen"),o.log("Screen capturing started"),this._screenTrack=i,this._mediaSettings.isScreenSharingEnabled=!0,p.consumerScreenTrack||(this._videoStatusOnScreenCapturingEnabled=this._mediaSettings.isVideoEnabled,this._mediaSettings.isVideoEnabled=!0,this._stopLocalTrack("video"),this._sendVideoTrack=p.consumerScreenDataChannel?y.getBlackMediaTrack(p.videoMinWidth,p.videoMinHeight):i,yield this._replaceLocalTrack(i,this._sendVideoTrack)),this._triggerEvent("SCREEN_STATUS",{track:i,mediaSettings:this._mediaSettings}),this._triggerEvent("SOURCE_CHANGED",{kind:"screen",mediaSettings:this._mediaSettings})}}catch(t){throw m.log(g.ERROR,"screen"),o.warn("Screen capturing failed",t),t}})}_disableScreenCapture(){this._sendVideoTrack&&(this._sendVideoTrack.stop(),this._sendVideoTrack=null),this._screenTrack&&(this._screenTrack.stop(),this._screenTrack=null),this._mediaSettings.isScreenSharingEnabled&&(this._mediaSettings.isScreenSharingEnabled=!1,this._triggerEvent("SCREEN_STATUS",{mediaSettings:this._mediaSettings}),this._triggerEvent("SOURCE_CHANGED",{kind:"screen",mediaSettings:this._mediaSettings}))}_replaceLocalTrack(e,t){return c(this,null,function*(){!this._stream||this._stream.getTracks().forEach(i=>{var r,n;i.kind===e.kind&&((r=this._stream)==null||r.removeTrack(i),(n=this._stream)==null||n.addTrack(e),this._triggerEvent("TRACK_REPLACED",e,t))})})}_stopLocalTrack(e){this._stream&&this._stream.getTracks().forEach(t=>{t.kind===e&&t.stop()})}_videoEffect(e,t){return c(this,null,function*(){if(!p.videoEffects)return t;try{return m.log(g.DEVICE_CHANGED,`effect_${e}`),p.videoEffects.setEffect(e,t)}catch(i){return o.warn("Video effect failed",i),t}})}_stopAndRemoveTrackVideoStreamBackup(){this._trackVideoStreamBackup&&(this._trackVideoStreamBackup.stop(),this._trackVideoStreamBackup=null)}destroy(){p.videoEffects&&(this._effect=null,p.videoEffects.destroy()),this._stream&&(Rr(this._stream),this._stream=null),this._stopAndRemoveTrackVideoStreamBackup(),this._disableScreenCapture()}toggleScreenCapturing(e){return c(this,null,function*(){return e?this._changeScreen():p.consumerScreenTrack?this._disableScreenCapture():this._videoStatusOnScreenCapturingEnabled?this._changeVideoInput():this.toggleVideo(!1)})}toggleVideo(e){return c(this,null,function*(){if(!this._stream)return;p.consumerScreenTrack||this._disableScreenCapture();let t;if(e){let i=yield y.getUserVideo(void 0,!!this._effect);t=this._getVideoEffectTrack(i),t=yield this._videoEffect(this._effect,t)}else t=y.getBlackMediaTrack(p.videoMinWidth,p.videoMinHeight),t=yield this._videoEffect(null,t),this._stopAndRemoveTrackVideoStreamBackup();this._stopLocalTrack("video"),yield this._replaceLocalTrack(t),this._mediaSettings.isVideoEnabled=e,this._triggerEvent("SOURCE_CHANGED",{kind:"video",mediaSettings:this._mediaSettings})})}toggleAudio(e){return c(this,null,function*(){if(!this._stream)return;let t;e?t=(yield y.getUserAudio()).getAudioTracks()[0]:t=y.getSilentMediaTrack(),this._stopLocalTrack("audio"),yield this._replaceLocalTrack(t),this._mediaSettings.isAudioEnabled=e,this._triggerEvent("SOURCE_CHANGED",{kind:"audio",mediaSettings:this._mediaSettings})})}setResolution(e,t){return c(this,null,function*(){if(!p.consumerScreenTrack&&this._mediaSettings.isScreenSharingEnabled)return;if(!this._stream)throw new Error("Local stream not found");let i=this._stream.getVideoTracks()[0];if(!i)throw new Error("Local video track not found");if(!!i.enabled){if(!this._effect)return i.applyConstraints({width:{ideal:e},height:{ideal:t}});yield this.toggleVideo(!1),yield this.toggleVideo(!0)}})}updateNoiseSuppression(){return c(this,null,function*(){if(!this._stream||!this._mediaSettings.isAudioEnabled)return;let e=this._stream.getAudioTracks()[0];if(!e)throw new Error("Local audio track not found");if(!!e.enabled)return e.applyConstraints({noiseSuppression:p.noiseSuppression})})}videoEffect(e){return c(this,null,function*(){if(!p.videoEffects)throw new Error("Video Effects library is not set");if(!p.consumerScreenTrack&&this._mediaSettings.isScreenSharingEnabled)throw new Error("Can't apply effect to screensharing");if(!this._mediaSettings.isVideoEnabled){this._effect=e;return}if(this._stream&&e!==this._effect)return this._effect=e,this._changeVideoInput(this._stream)})}};var nt=":",kt="d",li;(Qt=>{function a(u,I,D,V,f=!1){let J=/[\r\n]+/,R=`\r
8
+ `;if(!I&&!D&&!V)return f?$(u.split(J)).join(R):u;function $(Y){let Me=["a=rtcp-fb:111 nack","a=rtcp-fb:111 nack pli"],ce="a=rtcp-fb:111",_=Y.findIndex(C=>C.startsWith(ce));return~_&&(Y[_]=Y[_]+R+Me.join(R)),Y}function te(Y,Me,ce){let _=Y.split(" "),C=_.slice(0,3),F;for(F=3;F<_.length;F++)ce.includes(_[F])&&C.push(_[F]);for(F=3;F<_.length;F++)!ce.includes(_[F])&&!Me.includes(_[F])&&C.push(_[F]);return C.join(" ")}function k(Y,Me){let ce=new RegExp("a=rtpmap:(\\d+) ([a-zA-Z0-9-]+)\\/\\d+"),_,C=[];for(_=0;_<Y.length;++_){let F=Y[_].match(ce);F&&F.length===3&&F[2]===Me&&C.push(F[1])}return C}function ge(Y,Me,ce,_){let C,F="m="+Me;for(C=0;C<Y.length;++C)if(Y[C].startsWith(F)){Y[C]=te(Y[C],ce,_);break}}let Le=[],ie=u.split(J);(D||I)&&(Le=k(ie,"H264"));let we=[];if(V&&(we=k(ie,"VP9")),D){let Y=Le.slice(0),Me=new RegExp("a=fmtp:(\\d+) apt=(\\d+)"),ce;for(ce=0;ce<ie.length;++ce){let C=ie[ce].match(Me);C&&C.length===3&&Y.includes(C[2])&&Y.push(C[1])}let _=new RegExp("a=(rtpmap|rtcp-fb|fmtp):(\\d+) .*");for(ce=ie.length;ce--;){let C=ie[ce].match(_);C&&C.length===3&&Y.includes(C[2])&&ie.splice(ce,1)}ge(ie,"video",Y,[])}else I&&ge(ie,"video",[],Le);return V&&ge(ie,"video",[],we),f&&$(ie),ie.join(R)}Qt.patchSDP=a;function e(u){return u?`${u.type||"WEB_SOCKET"}_${u.id}`:"_"}Qt.getPeerIdString=e;function t(u,I){return u&&u.id===I.id&&(u.type||"WEB_SOCKET")===(I.type||"WEB_SOCKET")}Qt.comparePeerId=t;function i(u){return c(this,null,function*(){return!u||!u.getStats?Promise.resolve(null):u.getStats(null).then(I=>{let D=null,V=null;if(I.forEach(f=>{f.type==="transport"&&f.selectedCandidatePairId?V=I.get(f.selectedCandidatePairId):f.type==="candidate-pair"&&f.state==="succeeded"&&!V&&(!f.hasOwnProperty("selected")||f.selected)&&(V=f)}),V&&V.localCandidateId){let f=I.get(V.localCandidateId);f&&(D={type:f.candidateType,ip:f.ip||f.ipAddress,port:f.port||f.portNumber})}return D}).catch(()=>null)})}Qt.getPeerConnectionHostInfo=i;let r=/^[0-9]+$/,n=/^([gu])([0-9]+)$/;function s(u,I){let D=String(u);return n.test(D)?(o.warn(`Already composite id [${u}] type supplied [${I}]`),D):I===Q.GROUP?"g"+D:I===Q.USER?"u"+D:(o.warn(`Unknown type [${I}] for id [${u}]`),D.match(r)?"u"+D:D)}Qt.composeUserId=s;function d(u,I,D){let V=s(u,I);return l(V,D)}Qt.composeParticipantId=d;function l(u,I){return I?u+nt+kt+I:u}Qt.compose=l;function h(u){return d(u.id,u.idType||Q.USER,u.deviceIdx||0)}Qt.composeId=h;function P(u){return u.participant?h(u.participant):d(u.participantId,u.participantType||Q.USER,u.deviceIdx||0)}Qt.composeMessageId=P;function b(u){let I=String(u),D=I.match(n);return D?{id:Number(D[2]),type:D[1]==="g"?Q.GROUP:Q.USER}:(o.warn(`Unsupported compositeId [${u}]`),{id:Number(I),type:Q.USER})}Qt.decomposeId=b;function j(u){let I=u.split(nt+kt);return{compositeUserId:I[0],deviceIdx:I.length>1?parseInt(I[1],10):0}}Qt.decomposeParticipantId=j;function W(){let u="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),I=new Array(36),D=0,V,f;for(f=0;f<36;f++)f===8||f===13||f===18||f===23?I[f]="-":f===14?I[f]="4":(D<=2&&(D=33554432+Math.random()*16777216|0),V=D&15,D=D>>4,I[f]=u[f===19?V&3|8:V]);return I.join("")}Qt.uuid=W;function x(u,I){let D;function V(){let f=this,J=arguments;D&&window.clearTimeout(D),D=window.setTimeout(()=>{u.apply(f,J)},I)}return V}Qt.throttle=x;function le(u){let I="",D=u.split(`
9
+ `);for(let R of D)if(R.startsWith("a=fingerprint")){let $=R.split(" ");if($.length===2){I=$[1];break}}if(!I)return at.default.minusOne;let V=I.split(":"),f=at.default.zero;for(let R=Math.min(7,V.length-1);R>=0;R--){let $=(0,at.default)(V[R],16);f=f.shiftLeft(8).or($)}return((R,$)=>{let te=$.value;if(typeof te=="bigint")return(0,at.default)(BigInt.asIntN(R,te));let k=at.default.one.shiftLeft(R),ge=$.and(k.subtract(1));return ge.greaterOrEquals(k.subtract(ge))?ge.subtract(k):ge})(64,f)}Qt.sdpFingerprint=le;function be(u){return c(this,null,function*(){return new Promise(I=>window.setTimeout(I,u))})}Qt.delay=be;function oe(u,I,D){let V=[];return u.getSenders().forEach(f=>Fe(I,f,f.track,D,V)),V}Qt.applySettings=oe;function Fe(u,I,D,V,f){if(u&&D&&D.kind===se.video){let J=D.getSettings();if(J){let R=u.maxBitrateK?u.maxBitrateK*1024:null,$=J.width,te=J.height,k=$&&te&&u.maxDimension?Math.max(1,Math.max($,te)/u.maxDimension):null,ge=u.maxFramerate?u.maxFramerate:null,Le=u.degradationPreference?u.degradationPreference:"balanced",ie=V[D.id];if(ie&&ie.bitrate===R&&ie.scaleResolutionDownBy===k&&ie.maxFramerate===ge&&ie.degradationPreference===Le){f[D.id]=ie;return}f[D.id]={bitrate:R,scaleResolutionDownBy:k,maxFramerate:ge,degradationPreference:Le};let we=I.getParameters();we.encodings||(we.encodings=[{}]),we.encodings.forEach(Y=>{R?Y.maxBitrate=R:delete Y.maxBitrate,k?Y.scaleResolutionDownBy=k:delete Y.scaleResolutionDownBy,ge?Y.maxFramerate=ge:delete Y.maxFramerate}),we.degradationPreference=Le,I.setParameters(we)}}}Qt.applyVideoTrackSettings=Fe;function ne(u,I){Array.isArray(I)||(I=[I]);for(let D of I)if(u.includes(D))return!0;return!1}Qt.includesOneOf=ne;function K(u){var I;return Object.entries(((I=u.participantState)==null?void 0:I.state)||{}).reduce((D,[V,f])=>(u.participantState&&(D[V]={ts:u.participantState.stateUpdateTs[V],state:f}),D),{})}Qt.mapParticipantState=K;function Ce(u){return Object.entries(u).reduce((I,[D,{state:V}])=>(I[D]=V,I),{})}Qt.mapLegacyParticipantState=Ce;function ut(u){return u.map(I=>{let D={uid:I.externalId,mediaSettings:I.mediaSettings,status:I.status,muteStates:I.muteStates,unmuteOptions:I.unmuteOptions};return p.participantStateMapped&&(D.participantState=I.participantState),D})}Qt.mapSharedParticipants=ut;function Bi(u,I){let D=Object.keys(u),V=Object.keys(I);if(D.length!==V.length)return!1;for(let f of D)if(!V.hasOwnProperty(f)||u[f].state!==I[f].state||u[f].ts!==I[f].ts)return!1;return!0}Qt.isEqualParticipantState=Bi;function Vi(u,I){let D=Object.keys(u),V=Object.keys(I);if(D.length!==V.length)return!1;for(let f of D)if(!I.hasOwnProperty(f)||u[f]!==I[f])return!1;return!0}Qt.isObjectsEquals=Vi;function Fi(u,I){if(u.length!==I.length)return!1;for(let D of u)if(I.indexOf(D)<0)return!1;return!0}Qt.isArraysEquals=Fi;function Hi(u){return!Object.keys(u).length}Qt.isEmptyObject=Hi})(li||(li={}));var E=li;var Ke=null,ui=null,wt=[],Nt=[],mi=[],ft=null,St=null,hi=null,_i=!1,gi=!1,xt,st,Lt,br=!1,Mr=!1,fi=null,Si="",Ut=[],vi=null,Dr=navigator.appVersion,ka=navigator.appName,ve=navigator.userAgent,Ei=(r=>(r.USER="user",r.ENVIRONMENT="environment",r.LEFT="left",r.RIGHT="right",r))(Ei||{}),vt=class{constructor(e,t=!1,i=p.videoMaxWidth,r=p.videoMaxHeight){let n=!1;if(e){n={noiseSuppression:p.noiseSuppression,echoCancellation:!0,autoGainControl:!0};let d;St&&(d=St.deviceId),typeof e=="string"&&(d=e),d&&(n.deviceId={exact:d})}let s=!1;if(t){s={width:{min:p.videoMinWidth,max:i,ideal:i},height:{min:p.videoMinHeight,max:r,ideal:r},aspectRatio:{ideal:p.videoAspectRatio},frameRate:{ideal:p.videoFrameRate}};let d;ft&&(d=ft.deviceId),typeof t=="string"&&(d=t),d&&(s.deviceId={exact:d}),p.videoFacingMode&&(s.facingMode={exact:p.videoFacingMode})}this.audio=n,this.video=s,this.needVideo=!!s}getNative(){return Object.assign({},{audio:this.audio,video:this.video})}simplify(){return typeof this.video=="object"&&(this.video.width||this.video.height?(delete this.video.width,delete this.video.height):this.video.aspectRatio?delete this.video.aspectRatio:this.video.frameRate?delete this.video.frameRate:(this.video.deviceId||this.video.facingMode)&&(delete this.video.deviceId,delete this.video.facingMode)),typeof this.audio=="object"&&(this.audio.echoCancellation||this.audio.autoGainControl||this.audio.noiseSuppression?(delete this.audio.echoCancellation,delete this.audio.autoGainControl,delete this.audio.noiseSuppression):this.audio.deviceId&&delete this.audio.deviceId),this.video===!0&&this.audio===!0?this.video=!1:this.video===!1&&this.audio===!0?(this.audio=!1,this.video=this.needVideo):this.video===!0&&this.audio===!1&&(this.video=!1),this.video&&!Object.keys(this.video).length&&(this.video=!0),this.audio&&!Object.keys(this.audio).length&&(this.audio=!0),this}canSimplify(){let e=typeof this.video=="object"&&(this.video.width||this.video.height||this.video.aspectRatio||this.video.frameRate||this.video.facingMode||this.video.deviceId)||this.video;return!!(typeof this.audio=="object"&&(this.audio.deviceId||this.audio.noiseSuppression||this.audio.echoCancellation||this.audio.autoGainControl)||this.audio||e)}isVideo(){return!!this.video}isAudio(){return!!this.audio}},Ar=class extends vt{constructor(e,t){super(!1,!0);typeof this.video=="object"?(delete this.video.deviceId,delete this.video.aspectRatio,delete this.video.frameRate,delete this.video.facingMode):this.video={},this.video.cursor="motion",this.video.width=e,this.video.height=t,this.video.frameRate=p.screenFrameRate}};function wa(){return c(this,null,function*(){Ke=null,yield Bt()})}function Na(){Ke=null,Bt().then(()=>T.onDeviceChange())}function Bt(){return c(this,null,function*(){return Ke||(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices?[]:(!ui&&navigator.mediaDevices.addEventListener&&(ui=E.throttle(Na,1e3),navigator.mediaDevices.addEventListener("devicechange",ui)),Ke=navigator.mediaDevices.enumerateDevices().then(a=>{wt=a.filter(r=>r.kind==="videoinput"?(r.label&&(_i=!0),!0):!1),Nt=a.filter(r=>r.kind==="audioinput"?(r.label?gi=!0:$e.isMobile()&&$e.browserName()==="Firefox"&&(gi=_i),!0):!1),mi=a.filter(r=>r.kind==="audiooutput");let e=Ue.get("videoinput"),t=Ue.get("audioinput"),i=Ue.get("audiooutput");return ft=wt.find(r=>r.deviceId===e)||null,St=Nt.find(r=>r.deviceId===t)||null,hi=mi.find(r=>r.deviceId===i)||null,Ke=Promise.resolve(a),a}).catch(()=>(Ke=null,[]))))})}function xa(){return c(this,null,function*(){return $e.isBrowserSupported()?new Promise(a=>{new window.RTCPeerConnection().createOffer({offerToReceiveVideo:!0}).then(t=>{/^a=rtpmap:\d+ VP8\/\d+$/m.test(t.sdp)&&(br=!0),/^a=mid:0$/m.test(t.sdp)&&(Mr=!0),a()}).catch(a)}):Promise.resolve()})}function Vt(a,e){return c(this,null,function*(){o.debug("Try to get media",a.getNative());let t=$e.hasPermissions(a.isVideo());!t&&!e&&T.onPermissionsRequested();try{let i=yield navigator.mediaDevices.getUserMedia(a.getNative());return t||(yield wa()),i}catch(i){switch(i.name){case"PermissionDeniedError":case"PermissionDismissedError":case"NotAllowedError":case"SecurityError":case"DOMException":e=a.isVideo()?Z.CAMERA_PERMISSION:Z.MIC_PERMISSION;break;case"OverconstrainedError":case"TypeError":case"NotFoundError":break;case"AbortError":case"NotReadableError":e=a.isVideo()?Z.CAMERA_ACCESS:Z.MIC_ACCESS;break}if(a.canSimplify())return Vt(a.simplify(),e);let r=e||Z.UNKNOWN;throw T.onPermissionsError(r),r}})}function La(a){return c(this,null,function*(){o.debug("Try to get screen",a.getNative());try{let e=yield navigator.mediaDevices.getDisplayMedia(a.getNative()),t=e==null?void 0:e.getVideoTracks()[0];return t&&(o.debug("Got display media track",t.id),t.contentHint="text"),e}catch(e){switch(e.name){case"PermissionDeniedError":case"NotAllowedError":case"SecurityError":throw Z.SCREEN_PERMISSION;default:throw Z.SCREEN_ACCESS}}})}function Ti(){return Ut.length||(Ut=(()=>{let a,e=!1,t=0,i=ve.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];if(/trident/i.test(i[1]))return a=/\brv[ :]+(\d+)/g.exec(ve),["IE",a&&a[1]||"Unknown",e,t];if(i[1]==="Safari"){if(a=ve.match(/\bEdge\/(\d+)/),a)return["Edge",a[1]||"Unknown",e,t];if(a=ve.match(/\bCriOS\/(\d+)/),a)return["Chrome",a[1],!0,a[1]];if(a=ve.match(/\bFxiOS\/(\d+)/),a)return["Firefox",a[1],!1,t];if(a=ve.match(/\bYaBrowser\/(\d+)/),a)return["Yandex",a[1],!1,t];if(a=ve.match(/\bOPT\/(\d+)/),a)return["Opera",a[1],!1,t]}if(i[1]==="Chrome"){if(e=!0,t=Number(i[2]),a=ve.match(/\bOPR\/(\d+)/),a)return["Opera",a[1]||"Unknown",e,t];if(a=ve.match(/\bYaBrowser\/(\d+)/),a)return["Yandex",a[1]||"Unknown",e,t];if(a=ve.match(/\bSferum\/((\d+)(?:\.\d+)*)/),a)return["Sferum",a[1]||"Unknown",e,t];if(a=ve.match(/\bEdge?\/(\d+)/),a)return["Edge",a[1]||"Unknown",e,t];if(typeof window.opr!="undefined"&&/^(.+\.)?ok.ru$/.test(window.location.host))return["Opera","Hidden",e,t]}return a=ve.match(/version\/(\d+)/i),[i[2]?i[1]:ka,a&&a[1]||i[2]||Dr,e,t]})()),Ut}var $e;(V=>{function a(){return c(this,null,function*(){return yield xa(),Bt()})}V.init=a;function e(){return wt}V.getCameras=e;function t(){return Nt}V.getMicrophones=t;function i(){return mi}V.getOutput=i;function r(){return wt.length>0}V.hasCamera=r;function n(){return Nt.length>0}V.hasMicrophone=n;function s(){return ft}V.getSavedCamera=s;function d(){return St}V.getSavedMicrophone=d;function l(){return hi}V.getSavedOutput=l;function h(){return _i}V.hasCameraPermission=h;function P(){return gi}V.hasMicrophonePermission=P;function b(f=!1){return P()?r()&&f?h():!0:!1}V.hasPermissions=b;function j(f=!1,J=!0){return c(this,null,function*(){let R=n()&&J,$=r()&&f,te;if(!R&&!$)te=new MediaStream;else try{te=yield Vt(new vt(R,$))}catch(k){te=new MediaStream}return te.getVideoTracks().length||te.addTrack(Fe()),te.getAudioTracks().length||te.addTrack(oe()),te})}V.getUserMedia=j;function W(){return c(this,null,function*(){return La(new Ar(window.screen.width,window.screen.height))})}V.getScreenMedia=W;function x(f,J=!1){return c(this,null,function*(){let R=J?p.videoEffectMaxWidth:p.videoMaxWidth,$=J?p.videoEffectMaxHeight:p.videoMaxHeight;return Vt(new vt(!1,f||!0,R,$))})}V.getUserVideo=x;function le(f){return c(this,null,function*(){return Vt(new vt(f||!0,!1))})}V.getUserAudio=le;function be(f,J){return c(this,null,function*(){let $=(yield Bt()).find(te=>te.kind===f&&te.deviceId===J);return $?(f==="videoinput"?ft=$:f==="audioinput"?St=$:f==="audiooutput"&&(hi=$),Ue.set(f,J),$):null})}V.saveDeviceId=be;function oe(){if(!Lt||Lt.readyState==="ended"){let f=D(),J=f.createMediaStreamDestination(),R=f.createGain();R.gain.value=1e-5,R.connect(J),R.connect(f.destination);let $=f.createOscillator();$.type="sine",$.frequency.value=0,$.connect(R),$.start(),Lt=J.stream.getAudioTracks()[0]}return Object.assign(Lt.clone(),{enabled:!1})}V.getSilentMediaTrack=oe;function Fe(f=p.videoMinWidth,J=p.videoMinHeight){return st||(st=document.createElement("canvas"),st.getContext("2d")),st.width=f,st.height=J,(!xt||xt.readyState==="ended")&&(xt=st.captureStream(p.videoFrameRate).getVideoTracks()[0]),Object.assign(xt.clone(),{enabled:!1})}V.getBlackMediaTrack=Fe;function ne(){if(Qt()==="Edge"&&u()<70)return!1;try{let f=window;return navigator.mediaDevices&&navigator.mediaDevices.getUserMedia&&f.RTCPeerConnection&&f.RTCIceCandidate&&f.RTCSessionDescription&&f.HTMLCanvasElement&&f.HTMLCanvasElement.prototype.captureStream&&f.RTCRtpSender&&f.RTCRtpSender.prototype.replaceTrack&&f.RTCRtpSender.prototype.getParameters&&navigator.sendBeacon&&!0||!1}catch(f){return!1}}V.isBrowserSupported=ne;function K(){return!!navigator.mediaDevices.getDisplayMedia}V.isScreenCapturingSupported=K;function Ce(){return br}V.canVP8=Ce;function ut(){return Mr}V.isUnifiedPlan=ut;function Bi(){return V.browserName()==="Opera"&&V.os()==="Windows"}V.isBrokenH264=Bi;function Vi(){return!(V.baseChromeVersion()&&V.isMobile())}V.canPreferH264=Vi;function Fi(){return Si||(Si=(()=>{let f={Windows:/Win/,Android:/Android/,OpenBSD:/OpenBSD/,SunOS:/SunOS/,Linux:/(Linux|X11)/,iPad:/(iPad)/,iPhone:/(iPhone)/,iPod:/(iPod)/,MacOS:/(MacPPC|MacIntel|Mac_PowerPC|Macintosh|Mac OS X)/,QNX:/QNX/,UNIX:/UNIX/,BeOS:/BeOS/,OS2:/OS\/2/,Bot:/(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/};for(let J in f)if(f.hasOwnProperty(J)&&f[J].test(ve))return J;return"Unknown"})()),Si}V.os=Fi;function Hi(){return fi===null&&(fi=/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(Dr)),fi}V.isMobile=Hi;function Qt(){return Ti()[0]}V.browserName=Qt;function u(){return Ti()[1]}V.browserVersion=u;function I(){return Ti()[3]}V.baseChromeVersion=I;function D(){return vi||(vi=new(window.AudioContext||window.webkitAudioContext)),vi}V.getAudioContext=D})($e||($e={}));var y=$e;var Or=He(require("bit-buffer"));var Ua=65536,qe=class{constructor(e,t){this._chunks=[];this._participantId=e,this._onStream=t}appendChunk(e){let t=this._chunks.length;if(e.start)t&&(o.warn("[FrameBuilder] Cleanup buffer",Array.prototype.slice.call(this._chunks)),this._chunks=[]);else if(!t||(this._chunks[t-1].sequence+1)%Ua!==e.sequence){o.warn("[FrameBuilder] Got incorrect chunk");return}if(this._chunks.push(e),e.end){let i=this._processFrameData(),{width:r,height:n}=qe.getFrameSize(i);this._processFrame({timestamp:e.timestamp,frameData:i,isVP9:e.isVP9,keyframe:e.keyframe,width:r,height:n})}}destroy(){this._chunks=[]}_processFrameData(){let e=this._chunks;this._chunks=[];let t=e.reduce((n,s)=>n+s.data.byteLength,0),i=new Uint8Array(t),r=0;for(let n of e)i.set(new Uint8Array(n.data),r),r+=n.data.byteLength;return i}static getFrameSize(e){let t={width:0,height:0},i=new Or.BitStream(e.buffer);i.bigEndian=!0,i.index+=2;let r=i.readBits(1),s=i.readBits(1)<<1|r;return s===3&&i.index++,i.readBits(1)===1||i.readBits(1)!==0||(i.index++,i.index++,i.index+=24,s>=2&&i.index++,i.readBits(3)!==7?(i.index++,(s===1||s===3)&&(i.index+=3)):(s===1||s===3)&&i.index++,t.width=i.readBits(16)+1,t.height=i.readBits(16)+1),t}static isBrowserSupported(){throw new Error("Method `isBrowserSupported` is not implemented")}};var Et=class extends qe{constructor(e,t){super(e,t);this._decoderReady=!1;this._decoderQueue=[];this._canvas=null;this._canvasContext=null;this._stream=null;this._track=null;o.debug(`StreamBuilder started for participant [${e}]`),this._useImageBitmap="ImageBitmap"in window,je.isBrowserSupported()?this._decoder=new je:this._decoder=new it,this._decoder.init(i=>this._drawImage(i)).then(()=>{this._decoderReady=!0,this._decodeQueue()})}_createStream(e,t){this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.width=e,this._canvas.height=t,this._canvas.style.pointerEvents="none",this._canvas.style.visibility="hidden",this._canvas.style.position="absolute",this._canvas.style.width="160px",this._canvas.style.height="90px",this._canvas.style.bottom="0",this._canvas.style.right="0",this._canvas.style.zIndex="5000",document.body.appendChild(this._canvas),this._useImageBitmap?this._canvasContext=this._canvas.getContext("bitmaprenderer"):this._canvasContext=this._canvas.getContext("2d"),this._stream=this._canvas.captureStream(0),this._track=this._stream.getVideoTracks()[0],this._track.contentHint="text")}_removeStream(){this._stream&&(this._stream.getTracks().forEach(e=>e.stop()),this._stream=null,this._track=null),this._canvasContext=null;try{this._canvas&&document.body.removeChild(this._canvas)}catch(e){}this._canvas=null}_requestCanvasFrame(){this._track&&this._track.requestFrame?this._track.requestFrame():this._stream&&this._stream.requestFrame&&this._stream.requestFrame()}_drawImage(e){this._track||(this._createStream(e.width,e.height),this._onStream(this._stream));let t=this._canvas;if(t.width=e.width,t.height=e.height,e instanceof ImageData){let i=this._canvasContext;i.clearRect(0,0,t.width,t.height),i.putImageData(e,0,0)}else this._canvasContext.transferFromImageBitmap(e);this._requestCanvasFrame()}_processFrame(e){!this._decoderReady||this._decoderQueue.length?(this._decoderQueue.push(e),this._decodeQueue()):this._decoder.decodeFrame(e.timestamp,e.frameData,e.isVP9,e.keyframe)}_decodeQueue(){if(!this._decoderReady)return;let e=this._decoderQueue;this._decoderQueue=[],e.forEach(t=>{this._decoder.decodeFrame(t.timestamp,t.frameData,t.isVP9,t.keyframe)})}destroy(){super.destroy(),this._decoder.destroy(),this._removeStream(),o.debug(`StreamBuilder destroyed for participant ${this._participantId}`)}static isBrowserSupported(){return("CanvasCaptureMediaStream"in window||"CanvasCaptureMediaStreamTrack"in window)&&!(y.browserName()==="Safari"&&y.browserVersion()>=15)}};var Ft=1,Ba=1,kr=0,wr=11,Nr=1,xr=2,Lr=4,Ur=8;function Br(a,e,t,i,r,n,s){let d=0;e&&(d|=Nr),t&&(d|=xr),i&&(d|=Lr),s||(d|=Ur);let l=new ArrayBuffer(wr),h=new DataView(l);if(h.setUint8(0,Ft),h.setUint16(1,r),h.setUint32(3,a),h.setUint8(7,n?1:0),h.setUint16(8,kr),h.setUint8(10,d),!s)return l;let P=new Uint8Array(l.byteLength+s.byteLength);return P.set(new Uint8Array(l),0),P.set(new Uint8Array(s),l.byteLength),P.buffer}function Vr(a){let e=new DataView(a),t=e.getUint8(0),i=e.getUint16(1),r=e.getUint32(3),n=e.getUint8(7)===1,s=e.getUint16(8),d=e.getUint8(10),l=!!(d&Nr),h=!!(d&xr),P=!!(d&Lr),b=!!(d&Ur);if(t!==Ft)throw new Error(`Unexpected protocol version. Got ${t}, expected ${Ft}`);return{timestamp:r,start:l,end:h,keyframe:P,sequence:i,isVP9:n,ssrc:s,eos:b,data:a.slice(wr)}}function Fr(a){if(!a||!a.byteLength||a.byteLength!==4)return!1;let e=new DataView(a);return!(e.getUint8(0)!==Ft||e.getUint8(1)!==Ba||e.getUint16(2)!==kr)}var S=He(require("simple-ebml-builder"));var Va=ji(2,15)-1,Ii=1,Fa=5,Ha=5;var Ht=class{constructor(e){this._queue=[];this._clearBufferTill=0;this._mediaSource=new MediaSource,this._codec=e;let t=()=>{this._mediaSource.removeEventListener("sourceopen",t),this._initBuffer(),this._handleQueue()};this._mediaSource.addEventListener("sourceopen",t,!1)}_handleQueue(){if(!this._sourceBuffer||this._sourceBuffer.updating||!this._queue.length)return;if(this._clearBufferTill&&this._sourceBuffer.buffered.length){let i=this._sourceBuffer.buffered.start(0);i<this._clearBufferTill&&(this._sourceBuffer.remove(i,this._clearBufferTill),o.debug(`[WebmBuilder] SourceBuffer cleanup from ${i} to ${this._clearBufferTill}`)),this._clearBufferTill=0;return}let e=this._queue;this._queue=[];let t=Ht._buildQueue(e);this._sourceBuffer.appendBuffer(t)}static _buildQueue(e){if(e.length){if(e.length===1)return S.build(e[0])}else return new Uint8Array;let t=e.reduce((n,s)=>n+s.countSize(),0),i=new Uint8Array(t),r=0;for(let n of e){let s=S.build(n);i.set(s,r),r+=s.byteLength}return i}_initBuffer(){this._sourceBuffer=this._mediaSource.addSourceBuffer(`video/webm; codecs="${this._codec}"`),this._sourceBuffer.mode="sequence",this._sourceBuffer.addEventListener("updateend",()=>this._handleQueue())}changeType(e){var t;return this._codec=e,(t=this._sourceBuffer)==null?void 0:t.changeType(e)}append(e,t=!1){this._queue.push(e),t&&this._handleQueue()}cleanup(){var n,s,d;((n=this._mediaSource)==null?void 0:n.readyState)==="open"&&((s=this._sourceBuffer)==null||s.abort());let e=(d=this._sourceBuffer)==null?void 0:d.buffered,t=e==null?void 0:e.length;if(!t)return;let i=e.start(0),r=Math.max(0,e.end(t-1)-Fa);r-i>Ha&&(this._clearBufferTill=r)}destroy(){this._queue=[],this._mediaSource.readyState==="open"&&(this._sourceBuffer.abort(),this._mediaSource.endOfStream()),this._sourceBuffer=null,this._clearBufferTill=0}get codec(){return this._codec}get mediaSource(){return this._mediaSource}get buffered(){var e;return(e=this._sourceBuffer)==null?void 0:e.buffered}},Re=class extends qe{constructor(e,t){super(e,t);this._video=null;this._stream=null;this._earliestTimestamp=0;this._clusterStartTime=0;this._lastFrameTimestamp=0;o.debug(`[WebmBuilder] started for participant [${e}]`)}static _intToU16BE(e){return new Uint8Array([e>>8,e])}static _genWebmHeader(){return S.element(S.ID.EBML,[S.element(S.ID.EBMLVersion,S.number(1)),S.element(S.ID.EBMLReadVersion,S.number(1)),S.element(S.ID.EBMLMaxIDLength,S.number(4)),S.element(S.ID.EBMLMaxSizeLength,S.number(8)),S.element(S.ID.DocType,S.string("webm")),S.element(S.ID.DocTypeVersion,S.number(2)),S.element(S.ID.DocTypeReadVersion,S.number(2))])}static _genSegmentHeader(e,t,i){let r=S.element(S.ID.Info,[S.element(S.ID.TimecodeScale,S.number(1e6)),S.element(S.ID.MuxingApp,S.string("vk-webm-builder")),S.element(S.ID.WritingApp,S.string("vk-webm-builder"))]),n=[S.element(S.ID.PixelWidth,S.number(e)),S.element(S.ID.PixelHeight,S.number(t))],s=S.element(S.ID.Tracks,S.element(S.ID.TrackEntry,[S.element(S.ID.TrackNumber,S.number(Ii)),S.element(S.ID.TrackUID,S.number(Ii)),S.element(S.ID.TrackType,S.number(1)),S.element(S.ID.FlagLacing,S.number(0)),S.element(S.ID.DefaultDuration,S.number(1e9)),S.element(S.ID.CodecID,S.string(`V_${i.toUpperCase()}`)),S.element(S.ID.Video,n)]));return S.unknownSizeElement(S.ID.Segment,[r,s])}static _genClusterHeader(e){return S.unknownSizeElement(S.ID.Cluster,[S.element(S.ID.Timecode,S.number(Math.round(e)))])}_createVideo(e){this._mediaBuffer=new Ht(e),this._video=document.createElement("video"),this._video.autoplay=!0,this._video.controls=!1,this._video.muted=!0,this._video.style.pointerEvents="none",this._video.style.visibility="hidden",this._video.style.position="absolute",this._video.style.width="160px",this._video.style.height="90px",this._video.style.bottom="0",this._video.style.right="0",this._video.style.zIndex="5000",this._video.src=URL.createObjectURL(this._mediaBuffer.mediaSource),document.body.appendChild(this._video);let t=()=>{if(this._video.src){o.warn(`[WebmBuilder] Video paused for participant [${this._participantId}], try to play again`);let i=this._video.seekable;i.length&&(this._video.currentTime=i.end(i.length-1)-.1),this._video.play().catch(()=>{})}};this._video.onpause=t,this._video.onwaiting=t,this._video.onstalled=t,this._video.onerror=()=>o.warn(`[WebmBuilder] Video Error for participant [${this._participantId}]`,this._video.error),this._stream=this._video.captureStream(),this._onStream(this._stream)}_processFrame(e){let t=e.isVP9?"vp9":"vp8";this._mediaBuffer?this._mediaBuffer.codec!==t&&this._mediaBuffer.changeType(t):this._createVideo(t);let i=e.timestamp;if(i<=this._lastFrameTimestamp&&(i=this._lastFrameTimestamp+10,o.debug(`[WebmBuilder] Fixup timestamp for participant [${this._participantId}]`)),this._lastFrameTimestamp=i,this._earliestTimestamp)i-=this._earliestTimestamp;else{if(!e.keyframe)return;this._earliestTimestamp=i,i=0}if(e.keyframe){this._clusterStartTime=i,this._mediaBuffer.cleanup(),o.debug(`[WebmBuilder] Segment header for participant [${this._participantId}]`);let s=Re._genWebmHeader();this._mediaBuffer.append(s);let d=Re._genSegmentHeader(e.width,e.height,t);this._mediaBuffer.append(d)}let r=Math.round(i-this._clusterStartTime);if(r>Va&&(this._clusterStartTime=i,r=0),r===0){o.debug(`[WebmBuilder] Cluster header for participant [${this._participantId}]`);let s=Re._genClusterHeader(this._clusterStartTime);this._mediaBuffer.append(s)}let n=S.element(S.ID.SimpleBlock,[S.vintEncodedNumber(Ii),S.bytes(Re._intToU16BE(r)),S.number((e.keyframe?1:0)<<7),S.bytes(e.frameData)]);this._mediaBuffer.append(n,!0)}destroy(){super.destroy(),this._video&&(this._video.onpause=null,this._video.onwaiting=null,this._video.onstalled=null,this._video.onerror=null,this._video.pause(),this._video.src="",document.body.removeChild(this._video)),this._mediaBuffer&&(this._mediaBuffer.destroy(),this._mediaBuffer=null),this._stream&&(this._stream.getTracks().forEach(e=>e.stop()),this._stream=null),o.debug(`[WebmBuilder] destroyed for participant [${this._participantId}]`)}static isBrowserSupported(){var e,t,i;return"captureStream"in((e=window.HTMLVideoElement)==null?void 0:e.prototype)&&((t=window.MediaSource)==null?void 0:t.isTypeSupported('video/webm; codecs="vp8"'))&&((i=window.MediaSource)==null?void 0:i.isTypeSupported('video/webm; codecs="vp9"'))}};var ot=class{constructor(e,t,i,r){this._participantIdRegistry=null;this._streamBuilders={};this._onStream=()=>{};this._onEos=()=>{};o.debug("ScreenCaptureReceiver started"),this._datachannel=e,this._participantIdRegistry=t,this._onStream=i,this._onEos=r,this._datachannel.onmessage=n=>this._onDataChannelMessage(n.data)}_onDataChannelMessage(e){var n,s;let t=Vr(e),i=(s=(n=this._participantIdRegistry)==null?void 0:n.getStreamDescription(t.ssrc))==null?void 0:s.participantId;if(!i){o.warn(`Participant id for ssrc ${t.ssrc} not found in registry`);return}if(t.eos){this.close(i),this._onEos(i);return}let r=this._streamBuilders[i];if(!r){let d=l=>this._onStream(i,l);p.screenShareWebmBuilder&&Re.isBrowserSupported()?r=new Re(i,d):r=new Et(i,d),this._streamBuilders[i]=r}r.appendChunk(t)}close(e){let t=this._streamBuilders[e];t&&(t.destroy(),delete this._streamBuilders[e])}destroy(){this._datachannel.onbufferedamountlow=null,this._datachannel.onmessage=null,this._onStream=()=>{},Object.values(this._streamBuilders).forEach(e=>e.destroy()),this._streamBuilders={},this._participantIdRegistry=null,o.debug("ScreenCaptureReceiver destroyed")}static isBrowserSupported(){return(je.isBrowserSupported()||it.isBrowserSupported())&&(Et.isBrowserSupported()||Re.isBrowserSupported())}};var Ci=He(require("@vkontakte/libvpx"));var Ga=1e3,Tt=class extends Oe{constructor(e,t){super();this._video=null;this._imageCapture=null;this._canvas=null;this._canvasCtx=null;this._stream=null;this._track=null;this._frameReadTimeout=0;this._lastFrame=null;this._sourceTrack=e,this._onFrame=t,this._useImageCapture="ImageCapture"in window&&"ImageBitmap"in window,(e.readyState!=="live"||!e.enabled||e.muted)&&(this._useImageCapture=!1)}_createDom(){this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.style.pointerEvents="none",this._canvas.style.visibility="hidden",this._canvas.style.position="absolute",this._canvas.style.width="160px",this._canvas.style.height="90px",this._canvas.style.bottom="0",this._canvas.style.right="160px",this._canvas.style.zIndex="5000",this._canvasCtx=this._canvas.getContext("2d"),document.body.appendChild(this._canvas)),!this._video&&!this._useImageCapture&&(this._video=document.createElement("video"),this._video.controls=!1,this._video.autoplay=!1,this._video.preload="auto",this._video.muted=!0,this._video.style.pointerEvents="none",this._video.style.visibility="hidden",this._video.style.position="absolute",this._video.style.width="160px",this._video.style.height="90px",this._video.style.bottom="0",this._video.style.right="0",this._video.style.zIndex="5000",document.body.appendChild(this._video))}_removeDom(){try{this._canvas&&document.body.removeChild(this._canvas),this._video&&document.body.removeChild(this._video)}catch(e){}this._canvasCtx=null,this._canvas=null,this._video=null}_createStream(e){return c(this,null,function*(){if(!this._canvas)throw new Error("Canvas not found");if(!this._video&&!this._useImageCapture)throw new Error("Video element not found");return this._stream=this._canvas.captureStream(0),this._track=this._stream.getVideoTracks()[0],new Promise((t,i)=>{if(this._useImageCapture)this._imageCapture=new ImageCapture(e),t();else{let r=this._video;r.srcObject=new MediaStream([e]),r.onloadeddata=d=>t(),r.onerror=()=>i(new Error("Video element error"));let n=r.play(),s=()=>i(new Error("Autoplay is disabled"));n?n.catch(s):s()}})})}_removeStream(){var e;window.clearTimeout(this._frameReadTimeout),(e=this._lastFrame)==null||e.close(),this._stream&&(this._stream.getTracks().forEach(t=>t.stop()),this._stream=null,this._track=null),this._video&&(this._video.pause(),this._video.srcObject=null),this._imageCapture&&(this._imageCapture=null)}_drawFrameVideo(){if(!this._canvas||!this._canvasCtx||!this._video||!this._track)throw new Error("Fatal error");let e=this._video.videoWidth,t=this._video.videoHeight;return this._canvas.width=this._video.width=e,this._canvas.height=this._video.height=t,this._canvasCtx.clearRect(0,0,e,t),this._canvasCtx.drawImage(this._video,0,0,e,t),this._requestCanvasFrame(),this._canvasCtx.getImageData(0,0,e,t)}_getFrameBitmap(){return c(this,null,function*(){if(!this._imageCapture)throw new Error("Destroyed");return this._imageCapture.grabFrame()})}_drawFrameData(e){var r;if(!this._canvas||!this._canvasCtx||!this._track)throw new Error("Destroyed");let t=e.width,i=e.height;return this._canvas.width=t,this._canvas.height=i,this._canvasCtx.clearRect(0,0,t,i),this._canvasCtx.drawImage(e,0,0,t,i),this._requestCanvasFrame(),(r=this._canvasCtx)==null?void 0:r.getImageData(0,0,t,i)}_requestCanvasFrame(){this._track&&this._track.requestFrame?this._track.requestFrame():this._stream&&this._stream.requestFrame&&this._stream.requestFrame()}init(){return c(this,null,function*(){this._createDom();let e=this._sourceTrack.getSettings().width,t=this._sourceTrack.getSettings().height;o.debug(`LibVPxEncoder started ${e}x${t}, codec ${this.isVP9()?"VP9":"VP8"}`),yield this._createStream(this._sourceTrack),yield this._createWorker(`var exports=(()=>{var u=Object.defineProperty;var b=o=>u(o,"__esModule",{value:!0});var g=(o,n)=>{b(o);for(var t in n)u(o,t,{get:n[t],enumerable:!0})};var y={};g(y,{default:()=>R});var e=(r=>(r.INIT="init",r.READY="ready",r.FRAME="frame",r.ERROR="error",r.DEBUG="debug",r.LOG_ERROR="log_error",r))(e||{});var R=(o,n)=>{let t;function m(a,r){return o({locateFile:n}).then(s=>{if(t=new s.VpxEncoder,t.debug(r),!t.init(a?s.VpxType.VP9:s.VpxType.VP8))throw self.postMessage({type:e.LOG_ERROR,message:"encoder-init-fail-libvpx"}),new Error("LibVPxEncoder failed to create");t.setMaxQuantizer(10),t.setTargetBitrate(1024)})}function E(a,r,s,i){let c=t.allocateImage(a,r);if(!c){self.postMessage({type:e.FRAME,error:"No buffer data"});return}c.set(new Uint8Array(s));let f=Math.round(performance.now()),l=150;if(!t.encode(f,l,i)){self.postMessage({type:e.FRAME,error:"Encode failed"});return}let p=t.readFrame();if(!p){self.postMessage({type:e.FRAME,error:"No encoded data"});return}t.readFrame()&&(self.postMessage({type:e.DEBUG,message:"LibVPxEncoder dropped frame"}),self.postMessage({type:e.LOG_ERROR,message:"LibVPxEncoder-drop"}));let d=new Uint8Array(p.byteLength);d.set(p),self.postMessage({type:e.FRAME,frameType:i?"key":"delta",timestamp:f,duration:l,data:d.buffer},[d.buffer])}self.onmessage=a=>{switch(a.data.type){case e.INIT:m(a.data.isVP9,a.data.debug).then(()=>self.postMessage({type:e.READY})).catch(r=>self.postMessage({type:e.ERROR,error:String(r)}));break;case e.FRAME:E(a.data.width,a.data.height,a.data.imageData,a.data.keyFrame);break}}};return y;})();
10
+ `,i=>{var r;i.error?this._onFrame(null,i.error):this._onFrame({type:i.frameType,timestamp:i.timestamp,duration:i.duration,data:i.data,byteLength:(r=i.data)==null?void 0:r.byteLength})},[Ci.default,Ci.default.getUrl],{isVP9:this.isVP9(),debug:o.enabled()})})}_encode(e,t){let i=e.data.buffer;this._sendToWorker(me.FRAME,{width:e.width,height:e.height,imageData:i,keyFrame:t},[i])}_requestFrameVideo(e){let t=this._drawFrameVideo();this._encode(t,e)}_requestFrameBitmap(e){this._frameReadTimeout=window.setTimeout(()=>{if(this._lastFrame){let t=this._drawFrameData(this._lastFrame);this._encode(t,e)}else this._onFrame(null)},Ga),this._getFrameBitmap().then(t=>{var r;window.clearTimeout(this._frameReadTimeout),(r=this._lastFrame)==null||r.close(),this._lastFrame=t;let i=this._drawFrameData(t);this._encode(i,e)}).catch(()=>{})}requestFrame(e=!1){this._useImageCapture?this._requestFrameBitmap(e):this._requestFrameVideo(e)}isVP9(){return!1}destroy(){this._removeWorker(),this._removeStream(),this._removeDom(),o.debug("LibVPxEncoder destroyed")}static isBrowserSupported(){return"WebAssembly"in window&&"Worker"in window&&("CanvasCaptureMediaStream"in window||"CanvasCaptureMediaStreamTrack"in window)}};var ct=class extends Oe{constructor(e,t){super();this._sourceTrack=e,this._onFrame=t,this._trackProcessor=new MediaStreamTrackProcessor(e)}init(){return c(this,null,function*(){let e=this._sourceTrack.getSettings().width,t=this._sourceTrack.getSettings().height,i=this._trackProcessor.readable;o.debug(`WebCodecsEncoder started ${e}x${t}, codec ${this.isVP9()?"VP9":"VP8"}`),yield this._createWorker(`var exports=(()=>{var b=Object.defineProperty;var g=i=>b(i,"__esModule",{value:!0});var F=(i,n)=>{g(i);for(var r in n)b(i,r,{get:n[r],enumerable:!0})};var A={};F(A,{default:()=>h});var l=(r=>(r.VP9="vp09.00.50.08",r.VP8="vp8",r))(l||{}),d=(t=>(t.INIT="init",t.READY="ready",t.FRAME="frame",t.ERROR="error",t.DEBUG="debug",t.LOG_ERROR="log_error",t))(d||{});var h=()=>{let i=1e3,n,r,c,s,f,t,a=null,p=0,u=!1;function V(e){n=e.readable,r=n.getReader(),c=e.width,s=e.height,f=e.isVP9,t=e.framerate,m.configure({framerate:t,codec:f?l.VP9:l.VP8,width:c,height:s,latencyMode:"realtime"}),self.postMessage({type:d.READY})}function y(e){p=self.setTimeout(()=>{a&&E(a,e)},i),!u&&(u=!0,r.read().finally(()=>{u=!1,self.clearTimeout(p)}).then(({done:o,value:R})=>{if(a==null||a.close(),a=null,!(o||!R)){if(!m){r.releaseLock(),n.cancel();return}a=R,E(R,e)}}))}function E(e,o){(e.codedWidth!==c||e.codedHeight!==s)&&(c=e.codedWidth,s=e.codedHeight,m.configure({framerate:t,codec:f?l.VP9:l.VP8,width:c,height:s,latencyMode:"realtime"})),m.encode(e,{keyFrame:o})}let m=new VideoEncoder({output:e=>{let o;e.data?o=e.data:(o=new ArrayBuffer(e.byteLength),e.copyTo(o)),self.postMessage({type:d.FRAME,frameType:e.type,timestamp:e.timestamp,duration:e.duration,data:o},[o])},error:e=>{self.postMessage({type:d.FRAME,error:String(e)})}});self.onmessage=e=>{switch(e.data.type){case d.INIT:V(e.data);break;case d.FRAME:y(e.data.keyFrame);break}}};return A;})();
11
+ `,r=>{var n;r.error?this._onFrame(null,r.error):this._onFrame({type:r.frameType,timestamp:r.timestamp,duration:r.duration,data:r.data,byteLength:(n=r.data)==null?void 0:n.byteLength})},[],{readable:i,width:e,height:t,isVP9:this.isVP9(),framerate:p.screenFrameRate},[i])})}requestFrame(e=!1){this._sendToWorker(me.FRAME,{keyFrame:e})}isVP9(){return!0}destroy(){this._removeWorker(),o.debug("WebCodecsEncoder destroyed")}static isBrowserSupported(){return"VideoEncoder"in window&&"Worker"in window&&"EncodedVideoChunk"in window&&"MediaStreamTrackProcessor"in window}};var Wa=16*1024,ja=11,Hr=Wa-ja,Ka=65536,yi=0,dt=class{constructor(e,t){this._destroyed=!1;this._needKeyframe=!0;o.debug("ScreenCaptureSender started"),this._datachannel=t;let i=(r,n)=>{if(!this._destroyed){if(!r){o.warn("requestFrame failed, keyFrame: "+this._needKeyframe,n),this._needKeyframe=!0,this._requestFrame();return}this._send(r).catch(s=>{o.warn("sendFrame failed",s),this._needKeyframe=!0}).finally(()=>this._requestFrame())}};ct.isBrowserSupported()?this._encoder=new ct(e,i):this._encoder=new Tt(e,i),this._datachannel.onmessage=r=>{Fr(r.data)&&(o.debug(`[${this._datachannel.label}] Requested keyframe`),this._needKeyframe=!0)},this._encoder.init().then(()=>this._requestFrame()).catch(r=>o.warn("ScreenCaptureSender init failed",r))}_requestFrame(){this._destroyed||(this._encoder.requestFrame(this._needKeyframe),this._needKeyframe=!1)}_wrapHeader(e,t,i,r,n){let s=Br(e,t,i,r,yi,this._encoder.isVP9(),n);return yi=(yi+1)%Ka,s}_stopPacket(){return this._wrapHeader(Date.now(),!1,!1,!1,null)}_send(e){return c(this,null,function*(){return new Promise((t,i)=>{this._sendChunk(e,0,t,i)})})}_sendChunk(e,t,i,r){if(!this._datachannel||this._datachannel.readyState!=="open"){r();return}let n=e.data.slice(t,t+Hr),s=e.data.byteLength<=t+n.byteLength,d=this._wrapHeader(e.timestamp,!t,s,e.type==="key",n);this._datachannel.onbufferedamountlow=s?()=>{this._datachannel.bufferedAmount<=this._datachannel.bufferedAmountLowThreshold&&i()}:null;try{this._datachannel.send(d)}catch(l){o.warn("Error send data to DataChannel",l),r();return}s||window.setTimeout(()=>this._sendChunk(e,t+Hr,i,r),0)}destroy(){this._datachannel.onbufferedamountlow=null,this._datachannel.onmessage=null,this._datachannel.readyState==="open"&&this._datachannel.send(this._stopPacket()),this._destroyed=!0,this._encoder.destroy(),o.debug("ScreenCaptureSender destroyed")}static isBrowserSupported(){return ct.isBrowserSupported()||Tt.isBrowserSupported()}};var X=class{static get sessionKey(){return X._sessionKey}static set sessionKey(e){X._sessionKey=e}static get sessionSecretKey(){return X._sessionSecretKey}static set sessionSecretKey(e){X._sessionSecretKey=e}static get accessToken(){return X._accessToken}static set accessToken(e){X._accessToken=e}static isEmpty(){return!X._sessionKey||!X._sessionSecretKey}};var v=class{static set(e){e.hasOwnProperty("voiceParams")&&(Object.assign(v._params.voiceParams,e.voiceParams),delete e.voiceParams),e.hasOwnProperty("specListenerParams")&&(Object.assign(v._params.specListenerParams,e.specListenerParams),delete e.specListenerParams),e.hasOwnProperty("unifiedPlanBrowsers")&&(Object.assign(v._params.unifiedPlanBrowsers,e.unifiedPlanBrowsers),delete e.unifiedPlanBrowsers),e.hasOwnProperty("apiAuth")&&(X.accessToken=e.apiAuth.accessToken,X.sessionKey=e.apiAuth.sessionKey,X.sessionSecretKey=e.apiAuth.sessionSecretKey),Object.assign(v._params,e)}static get(e){return v._params[e]}static get appName(){return"ok.calls.sdk.js"}static get appVersion(){return 1.1}static get sdkVersion(){return"2.5.2-dev.e4603f6.0"}static get debug(){return!1}static get protocolVersion(){return v._params.joinFromMultipleDevices?6:5}static get platform(){return v._params.platform}static set platform(e){v._params.platform=e}static get clientType(){return v._params.clientType}static set clientType(e){v._params.clientType=e}static get device(){return v._params.device}static get apiKey(){return v._params.apiKey}static get apiEnv(){return v._params.apiEnv}static get apiEndpoint(){switch(v.apiEnv){case"AUTO":case"PROD":return"https://api.mycdn.me";case"PROD_OK":return"https://api.ok.ru";case"TEST":return"https://apitest.ok.ru/api";case"VIDEOTEST":return"https://videotestapi.ok.ru/api";default:return v._params.apiEnv}}static get authToken(){return v._params.authToken}static set authToken(e){v._params.authToken=e}static get anonymToken(){return v._params.anonymToken}static set anonymToken(e){v._params.anonymToken=e}static get domain(){return v._params.domain}static get iceServers(){return v._params.iceServers}static set iceServers(e){v._params.iceServers=e}static get wssBase(){return v._params.wssBase}static set wssBase(e){v._params.wssBase=e}static get wssToken(){return v._params.wssToken}static set wssToken(e){v._params.wssToken=e}static get signalingReconnectDelay(){return v._params.signalingReconnectDelay}static get signalingReconnectMaxDelay(){return v._params.signalingReconnectMaxDelay}static get signalingReconnectMaxCount(){return v._params.signalingReconnectMaxCount}static get waitConnectionDelay(){return v._params.waitConnectionDelay}static get waitResponseDelay(){return v._params.waitResponseDelay}static get waitMessageDelay(){return v._params.waitMessageDelay}static get debugLog(){return v._params.debugLog}static get forceRelayPolicy(){return v._params.forceRelayPolicy}static set forceRelayPolicy(e){v._params.forceRelayPolicy=e}static get videoMinWidth(){return v._params.videoMinWidth}static get videoMaxWidth(){return v._params.videoMaxWidth}static set videoMaxWidth(e){v._params.videoMaxWidth=e}static get videoMinHeight(){return v._params.videoMinHeight}static get videoMaxHeight(){return v._params.videoMaxHeight}static set videoMaxHeight(e){v._params.videoMaxHeight=e}static get videoAspectRatio(){return v._params.videoAspectRatio}static get videoFrameRate(){return v._params.videoFrameRate}static get videoFacingMode(){return v._params.videoFacingMode}static get screenFrameRate(){return v._params.screenFrameRate}static get videoEffects(){return v._params.videoEffects}static set videoEffects(e){v._params.videoEffects=e}static get videoEffectMaxWidth(){return v._params.videoEffectMaxWidth}static set videoEffectMaxWidth(e){v._params.videoEffectMaxWidth=e}static get videoEffectMaxHeight(){return v._params.videoEffectMaxHeight}static set videoEffectMaxHeight(e){v._params.videoEffectMaxHeight=e}static get voiceParams(){return v._params.voiceParams}static get specListenerParams(){return v._params.specListenerParams}static get iceRestartWaitTime(){return v._params.iceRestartWaitTime}static get transportConnectionWaitTime(){return v._params.transportConnectionWaitTime}static get statisticsInterval(){return v._params.statisticsInterval}static set statisticsInterval(e){v._params.statisticsInterval=e}static get networkStatisticsInterval(){return v._params.networkStatisticsInterval}static get perfStatReportEnabled(){return v._params.perfStatReportEnabled}static get callStatReportEnabled(){return v._params.callStatReportEnabled}static get producerNotificationDataChannel(){return v._params.producerNotificationDataChannel&&ot.isBrowserSupported()}static get producerCommandDataChannel(){return v._params.producerCommandDataChannel}static get consumerScreenDataChannel(){return v._params.consumerScreenDataChannel&&dt.isBrowserSupported()}static get producerScreenDataChannel(){return v._params.producerScreenDataChannel&&v.producerNotificationDataChannel}static get screenShareWebmBuilder(){return v._params.screenShareWebmBuilder}static get noiseSuppression(){return v._params.noiseSuppression}static set noiseSuppression(e){v._params.noiseSuppression=e}static get preferH264(){return v._params.preferH264}static get preferVP9(){return v._params.preferVP9}static get audioNack(){return v._params.audioNack}static get consumerScreenTrack(){return v._params.consumerScreenTrack&&v.consumerScreenDataChannel}static get producerScreenTrack(){return v._params.producerScreenTrack&&v.producerScreenDataChannel}static isUnifiedPlanSupported(e,t){let i=v._params.unifiedPlanBrowsers;return i.hasOwnProperty(e)?t>=i[e]:!1}static get movieShare(){return v._params.movieShare&&v.videoTracksCount>0}static get videoTracksCount(){return v.producerNotificationDataChannel?v._params.videoTracksCount:0}static get breakVideoPayloadTypes(){return v._params.breakVideoPayloadTypes}static get filteredMessages(){return v._params.filteredMessages}static get batchParticipantsOnStart(){return v._params.batchParticipantsOnStart}static get participantStateMapped(){return v._params.participantStateMapped}},p=v;p._params={platform:"WEB",clientType:"PORTAL",device:"browser",apiKey:"",authToken:"",anonymToken:"",apiEnv:"AUTO",domain:"",iceServers:[],wssBase:"",wssToken:"",signalingReconnectDelay:1e3,signalingReconnectMaxDelay:5e3,signalingReconnectMaxCount:20,waitConnectionDelay:1e4,waitResponseDelay:1e4,waitMessageDelay:15e3,debugLog:!1,forceRelayPolicy:!1,videoMinWidth:428,videoMinHeight:240,videoMaxWidth:1280,videoMaxHeight:720,videoAspectRatio:16/9,videoFrameRate:25,screenFrameRate:15,videoEffects:null,videoEffectMaxWidth:640,videoEffectMaxHeight:360,iceRestartWaitTime:2e4,transportConnectionWaitTime:5e3,statisticsInterval:5e3,networkStatisticsInterval:2e4,perfStatReportEnabled:!0,callStatReportEnabled:!1,voiceParams:{smoothing:.8,minFreq:200,maxFreq:5e3,interval:500,threshold:.35,speakerLevelMultiplier:1.8},specListenerParams:{connectionTimeout:1e4,volumeTimeout:1e4},unifiedPlanBrowsers:{Firefox:10,Chrome:76,Safari:12},producerNotificationDataChannel:!0,producerCommandDataChannel:!0,consumerScreenDataChannel:!0,producerScreenDataChannel:!0,screenShareWebmBuilder:!1,noiseSuppression:!0,preferH264:!1,preferVP9:!0,audioNack:!0,consumerScreenTrack:!1,producerScreenTrack:!1,videoTracksCount:0,movieShare:!1,filteredMessages:!1,breakVideoPayloadTypes:!1,batchParticipantsOnStart:!1,participantStateMapped:!1,joinFromMultipleDevices:!0};var q=(l=>(l.WAITING_HALL="WAITING_HALL",l.WAITING="WAITING",l.CONNECTING="CONNECTING",l.CONNECTED="CONNECTED",l.RECONNECT="RECONNECT",l.ERROR="ERROR",l.HANGUP="HANGUP",l.PERMISSIONS="PERMISSIONS",l))(q||{});function U(a,...e){let t=p.get(a);t&&setTimeout(t,0,...e)}function ke(a){return Object.assign({},a)}function pt(a){return a.slice()}var Ri;(ce=>{function a(_,C){U("onLocalStream",_,ke(C))}ce.onLocalStream=a;function e(_,C){U("onScreenStream",_,ke(C))}ce.onScreenStream=e;function t(_,C){U("onLocalStreamUpdate",ke(_),C)}ce.onLocalStreamUpdate=t;function i(_){U("onLocalStatus",_)}ce.onLocalStatus=i;function r(_,C){U("onRemoteStream",_,C)}ce.onRemoteStream=r;function n(_,C,F){U("onRemoteLive",_,C,F)}ce.onRemoteLive=n;function s(_,C){U("onRemoteScreenStream",_,C)}ce.onRemoteScreenStream=s;function d(_,C,F,mt){U("onConversation",_,ke(C),ke(F),mt)}ce.onConversation=d;function l(_,C){U("onRemoteMediaSettings",_,ke(C))}ce.onRemoteMediaSettings=l;function h(_,C){U("onRemoteParticipantState",_,ke(C))}ce.onRemoteParticipantState=h;function P(_,C,F=null){U("onRemoteStatus",_,C,F)}ce.onRemoteStatus=P;function b(_,C,F=null){U("onParticipantStatus",_,C,F)}ce.onParticipantStatus=b;function j(){U("onPermissionsRequested")}ce.onPermissionsRequested=j;function W(_){U("onPermissionsError",_)}ce.onPermissionsError=W;function x(_){U("onRemoteRemoved",_)}ce.onRemoteRemoved=x;function le(_,C,F){U("onCallState",_,C,ke(F))}ce.onCallState=le;function be(_,C){U("onDeviceSwitched",_,C)}ce.onDeviceSwitched=be;function oe(_,C,F,mt=!1,Xt=!1,Zt=null,_a=null){U("onMuteStates",ke(_),pt(C),pt(F),mt,Xt,Zt,_a)}ce.onMuteStates=oe;function Fe(_,C){U("onRolesChanged",_,pt(C))}ce.onRolesChanged=Fe;function ne(_){U("onLocalRolesChanged",pt(_))}ce.onLocalRolesChanged=ne;function K(_,C){U("onPinnedParticipant",_,C)}ce.onPinnedParticipant=K;function Ce(_){U("onLocalPin",_)}ce.onLocalPin=Ce;function ut(_){U("onOptionsChanged",pt(_))}ce.onOptionsChanged=ut;function Bi(){U("onCallAccepted")}ce.onCallAccepted=Bi;function Vi(){U("onRateNeeded")}ce.onRateNeeded=Vi;function Fi(_){U("onSpeakerChanged",_)}ce.onSpeakerChanged=Fi;function Hi(_){U("onVolumesDetected",pt(_))}ce.onVolumesDetected=Hi;function Qt(_,C){U("onLocalVolume",_,C)}ce.onLocalVolume=Qt;function u(_,C){U("onJoinStatus",_,C)}ce.onJoinStatus=u;function I(_,C){U("onHangup",_,C)}ce.onHangup=I;function D(_){U("onMultipartyChatCreated",ke(_))}ce.onMultipartyChatCreated=D;function V(){U("onDeviceChange")}ce.onDeviceChange=V;function f(_){U("onFingerprintChange",_)}ce.onFingerprintChange=f;function J(){U("onTokenExpired")}ce.onTokenExpired=J;function R(_,C,F=!1){U("onChatMessage",_,C,F)}ce.onChatMessage=R;function $(_,C,F=!1){U("onCustomData",_,C,F)}ce.onCustomData=$;function te(_,C,F,mt,Xt,Zt){U("onRecordStarted",_,C,F,mt,Xt,Zt)}ce.onRecordStarted=te;function k(){U("onRecordStopped")}ce.onRecordStopped=k;function ge(_){U("onLocalNetworkStatusChanged",_)}ce.onLocalNetworkStatusChanged=ge;function Le(_){U("onNetworkStatusChanged",_)}ce.onNetworkStatusChanged=Le;function ie(_,...C){U("onDebugMessage",_,...C)}ce.onDebugMessage=ie;function we(_,C){let F=Object.assign({},_,{memory:C});U("onStatistics",F)}ce.onStatistics=we;function Y(){U("onAutoplayError")}ce.onAutoplayError=Y;function Me(_,C,F){U("onChatRoomUpdated",_,C,F)}ce.onChatRoomUpdated=Me})(Ri||(Ri={}));var T=Ri;var Pi=(r=>(r.DEBUG="DEBUG",r.LOG="LOG",r.WARN="WARN",r.ERROR="ERROR",r))(Pi||{}),bi;(ne=>{let a="📞",e=(K,...Ce)=>{T.onDebugMessage(K,...Ce)},t=!1,i=(K,Ce)=>(...ut)=>{K(...ut),Ir(Ce,ut)},r=console.debug.bind(console,a),n=console.log.bind(console,a),s=console.warn.bind(console,a),d=console.error.bind(console,a),l=e.bind(null,"DEBUG"),h=e.bind(null,"LOG"),P=e.bind(null,"WARN"),b=e.bind(null,"ERROR");ne.debug=l,ne.log=h,ne.warn=P,ne.error=b;function be(){return t}ne.enabled=be;function oe(K){t=K,p.debugLog&&ai(),K?(ne.debug=p.debugLog?i(r,"DEBUG"):r,ne.log=p.debugLog?i(n,"LOG"):n,ne.warn=p.debugLog?i(s,"WARN"):s,ne.error=p.debugLog?i(d,"ERROR"):d):(ne.debug=p.debugLog?i(l,"DEBUG"):l,ne.log=p.debugLog?i(h,"LOG"):h,ne.warn=p.debugLog?i(P,"WARN"):P,ne.error=p.debugLog?i(b,"ERROR"):b)}ne.toggle=oe;function Fe(K,...Ce){switch(K){case"DEBUG":ne.debug(...Ce);break;case"LOG":ne.log(...Ce);break;case"WARN":ne.warn(...Ce);break;case"ERROR":ne.error(...Ce);break}}ne.send=Fe})(bi||(bi={}));var o=bi;var Je=(i=>(i.USER="USER",i.ANONYM="ANONYM",i.GROUP="GROUP",i))(Je||{}),de;(d=>{function a(l){return l.length?typeof l[0]=="object"?l:l.map(h=>e(h)):[]}d.fromIds=a;function e(l,h="USER"){return{id:l,type:h}}d.fromId=e;function t(l){return{id:l.id,type:l.type==="ANONYM"?"ANONYM":"USER"}}d.fromSignaling=t;function i(l){return`{"id":"${l.id}","type":"${l.type}"}`}d.toString=i;function r(l,h="USER"){return i(e(l,h))}d.fromIdToString=r;function n(l){try{return JSON.parse(l)}catch(h){throw new Error(`Failed to parse ExternalId from string '${l}'`)}}d.fromString=n;function s(l,h){return l.id===h.id&&l.type===h.type}d.compare=s})(de||(de={}));var pe;(r=>{function a(n,s="USER",d=0){return{id:n,type:s,deviceIdx:d}}r.fromId=a;function e(n){return`{"id":"${n.id}","type":"${n.type}","deviceIdx":"${n.deviceIdx}"}`}r.toString=e;function t(n,s){return Object.assign({deviceIdx:s},de.fromSignaling(n))}r.fromSignaling=t;function i(n){return n&&typeof n=="object"?n.deviceIdx:0}r.getDeviceIdx=i})(pe||(pe={}));var fe=(r=>(r.CAMERA="CAMERA",r.SCREEN="SCREEN",r.STREAM="STREAM",r.MOVIE="MOVIE",r))(fe||{}),Gr="s",Wr="m";function Be(a){return a.participantId+(a.mediaType?nt+Gr+a.mediaType:"")+(a.streamName?nt+Wr+a.streamName:"")}function It(a){let e=a.split(nt),t=e.shift();if(!t)throw new Error("Illegal stream description: "+a);let i=null,r,n=0;for(let d of e)switch(d.charAt(0)){case Gr:i=$a(d.slice(1));break;case Wr:r=d.slice(1);break;case kt:n=Number.parseInt(d.slice(1),10);break;default:throw new Error("Unexpected parameter type "+d.charAt(0)+" in stream description "+a)}return{participantId:E.compose(t,n),mediaType:i,streamName:r}}function $a(a){for(let e of Object.keys(fe))if(e===a)return fe[e];return null}function Mi(a,e){return a===null||e===null?a===null&&e===null:!(a.maxDimension!==e.maxDimension||a.maxBitrateK!==e.maxBitrateK||a.maxFramerate!==e.maxFramerate||a.degradationPreference!==e.degradationPreference)}function Gt(a,e){return!(!Mi(a.camera,e.camera)||!Mi(a.screenSharing,e.screenSharing))}function Di(a,e){return{camera:Object.assign({},a.camera,e.camera),screenSharing:Object.assign({},a.screenSharing,e.screenSharing)}}function jr(a){try{return btoa(JSON.stringify(a))}catch(e){o.warn("WaitingParticipant: failed convert to string",a,e)}return null}function Kr(a){try{return JSON.parse(atob(a))}catch(e){o.warn("WaitingParticipant: failed convert from string",a,e)}return null}var Ct=class{constructor(e){this._fixNoPacketsApplied=!1;this._fixNoPacketsChecked=!1;this._fixTooManyPacketsApplied=!1;this._fixTooManyPacketsSucceeded=!1;this._fixTooManyPacketsFailed=!1;this._mediaSource=e}_fixAudioDeviceNoPackets(e){if(!(this._fixNoPacketsApplied&&this._fixNoPacketsChecked)){if(this._fixNoPacketsApplied&&!this._fixNoPacketsChecked){this._fixNoPacketsChecked=!0,m.log(g.ERROR,`audio_device_recover_${e.bandwidth?"success":"fail"}`);return}!this._fixNoPacketsApplied&&!e.bandwidth&&(this._fixNoPacketsApplied=!0,m.log(g.ERROR,"audio_device_recover"),this._mediaSource.toggleAudio(!0))}}_fixAudioDeviceTooManyPackets(e){if(this._fixTooManyPacketsSucceeded||this._fixTooManyPacketsFailed)return;let t=75,i=Date.now();if(!this._lastPacketsSentTime)e.packetsSent>0&&(this._lastPacketsSentTime=i,this._lastPacketsSent=e.packetsSent);else if(i-this._lastPacketsSentTime>500){let r=(e.packetsSent-this._lastPacketsSent)*1e3/(i-this._lastPacketsSentTime);this._lastPacketsSentTime=i,this._lastPacketsSent=e.packetsSent,this._fixTooManyPacketsApplied?r>t?(o.log("Failed to fix RV"),m.log(g.ERROR,"audio_device_recover_rv_fail"),this._fixTooManyPacketsFailed=!0):i-this._fixTooManyPacketsTime>6e4&&(o.log("Fixed RV"),m.log(g.ERROR,"audio_device_recover_rv_success"),this._fixTooManyPacketsSucceeded=!0):r>t&&(this._fixTooManyPacketsApplied=!0,o.log("Trying to fix RV"),this._mediaSource.toggleAudio(!0),this._fixTooManyPacketsTime=i)}}fix(e){if(!this._mediaSource)return;let t=e.find(i=>i.kind===se.audio);!t||(this._fixAudioDeviceNoPackets(t),this._fixAudioDeviceTooManyPackets(t))}};var Wt=class{constructor(){this._output=null;this._volume=1;this._features={setSinkId:!!Audio.prototype.setSinkId}}add(e){this.destroy(),this._output={},this._output.audioTrack=e,this._initAudioElement()}remove(e){!this._output||this._output.audioTrack!==e||this.destroy()}get volume(){return this._volume}set volume(e){this._volume=Math.max(0,Math.min(1,e)),this._output&&this._output.audioElement&&(this._output.audioElement.volume=this._volume)}_initAudioElement(){var s;if(!((s=this._output)==null?void 0:s.audioTrack))return;let e=y.browserName()!=="Safari",t=document.createElement(e?"audio":"video");t.muted=!1,t.volume=this._volume,t.preload="auto";let i=()=>{o.warn("Error on play audio"),T.onAutoplayError()},r=d=>{t.srcObject=new MediaStream([d]),t.load();let l=t.play();l?l.catch(i):i()},n=()=>{var l;o.debug("Recover audio playback");let d=(l=this._output)==null?void 0:l.audioTrack;d?r(d):o.warn("Broken audio track")};t.onpause=n,t.onstalled=n,t.onerror=n,r(this._output.audioTrack),this._output.audioElement=t}_stopAudioElement(){var e,t,i;((e=this._output)==null?void 0:e.audioElement)&&(this._output.audioElement.pause(),this._output.audioElement.srcObject=null),(i=(t=this._output)==null?void 0:t.audioTrack)==null||i.stop()}destroy(){!this._output||(this._stopAudioElement(),this._output=null)}changeOutput(){return c(this,null,function*(){var e,t,i;try{if(!this._features.setSinkId)throw new Error('Feature "setSinkId" is not supported');if(!((e=this._output)==null?void 0:e.audioElement))throw new Error("Audio Element is not initialized");let r=y.getSavedOutput();r&&(yield(i=(t=this._output.audioElement).setSinkId)==null?void 0:i.call(t,r.deviceId))}catch(r){throw m.log(g.ERROR,"change_output"),o.error("Output change failed",r),r}})}};var qa=90,Ja=3,jt=class extends z{constructor(){super(...arguments);this._lastMemoryStat={percent:0,bytes:0}}onRemoteDataStats(e,t){this._calcMemory(),e.inbound.rtps.map(i=>{let r=typeof i.userId=="string"&&t[i.userId]||null;i.userId=r==null?void 0:r.externalId}),T.onStatistics(e,this._lastMemoryStat)}_calcMemory(){var r;let e=(r=window==null?void 0:window.performance)==null?void 0:r.memory;if(!e||!e.usedJSHeapSize||!e.jsHeapSizeLimit)return;let t=Number((100*e.usedJSHeapSize/e.jsHeapSizeLimit).toFixed(2)),i=Number((e.usedJSHeapSize/1024/1024).toFixed(1));t>qa?o.warn(`High memory usage: ${t}% (${i} MiB)`):(!this._lastMemoryStat.percent||Math.abs(t-this._lastMemoryStat.percent)>=Ja)&&(o.debug(`Memory usage: ${t}% (${i} MiB)`),this._lastMemoryStat.percent=t,this._lastMemoryStat.bytes=e.usedJSHeapSize)}};var Ya=44100,yt=class{constructor(e,t){this._analyser=null;this._gainNode=null;this._fftBins=null;this._mediaStreamSource=null;this._lastSmoothedLevel=0;this._trackId=e,this._stream=t;try{let i=y.getAudioContext();this._gainNode=i.createGain(),this._gainNode.gain.value=1e-5,this._gainNode.connect(i.destination),this._analyser=i.createAnalyser(),this._analyser.fftSize=1024,this._analyser.smoothingTimeConstant=0,this._analyser.connect(this._gainNode),this._fftBins=new Uint8Array(this._analyser.frequencyBinCount),this._mediaStreamSource=i.createMediaStreamSource(t),this._mediaStreamSource.connect(this._analyser)}catch(i){}}get stream(){return this._stream}get trackId(){return this._trackId}_getBins(){if(!this._fftBins||!this._analyser)return new Uint8Array;this._analyser.getByteFrequencyData(this._fftBins);let e=Ya/this._fftBins.length,t=Math.ceil(p.voiceParams.minFreq/e),i=Math.floor(p.voiceParams.maxFreq/e);return this._fftBins.subarray(t,i)}getLevel(){let e=this._getBins(),i=e.reduce((n,s)=>n+s,0)/e.length/255,r=this._lastSmoothedLevel*p.voiceParams.smoothing+i*(1-p.voiceParams.smoothing);return this._lastSmoothedLevel=r,{real:i,smoothed:r}}destroy(){this._mediaStreamSource&&(this._mediaStreamSource.disconnect(),this._mediaStreamSource=null),this._gainNode&&(this._gainNode.disconnect(),this._gainNode=null),this._analyser&&(this._analyser.disconnect(),this._analyser=null,this._fftBins=null,this._lastSmoothedLevel=0)}};var Kt=class extends z{constructor(e){super();this._detector=null;this._track=null;this._interval=null;let t=()=>{this._detector&&T.onLocalVolume(this._detector.getLevel().real,e.getMediaSettings().isAudioEnabled),this._interval=window.setTimeout(t,p.voiceParams.interval)};this._interval=window.setTimeout(t,p.voiceParams.interval);let i=()=>{let r=e.getStream();r&&this.init(r)};this.subscribe(e,Se.SOURCE_CHANGED,r=>{r.kind===se.audio&&r.mediaSettings.isAudioEnabled&&i()}),i()}init(e){this._stopDetector();let t=e.getAudioTracks();t.length&&(this._track=t[0].clone(),this._detector=new yt("local",new MediaStream([this._track])))}_stopDetector(){this._detector&&(this._detector.destroy(),this._detector=null),this._track&&(this._track.stop(),this._track=null)}destroy(){this.unsubscribe(),this._interval&&(window.clearTimeout(this._interval),this._interval=null),this._stopDetector()}};var $r="videochat-epi",za=5e3,Qa=3e4,Ye=class extends z{constructor(e,t,i=!1){super();this._previousTimestamp=0;this._previousCallStatReportTimestamp=0;this._previousCallStatReport={nack_sent:0,nack_received:0,pli_sent:0,pli_received:0,fir_sent:0,fir_received:0,frames_dropped:0,jitter_video:0,jitter_audio:0,interframe_delay_variance:0,total_audio_samples_received:0,concealed_audio_samples:0,inserted_audio_samples_for_deceleration:0,removed_audio_samples_for_acceleration:0,silent_concealed_audio_samples:0,audio_concealment_events:0,total_audio_energy:0};this._signaling=t,this._directTopology=i,this.subscribe(e,N.REMOTE_DATA_STATS,this._handleStats.bind(this))}destroy(){this.unsubscribe()}static getEstimatedPerformanceIndex(){try{let e=parseInt(localStorage.getItem($r)||"",10);return isNaN(e)?0:e}catch(e){return 0}}_handleStats(e){return c(this,null,function*(){if(!e.inbound||!e.inbound.rtps)return;let t=Date.now();!this._directTopology&&p.perfStatReportEnabled&&this._previousTimestamp+za<=t&&(yield this.reportPerfStats(e),this._previousTimestamp=t),p.callStatReportEnabled&&this._previousCallStatReportTimestamp+Qa<=t&&(this._reportCallStats(e),this._previousCallStatReportTimestamp=t)})}reportPerfStats(e){return c(this,null,function*(){let t=e.inbound.rtps.reduce((i,r)=>(r.kind==="video"&&(i.framesDecoded+=r.framesDecoded||0,i.framesReceived+=r.framesReceived||0),i),{framesDecoded:0,framesReceived:0});if(t.framesDecoded)try{let i=yield this._signaling.reportPerfStat(t);localStorage.setItem($r,i.estimatedPerformanceIndex)}catch(i){}})}_reportCallStats(e){let t={nack_received:0,pli_received:0,fir_received:0,frames_dropped:0,jitter_video:0,jitter_audio:0,interframe_delay_variance:0,nack_sent:0,pli_sent:0,fir_sent:0,total_audio_samples_received:0,concealed_audio_samples:0,silent_concealed_audio_samples:0,inserted_audio_samples_for_deceleration:0,removed_audio_samples_for_acceleration:0,audio_concealment_events:0,total_audio_energy:0,inbound_video_count:0,inbound_audio_count:0};e.inbound.rtps.reduce((r,n)=>(n.kind==="video"?(n.framesReceived&&(r.jitter_video=r.jitter_video*r.inbound_video_count/(r.inbound_video_count+1)+n.jitter*1e3/(r.inbound_video_count+1),r.interframe_delay_variance=r.interframe_delay_variance*r.inbound_video_count/(r.inbound_video_count+1)+n.interframeDelayVariance*1e6/(r.inbound_video_count+1),r.inbound_video_count++),r.frames_dropped+=n.framesDropped,r.nack_sent+=n.nackCount,r.pli_sent+=n.pliCount,r.fir_sent+=n.firCount):(n.totalSamplesReceived&&(r.jitter_audio=r.jitter_audio*r.inbound_audio_count/(r.inbound_audio_count+1)+n.jitter*1e3/(r.inbound_audio_count+1),r.total_audio_energy=r.total_audio_energy*r.inbound_audio_count/(r.inbound_audio_count+1)+n.totalAudioEnergy/(r.inbound_audio_count+1),r.inbound_audio_count++),r.total_audio_samples_received+=n.totalSamplesReceived,r.inserted_audio_samples_for_deceleration+=n.insertedSamplesForDeceleration,r.removed_audio_samples_for_acceleration+=n.removedSamplesForAcceleration,r.concealed_audio_samples+=n.concealedSamples,r.silent_concealed_audio_samples+=n.silentConcealedSamples,r.audio_concealment_events+=n.concealmentEvents),r),t),e.outbound.rtps.reduce((r,n)=>(n.kind==="video"&&(r.nack_received+=n.nackCount,r.pli_received+=n.pliCount,r.fir_received+=n.firCount),r),t);let i={call_topology:this._directTopology?"D":"S",nack_sent:t.nack_sent-this._previousCallStatReport.nack_sent,nack_received:t.nack_received-this._previousCallStatReport.nack_received,pli_sent:t.pli_sent-this._previousCallStatReport.pli_sent,pli_received:t.pli_received-this._previousCallStatReport.pli_received,fir_sent:t.fir_sent-this._previousCallStatReport.fir_sent,fir_received:t.fir_received-this._previousCallStatReport.fir_received,frames_dropped:t.frames_dropped-this._previousCallStatReport.frames_dropped};if(t.jitter_video&&(i.jitter_video=t.jitter_video),t.jitter_audio&&(i.jitter_audio=t.jitter_audio),t.interframe_delay_variance&&(i.interframe_delay_variance=t.interframe_delay_variance),t.total_audio_samples_received){let r=t.total_audio_samples_received-this._previousCallStatReport.total_audio_samples_received,n=t.inserted_audio_samples_for_deceleration-this._previousCallStatReport.inserted_audio_samples_for_deceleration,s=t.removed_audio_samples_for_acceleration-this._previousCallStatReport.removed_audio_samples_for_acceleration,d=t.concealed_audio_samples-this._previousCallStatReport.concealed_audio_samples,l=t.silent_concealed_audio_samples-this._previousCallStatReport.silent_concealed_audio_samples,h=t.audio_concealment_events-this._previousCallStatReport.audio_concealment_events;i.inserted_audio_samples_for_deceleration=n/r*1e3,i.removed_audio_samples_for_acceleration=s/r*1e3,i.concealed_audio_samples=d/r*1e3,i.concealed_silent_audio_samples=l/r*1e3,i.concealment_audio_avg_size=d/h,i.total_audio_energy=t.total_audio_energy}m.logCustom("callStat",i),o.log("Sent call stats",i),this._previousCallStatReport=t}};var Xa=1e3;function ae(a,e,t=0){return e in a&&a[e]?a[e]:t}function qr(...a){return e=>{for(let t of a)if(t(e))return!0;return!1}}function Ve(a,e){return t=>t[a]===e}function Za(a){return(e,t)=>e[a]-t[a]}function $t(a,e){return e.reduce((t,i)=>(t[i[a]]=i,t),{})}function en(a){let e={},t=[];for(let i of a)e[i.id]||(e[i.id]=!0,t.push(i));return t}function tn(a){return a!==null&&typeof a=="object"&&!Array.isArray(a)}function Ai(a){return Object.keys(a).filter(e=>a[e]!==void 0).map(e=>[e,a[e]]).reduce((e,t)=>(e[t[0]]=tn(t[1])?Ai(t[1]):t[1],e),{})}function rn(a){let e=[];for(let t of a)t.forEach(i=>e.push(i));return e}function an(a){return c(this,null,function*(){let e=[];return RTCRtpReceiver.prototype.getStats?(e.push(...a.getReceivers().map(t=>t.getStats())),e.push(...a.getSenders().map(t=>t.getStats()))):e.push(a.getStats()),Promise.all(e).then(rn).then(en)})}function nn(a){let e=a.filter(Ve("type","candidate-pair")).sort(Za("priority")).find(qr(Ve("nominated",!0),Ve("selected",!0)));if(!e)return{totalRoundTripTime:0,currentRoundTripTime:0,bytesSent:0,bytesReceived:0};let t={totalRoundTripTime:e.totalRoundTripTime||0,currentRoundTripTime:e.currentRoundTripTime||0,bytesSent:e.bytesSent,bytesReceived:e.bytesReceived},i=a.find(Ve("id",e.remoteCandidateId));i&&(t=Object.assign({},t,{remote:{type:i.candidateType,address:i.ip||i.address,port:i.port,protocol:i.protocol}}));let r=a.find(Ve("id",e.localCandidateId));return r&&(t=Object.assign({},t,{local:{type:r.candidateType,address:r.ip||r.address,port:r.port,protocol:r.protocol,relayProtocol:r.relayProtocol,networkType:r.networkType}})),Ai(t)}function sn(a,e){let t=$t("id",a),i=a.filter(qr(Ve("type","inbound-rtp"),Ve("type","outbound-rtp")));y.browserName()==="Firefox"&&(i=Object.values(i.reduce((n,s)=>{if(!n[s.ssrc])n[s.ssrc]=s;else{let d=Object.assign({},n[s.ssrc],s),l=n[s.ssrc].isRemote?s:n[s.ssrc];d.id=l.id,d.type=l.type,delete d.isRemote,delete d.remoteId,n[d.ssrc]=d}return n},{})));let r={};if(y.browserName()==="Safari"){let n=a.filter(Ve("type","track"));r=$t("trackIdentifier",n)}return i.map(n=>{let s=Number(n.ssrc),d=n.mediaType||n.kind,l=n.trackId,h=n.type,P=n.codecId;if(y.browserName()==="Safari"){let j=/^.+_([\d]+)$/.exec(n.id);if(j&&(s=parseInt(j[1],10)),d=n.id.indexOf("Audio")>0?"audio":"video",e[s]){let W=d+"-"+e[s];r[W]&&(l=r[W].id)}}if(!h||!s||!d)return null;let b={ssrc:s,type:h,kind:d,bytesReceived:ae(n,"bytesReceived"),bytesSent:ae(n,"bytesSent"),jitter:ae(n,"jitter"),packetsLost:ae(n,"packetsLost"),packetsReceived:ae(n,"packetsReceived"),packetsSent:ae(n,"packetsSent"),fractionLost:ae(n,"fractionLost"),pliCount:ae(n,"pliCount"),firCount:ae(n,"firCount"),nackCount:ae(n,"nackCount"),userId:e[s]};if(d==="video"){let j=ae(n,"framesDecoded"),W=ae(n,"totalInterFrameDelay"),x=ae(n,"totalSquaredInterFrameDelay");b.interframeDelayVariance=(x-W*W/j)/j}if(d==="audio"&&(b.totalSamplesReceived=ae(n,"totalSamplesReceived"),b.concealedSamples=ae(n,"concealedSamples"),b.insertedSamplesForDeceleration=ae(n,"insertedSamplesForDeceleration"),b.removedSamplesForAcceleration=ae(n,"removedSamplesForAcceleration"),b.silentConcealedSamples=ae(n,"silentConcealedSamples"),b.concealmentEvents=ae(n,"concealmentEvents"),b.totalAudioEnergy=ae(n,"totalAudioEnergy")),P&&t[P]){let j=t[P];b.clockRate=j.clockRate,b.mimeType=j.mimeType}if(l&&t[l]){let j=t[l];b.frameHeight=j.frameHeight,b.frameWidth=j.frameWidth,b.framesDecoded=j.framesDecoded,b.framesReceived=j.framesReceived,b.framesDropped=j.framesDropped}return Ai(b)}).filter(n=>!!n)}function on(a,e){if(!e||!e.rtps||!a.rtps)return a;let t=$t("ssrc",a.rtps),i=$t("ssrc",e.rtps),r=(a.timestamp-e.timestamp)/1e3;return!t||!i||Object.keys(t).forEach(n=>{let s=t[n],d=i[n];if(!(!s||!d)){if(s.bytesReceived&&s.bytesReceived>d.bytesReceived&&(s.bandwidth=Math.round((s.bytesReceived-d.bytesReceived)/r)),s.bytesSent&&s.bytesSent>d.bytesSent&&(s.bandwidth=Math.round((s.bytesSent-d.bytesSent)/r)),s.packetsReceived)if(s.packetsReceived>d.packetsReceived||s.packetsLost>d.packetsLost){let l=s.packetsLost-d.packetsLost,h=s.packetsReceived-d.packetsReceived;s.packetLoss=parseFloat((100*l/(l+h)).toFixed(2))}else s.packetLoss=0;s.framesDropped&&d.framesDropped&&s.framesDropped>d.framesDropped&&(s.framesDroppedDelta=parseFloat(((s.framesDropped-d.framesDropped)/r).toFixed(0)))}}),a}function Rt(i,r){return c(this,arguments,function*(a,e,t={}){let n=yield an(a),s={timestamp:Date.now(),transport:nn(n),rtps:sn(n,t)};return e?on(s,e):(yield E.delay(Xa),Rt(a,s,t))})}var qt=.8,ze=class extends z{constructor(e,t,i,r,n){super();this._remoteSDP={};this._remoteCandidates={};this._state=L.IDLE;this._isOpen=!1;this._remotePeerId=null;this._statInterval=null;this._settingsInterval=null;this._failedOnCreate=null;this._remoteStream=null;this._iceRestartTimeout=null;this._reconnectionTimeout=null;this._reconnectionPrevented=!1;this._fingerprint=null;this._neverConnected=!0;this._prevConsumerSettings={};this._lastNetworkStat={rtt:0,loss:0,date:0};this._remoteNetworkStat={rtt:0,loss:0};this._networkLimits={badNet:{loss:3,rtt:1e3},goodNet:{loss:.5,rtt:600}};if(this._signaling=i,this._mediaSource=r,this._participantId=e,this._isMaster=t,this._serverSettings=n,this._perfStatReporter=new Ye(this,i,!0),this.subscribe(this._signaling,ue.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,Se.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,Se.SOURCE_CHANGED,this._applySettings.bind(this)),this._pc=new RTCPeerConnection({iceServers:p.iceServers,iceTransportPolicy:p.forceRelayPolicy?"relay":"all"},{optional:[{googSuspendBelowMinBitrate:!1}]}),this._pc.onicecandidate=this._handleIceCandidate.bind(this),this._pc.ontrack=this._onAddTrack.bind(this),this._pc.oniceconnectionstatechange=this._onIceConnectionStateChange.bind(this),this._pc.onconnectionstatechange=this._onConnectionStateChange.bind(this),this._pc.onsignalingstatechange=this._onSignalingStateChange.bind(this),this._prevConsumerSettings={},this._isMaster){try{this._mediaSource.addTrackToPeerConnection(this._pc,!0),this._applySettings()}catch(s){m.log(g.ERROR,"addTrack-direct"),o.error("Unable to add media source tracks",s,{participantId:this._participantId}),this._failedOnCreate=s;return}this._createOffer(!1).catch(s=>{this._state===L.IDLE?this._failedOnCreate=s:this.close(s)})}this._startSettingsInterval(),this._startStatInterval()}getState(){return this._state}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==L.IDLE&&e!==L.CLOSED&&e!==L.FAILED&&this._startStatInterval()}open(e=null){return c(this,null,function*(){if(this._isOpen){o.warn("DirectTransport: Already opened",{participantId:this._participantId});return}if(this._failedOnCreate){this.close(this._failedOnCreate);return}if(o.debug("DirectTransport: Open transport",{participantId:this._participantId}),this._isOpen=!0,this._remotePeerId=e,!this._isMaster)try{this._mediaSource.addTrackToPeerConnection(this._pc,!0),this._applySettings()}catch(i){m.log(g.ERROR,"addTrack-direct"),o.error("DirectTransport: Unable to add media source tracks",i,{participantId:this._participantId}),this.close(i);return}this._setState(L.OPENED);let t=e;if(!e){let i=Object.keys(this._remoteSDP);t=i[i.length-1]}if(t&&this._remoteSDP[t])try{yield this._setRemoteDescription(t,this._remoteSDP[t])}catch(i){this.close();return}this._remoteSDP={},this._remoteCandidates={},this._triggerEvent(N.ACTIVE_PARTICIPANTS_NO_SIGNAL)})}updateSettings(e){Gt(e,this._serverSettings)||(this._serverSettings=e,this._applySettings())}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}close(e){this._isOpen=!1,this._stopReconnection(),this._remoteStream&&(this._remoteStream.getTracks().forEach(t=>{t.stop(),this._triggerEvent(N.REMOTE_TRACK_REMOVED,this._remoteStream,t)}),this._remoteStream=null),this._stopStatInterval(),this._stopSettingsInterval(),this._pc&&(this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.oniceconnectionstatechange=null,this._pc.onconnectionstatechange=null,this._pc.onsignalingstatechange=null,this._pc.close()),this.unsubscribe(),e?(o.error("DirectTransport: Closed",e,{participantId:this._participantId}),this._setState(L.FAILED)):(o.debug("DirectTransport: Closed",{participantId:this._participantId}),this._setState(L.CLOSED)),this._triggerEvent(N.PEER_CONNECTION_CLOSED)}_setState(e){this._state!==e&&(o.debug(`DirectTransport: State changed to ${e}`,{participantId:this._participantId}),this._state=e,this._triggerEvent(N.STATE_CHANGED,e))}_onSignalingNotification(e){var t,i,r,n;switch(e.notification){case A.TRANSMITTED_DATA:this._handleTransmittedData(e);break;case A.SETTINGS_UPDATE:Object.assign(this._networkLimits.badNet,((t=e.settings)==null?void 0:t.badNet)||{}),Object.assign(this._networkLimits.goodNet,((i=e.settings)==null?void 0:i.goodNet)||{});break;case A.CUSTOM_DATA:e.data.hasOwnProperty("sdk")&&(this._remoteNetworkStat.rtt=((r=e.data.sdk)==null?void 0:r.rtt)||0,this._remoteNetworkStat.loss=((n=e.data.sdk)==null?void 0:n.loss)||0);break}}_handleTransmittedData(e){let t=e.data,i=E.getPeerIdString(e.peerId);E.composeMessageId(e)===this._participantId&&(t.candidate&&t.candidate.candidate?this._addIceCandidate(i,t.candidate).catch(this.close.bind(this)):t.sdp&&this._setRemoteDescription(i,t.sdp).catch(this.close.bind(this)))}_addIceCandidate(e,t){return c(this,null,function*(){if(this._isOpen&&(!this._remotePeerId||this._remotePeerId===e)&&this._pc&&this._pc.remoteDescription){o.debug("Add remote ice candidate",{participantId:this._participantId,candidate:t});try{yield this._pc.addIceCandidate(new RTCIceCandidate(t))}catch(i){throw m.log(g.ERROR,"addIceCandidate-direct"),o.error("Unable to add remote ice candidate",i,{participantId:this._participantId,candidate:t}),i}}else o.debug("Cache remote ice candidate",{participantId:this._participantId,candidate:t}),this._remoteCandidates[e]=this._remoteCandidates[e]||[],this._remoteCandidates[e].push(t)})}_setRemoteCandidates(e){return c(this,null,function*(){if(!this._remoteCandidates[e]){o.log(`No cached candidates found for peer ${e}`);return}let t=this._remoteCandidates[e];this._remoteCandidates[e]=[];for(let i of t)try{yield this._addIceCandidate(e,i)}catch(r){}})}_setRemoteDescription(e,t){return c(this,null,function*(){if(this._isOpen&&(!this._remotePeerId||this._remotePeerId===e)&&this._pc){o.debug("Add remote description",{participantId:this._participantId,sdp:t}),this._calcFingerprint(t.sdp);try{yield this._pc.setRemoteDescription(new RTCSessionDescription(t)),yield this._setRemoteCandidates(e)}catch(i){throw m.log(g.ERROR,"setRemoteDescription-direct"),o.error("Unable to set remote description",i,{participantId:this._participantId,sdp:t}),i}}else this._remoteSDP[e]=t})}_onAddTrack(e){o.debug("Added remote track",{participantId:this._participantId,kind:e.track.kind}),this._remoteStream?this._remoteStream.addTrack(e.track):(this._remoteStream=new MediaStream([e.track]),this._remoteStream.onremovetrack=t=>{this._triggerEvent(N.REMOTE_TRACK_REMOVED,this._remoteStream,t.track)}),this._triggerEvent(N.REMOTE_TRACK_ADDED,this._remoteStream,e.track)}_handleIceCandidate(e){return c(this,null,function*(){e.candidate&&this._signaling.ready&&(o.debug("Local ice candidate",{participantId:this._participantId,candidate:e.candidate}),yield this._signaling.sendCandidate(this._participantId,e.candidate))})}_onSignalingStateChange(){switch(o.debug(`DirectTransport: Signaling state changed to ${this._pc.signalingState}`,{participantId:this._participantId}),this._pc.signalingState){case"have-local-offer":let e=this._pc.localDescription;e?this._signaling.sendSdp(this._participantId,e).catch(this.close.bind(this)):this.close(new Error);break;case"have-remote-offer":this._createAnswer().catch(this.close.bind(this)).then(t=>c(this,null,function*(){return this._signaling.sendSdp(this._participantId,t)})).catch(this.close.bind(this));break}}_onIceConnectionStateChange(){switch(o.debug(`DirectTransport: Ice Connection state changed to ${this._pc.iceConnectionState}`,{participantId:this._participantId}),this._pc.iceConnectionState){case"checking":let e=this.getState();e===L.IDLE||e===L.OPENED?this._setState(L.CONNECTING):this._setState(L.RECONNECTING);break}}_onConnectionStateChange(){switch(o.debug(`DirectTransport: Connection state changed to ${this._pc.connectionState}`,{participantId:this._participantId}),m.log(g.ICE_CONNECTION_STATE,this._pc.connectionState),this._pc.connectionState){case"connected":this._neverConnected=!1,this._setState(L.CONNECTED),this._stopReconnection(),E.getPeerConnectionHostInfo(this._pc).then(e=>{e&&m.log(g.ICE_CONNECTION_TYPE,e.type)});break;case"failed":case"disconnected":this._reconnectionPrevented?this.close(new Error(`Ice connection ${this._pc.connectionState}`)):(this._setState(L.RECONNECTING),this._startReconnection());break;case"closed":this.close(new Error("Ice connection closed"));break}}_startReconnection(){this._reconnectionTimeout||this._iceRestartTimeout||(o.log("Waiting for reconnection...",{participantId:this._participantId}),this._reconnectionTimeout=window.setTimeout(()=>{this._reconnectionTimeout=null,this._neverConnected?this._requestTopologySwitch():this._startIceRestart()},p.transportConnectionWaitTime))}_requestTopologySwitch(){this._isMaster&&this._signaling.ready&&(o.log("Switch topology DIRECT to SERVER",{participantId:this._participantId}),this._signaling.switchTopology(Ee.SERVER))}_stopReconnection(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=null),this._iceRestartTimeout&&(clearTimeout(this._iceRestartTimeout),this._iceRestartTimeout=null)}_startIceRestart(){this._isMaster?(m.log(g.ICE_RESTART),o.log("Ice restart",{participantId:this._participantId}),this._createOffer(!0).catch(this.close.bind(this))):o.debug("Waiting for ice restart...",{participantId:this._participantId}),this._iceRestartTimeout=window.setTimeout(()=>{this._iceRestartTimeout=null,o.error("Ice restart failed",{participantId:this._participantId}),m.log(g.ERROR,"iceRestart-direct"),this._requestTopologySwitch()},p.iceRestartWaitTime)}_createOffer(e){return c(this,null,function*(){let t={iceRestart:e,offerToReceiveAudio:!0,offerToReceiveVideo:!0};return o.debug("Create offer",{participantId:this._participantId,options:t}),this._pc.createOffer(t).catch(i=>{throw o.error("Unable to create offer",i,{participantId:this._participantId}),m.log(g.ERROR,"createOffer-direct"),i}).then(i=>c(this,null,function*(){return o.debug("Created offer",{participantId:this._participantId,offer:i}),i=ze._patchDescription(i),o.debug("Set local description",{participantId:this._participantId,offer:i}),this._calcFingerprint(i.sdp),this._pc.setLocalDescription(i).then(()=>this._pc.localDescription)})).catch(i=>{throw o.error("Unable to set local description",i,{participantId:this._participantId}),m.log(g.ERROR,"setLocalDescription-direct"),i})})}_createAnswer(){return c(this,null,function*(){return o.debug("Create answer",{participantId:this._participantId}),this._pc.createAnswer().catch(e=>{throw o.error("Unable to create answer",e,{participantId:this._participantId}),m.log(g.ERROR,"createAnswer-direct"),e}).then(e=>c(this,null,function*(){return o.debug("Created answer",{participantId:this._participantId,answer:e}),e=ze._patchDescription(e),o.debug("Set local description",{participantId:this._participantId,answer:e}),this._calcFingerprint(e.sdp),this._pc.setLocalDescription(e)})).then(()=>this._pc.localDescription).catch(e=>{throw o.error("Unable to set local description",e,{participantId:this._participantId}),m.log(g.ERROR,"setLocalDescription-direct"),e})})}static _patchDescription(e){let t=!!y.baseChromeVersion();return e.sdp=E.patchSDP(e.sdp,p.preferH264&&y.canPreferH264(),y.isBrokenH264(),p.preferVP9,t&&p.audioNack),e}_onReplacedTrack(e){this._pc&&(this._pc.getSenders().forEach(t=>{t.track&&t.track.kind===e.kind&&(t.track.enabled=e.enabled,t.replaceTrack(e).catch(i=>{o.error("DirectTransport: Unable to replace track",i,{participantId:this._participantId}),m.log(g.ERROR,"replaceTrack-direct")}))}),this._applySettings())}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}Rt(this._pc,this._lastStat).then(t=>{this._lastStat=t;let i={inbound:{topology:Ee.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="inbound-rtp"?(r.userId=this._participantId,!0):!1)},outbound:{topology:Ee.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="outbound-rtp")}};this._checkBadNetwork(i),this._triggerEvent(N.REMOTE_DATA_STATS,i),this._statInterval=window.setTimeout(e,p.statisticsInterval)})};this._statInterval=window.setTimeout(e,p.statisticsInterval)}_stopStatInterval(){this._statInterval&&(window.clearTimeout(this._statInterval),this._statInterval=null)}_checkBadNetwork(e){if(!this._signaling.ready)return;let t=oe=>oe.rtt<=this._networkLimits.goodNet.rtt&&oe.loss<=this._networkLimits.goodNet.loss,i=oe=>oe.rtt>=this._networkLimits.badNet.rtt||oe.loss>=this._networkLimits.badNet.loss,r=Math.round(e.outbound.transport.currentRoundTripTime*1e3)||0,n=e.inbound.rtps.reduce((oe,Fe)=>Math.max(oe,Fe.packetLoss||0),0),s={rtt:this._lastNetworkStat.rtt*(1-qt)+r*qt,loss:this._lastNetworkStat.loss*(1-qt)+n*qt},d=i(s),l=t(s),h=i(this._remoteNetworkStat),P=t(this._remoteNetworkStat),b=i(this._lastNetworkStat),j=t(this._lastNetworkStat),le=d||h?.2:l&&P?1:0,be=Date.now();if((b!==d||j!==l||be-this._lastNetworkStat.date>p.networkStatisticsInterval)&&(this._lastNetworkStat.date=Date.now(),this._signaling.customData({sdk:Object.assign({type:"bad-net"},s)},null).catch(oe=>{o.warn("Unable to send [bad-net]",oe)})),le){let oe={};oe[this._participantId]=oe[""]=le,this._triggerEvent(N.NETWORK_STATUS,oe)}this._lastNetworkStat.rtt=s.rtt,this._lastNetworkStat.loss=s.loss}_startSettingsInterval(){let e=2e3;if(this._settingsInterval)return;let t=()=>{if(!this._pc){this._stopSettingsInterval();return}this._applySettings(),this._settingsInterval=window.setTimeout(t,e)};this._settingsInterval=window.setTimeout(t,e)}_stopSettingsInterval(){this._settingsInterval&&(window.clearTimeout(this._settingsInterval),this._settingsInterval=null)}_calcFingerprint(e){let t=E.sdpFingerprint(e);this._fingerprint===null?this._fingerprint=t:(T.onFingerprintChange(this._fingerprint.xor(t).toString()),this._fingerprint=null)}_applySettings(){var t;let e=this._mediaSource.getMediaSettings().isScreenSharingEnabled?this._serverSettings.screenSharing:this._serverSettings.camera;e&&((t=this._pc)==null?void 0:t.connectionState)==="connected"&&(this._prevConsumerSettings=E.applySettings(this._pc,e,this._prevConsumerSettings))}};var Jr=(r=>(r.producerNotification="producerNotification",r.producerCommand="producerCommand",r.consumerScreenShare="consumerScreenShare",r.producerScreenShare="producerScreenShare",r))(Jr||{}),Pt=Jr;var Qe=He(require("messagepack"));var Oi=class{constructor(){this.streamDescriptionByCompactId=new Map}getStreamDescription(e){return this.streamDescriptionByCompactId.get(e)}handleMessage(e){var n,s;let t=new Uint8Array(e),i=t[0],r=t.subarray(1);switch(i){case 1:let d=(0,Qe.decode)(r);return Object.entries(d).forEach(([x,le])=>{let be=It(x);this.streamDescriptionByCompactId.set(le,be)}),null;case 2:case 4:let l=(0,Qe.decode)(r),h=[];for(let x of l){let le=this.getStreamDescription(x);le&&h.push(le.participantId)}return i===2?{type:"notification",notification:A.AUDIO_ACTIVITY,activeParticipants:h}:{type:"notification",notification:A.STALLED_ACTIVITY,stalledParticipants:h};case 3:let P=(0,Qe.decode)(r);return{type:"notification",notification:A.SPEAKER_CHANGED,speaker:(n=this.getStreamDescription(P))==null?void 0:n.participantId};case 5:let b=(0,Qe.decode)(r);return{type:"notification",notification:A.VIDEO_QUALITY_UPDATE,quality:{maxBitrate:b[0],maxDimension:b[1]}};case 6:let j=(0,Qe.decode)(r),W={};for(let[x,le]of Object.entries(j)){let be=(s=this.getStreamDescription(Number(x)))==null?void 0:s.participantId;be&&(W[be]=le/100)}return{type:"notification",notification:A.NETWORK_STATUS,statuses:W};case 7:return this._createParticipantSourcesUpdateNotification(r);default:return o.debug("unsupported message type: "+i),null}}_createParticipantSourcesUpdateNotification(e){let t=(0,Qe.decode)(e),i=[];for(let[r,n]of Object.entries(t)){let s=n[0],d=n[1],l=n[2],h;if(s!==null){if(h=this.getStreamDescription(s),!h){o.error(`could not uncompress participant ID ${s}`);continue}}else h=null;if(l===null){o.error("unexpected null sequenceNumber",r,n);continue}let P=ye.PARTICIPANT_AGNOSTIC_TRACK_PREFIX+"-"+r,b=d?d>>>0:null;i.push({participantStreamDescription:h,streamId:P,rtpTimestamp:b,sequenceNumber:l})}return{type:"notification",notification:A.PARTICIPANT_SOURCES_UPDATE,participantUpdateInfos:i}}};var cn=90,dn=4294967295,Te=class extends z{constructor(e,t,i){super();this._pc=null;this._producerNotification=null;this._producerCommand=null;this._producerScreen=null;this._consumerScreen=null;this._isOpen=!1;this._reconnectionPrevented=!1;this._state=L.IDLE;this._statInterval=null;this._settingsInterval=null;this._statBytes={};this._ssrcMap={};this._producerOfferIsProcessing=!1;this._producerNextOffer=null;this._prevConsumerSettings={};this._captureSender=null;this._captureReceiver=null;this._participantIdRegistry=null;this._disabledSenders=new Set;this._rtpReceiversByStreamId={};this._producerSessionId="";this._signaling=e,this._mediaSource=t,this.subscribe(this._signaling,ue.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,Se.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,Se.SOURCE_CHANGED,this._applyConsumerSettings.bind(this)),this.subscribe(this._mediaSource,Se.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._perfStatReporter=new Ye(this,e),this._serverSettings=i,o.debug("ServerTransport: Created")}getState(){return this._state||L.IDLE}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==L.IDLE&&e!==L.CLOSED&&e!==L.FAILED&&this._startStatInterval()}open(){if(this._isOpen){o.log("ServerTransport: Already opened connections");return}this._isOpen=!0,this._openConnection()}close(e){this._isOpen=!1,this._closeConnection(),this.unsubscribe(),e?(o.error("ServerTransport: Closed",e),this._setState(L.FAILED)):(o.debug("ServerTransport: Closed"),this._setState(L.CLOSED))}removeParticipant(e){var t;(t=this._captureReceiver)==null||t.close(e)}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}updateSettings(e){Gt(e,this._serverSettings)||(this._serverSettings=e,this._applyConsumerSettings())}_closeConnection(){this._stopStatInterval(),this._stopSettingsInterval(),this._removeCaptureSender(),this._removeCaptureReceiver(),this._pc&&(this._rtpReceiversByStreamId={},this._disabledSenders.forEach(e=>{var t;return(t=e.track)==null?void 0:t.stop()}),this._disabledSenders.clear(),this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.onsignalingstatechange=null,this._participantIdRegistry=null,Te._closeDataChannel(this._producerNotification),Te._closeDataChannel(this._producerCommand),Te._closeDataChannel(this._producerScreen),Te._closeDataChannel(this._consumerScreen),this._pc.close(),this._pc=null,this._producerOfferIsProcessing=!1,this._producerNextOffer=null),this._triggerEvent(N.PEER_CONNECTION_CLOSED)}static _closeDataChannel(e){e&&(e.onopen=null,e.onmessage=null,e.onerror=null,e.close())}_createDataChannel(e,t,i){o.debug(`[${t}] data channel opening`);let r=e.createDataChannel(t,{ordered:!0});r.onopen=()=>{o.debug(`[${t}] data channel opened`),r.onerror=n=>{o.error(`[${t}] data channel error`,n)},i(r)}}_openConnection(e=!1){o.debug("ServerTransport: Open single connection");let t={};y.baseChromeVersion()&&(t.sdpSemantics=Te._isUnifiedPlanSupported()?"unified-plan":"plan-b"),this._pc=new RTCPeerConnection(t,{optional:[{googSuspendBelowMinBitrate:!1}]}),this._pc.ontrack=this._onAddTrack.bind(this,this._pc),this._pc.onconnectionstatechange=E.throttle(i=>{this._pc&&this._onConnectionStateChange(this._pc,i)},500),this._pc.onsignalingstatechange=Te._onSignalingStateChange.bind(this,this._pc),p.producerNotificationDataChannel&&this._createDataChannel(this._pc,Pt.producerNotification,i=>{this._producerNotification=i,this._producerNotification.binaryType="arraybuffer",this._participantIdRegistry=new Oi,this._signaling.setParticipantIdRegistry(this._participantIdRegistry),this._signaling.setProducerNotificationDataChannel(i)}),p.producerCommandDataChannel&&this._createDataChannel(this._pc,Pt.producerCommand,i=>{this._producerCommand=i,this._signaling.setProducerCommandDataChannel(i)}),p.producerScreenDataChannel&&this._createDataChannel(this._pc,Pt.producerScreenShare,i=>{this._producerScreen=i,this._producerScreen.binaryType="arraybuffer",this._createCaptureReceiver()});try{this._mediaSource.addTrackToPeerConnection(this._pc),this._prevConsumerSettings={},this._applyConsumerSettings()}catch(i){o.error("ServerTransport: Unable to add media source tracks",i),m.log(g.ERROR,"addTrack-single"),this.close(i);return}p.consumerScreenDataChannel&&this._createDataChannel(this._pc,Pt.consumerScreenShare,i=>{this._consumerScreen=i,this._consumerScreen.binaryType="arraybuffer";let r=this._mediaSource.getScreenTrack();r&&this._createCaptureSender(r)}),e||this._allocateConsumer(),this._setState(L.OPENED),this._startStatInterval(),this._startSettingsInterval()}_reconnect(){this.getState()!==L.OPENED&&(this._setState(L.RECONNECTING),this._closeConnection(),this._openConnection(!0))}_signalActiveParticipants(e){this._triggerEvent(N.SIGNALLED_ACTIVE_PARTICIPANTS,e)}_signalStalledParticipants(e){this._triggerEvent(N.SIGNALLED_STALLED_PARTICIPANTS,e)}_signalSpeakerChanged(e){this._triggerEvent(N.SIGNALLED_SPEAKER_CHANGED,e)}_signalNetworkStatus(e){this._triggerEvent(N.NETWORK_STATUS,e)}_updateSSRCMap(e){e&&e.sdp.split(`
12
+ `).forEach(t=>{let i=`a=ssrc:([0-9]+) label:(audio|video)-((?:[ug]?[\\d]+)|(?:mix)|(?:${ye.PARTICIPANT_AGNOSTIC_TRACK_PREFIX}-[0-9]+))`,r=new RegExp(i).exec(t);r&&(this._ssrcMap[r[1]]=r[3])})}_createCaptureSender(e){!e||!p.consumerScreenDataChannel||!this._consumerScreen||!this._mediaSource.getMediaSettings().isScreenSharingEnabled||(this._captureSender&&this._removeCaptureSender(),this._captureSender=new dt(e,this._consumerScreen))}_removeCaptureSender(){var e;(e=this._captureSender)==null||e.destroy(),this._captureSender=null}_createCaptureReceiver(){!p.producerScreenDataChannel||!this._producerScreen||!this._participantIdRegistry||(this._captureReceiver&&this._removeCaptureReceiver(),this._captureReceiver=new ot(this._producerScreen,this._participantIdRegistry,(e,t)=>{this._triggerEvent(N.REMOTE_STREAM_SECOND,e,t)},e=>{this._triggerEvent(N.REMOTE_STREAM_SECOND,e,null)}))}_removeCaptureReceiver(){var e;(e=this._captureReceiver)==null||e.destroy(),this._captureReceiver=null}_applyConsumerSettings(){let e=this._mediaSource.getMediaSettings().isScreenSharingEnabled&&!p.consumerScreenDataChannel?this._serverSettings.screenSharing:this._serverSettings.camera;if(e&&this._pc){let t=[];this._pc.getSenders().forEach(i=>{if(!i.track||i.track.kind!==se.video)return;let r=!this._disabledSenders.has(i),n=e.maxDimension!==0;if(r&&!n){o.log("Disabling video upload"),this._disabledSenders.add(i),i.replaceTrack(y.getBlackMediaTrack()).catch(d=>{o.error("Could not disable video upload",d)});return}let s=this._mediaSource.getSendVideoTrack();if(!r&&n&&s){o.log("Enabling video upload"),this._disabledSenders.delete(i);let d=i.track;d.enabled=s.enabled,i.replaceTrack(s).then(()=>d.stop()).catch(l=>{o.error("Could not enable video upload",l)})}E.applyVideoTrackSettings(e,i,s!=null?s:i.track,this._prevConsumerSettings,t)}),this._prevConsumerSettings=t}}_onScreenSharingStatus(e){e.track?this._createCaptureSender(e.track):this._removeCaptureSender()}_setState(e){this._state!==e&&(this._state=e,this._triggerEvent(N.STATE_CHANGED,e))}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}this._collectStat().then(t=>{this._reportStats(t),this._detectStaleTracks(t)}).catch(()=>{}),this._statInterval=window.setTimeout(e,p.statisticsInterval)};this._statInterval=window.setTimeout(e,p.statisticsInterval)}_stopStatInterval(){this._statInterval&&(window.clearTimeout(this._statInterval),this._statInterval=null),this._statBytes={}}_startSettingsInterval(){let e=2e3;if(this._settingsInterval)return;let t=()=>{if(!this._pc){this._stopSettingsInterval();return}this._applyConsumerSettings(),this._settingsInterval=window.setTimeout(t,e)};this._settingsInterval=window.setTimeout(t,e)}_stopSettingsInterval(){this._settingsInterval&&(window.clearTimeout(this._settingsInterval),this._settingsInterval=null)}_collectStat(){return c(this,null,function*(){if(!this._pc)return Promise.reject();let e=yield Rt(this._pc,this._lastStat,this._ssrcMap);return this._lastStat=e,e})}_reportStats(e){this._triggerEvent(N.REMOTE_DATA_STATS,{inbound:{topology:Ee.SERVER,transport:e.transport,rtps:e.rtps.filter(t=>t.type==="inbound-rtp")},outbound:{topology:Ee.SERVER,transport:e.transport,rtps:e.rtps.filter(t=>t.type==="outbound-rtp")}})}_detectStaleTracks(e){let t=e.rtps.find(s=>s.type==="inbound-rtp"&&s.kind==="audio"&&this._ssrcMap[s.ssrc]==="mix");if(!t)return;let i=ye.AUDIO_MIX,r=this._statBytes[i],n=!1;if(r){let s=t.bytesReceived-r.bytesReceived;s>=0&&s<=5&&(n=!0),r.stalled!==n&&this._triggerEvent(N.REMOTE_ALL_STALL,n)}this._statBytes[i]={bytesReceived:t.bytesReceived,stalled:n}}_allocateConsumer(){if(!this._signaling.ready)return;let e={estimatedPerformanceIndex:Ye.getEstimatedPerformanceIndex(),audioMix:!0,consumerUpdate:!0,producerNotificationDataChannelVersion:p.producerNotificationDataChannel?6:0,producerCommandDataChannelVersion:p.producerCommandDataChannel?2:0,consumerScreenDataChannelVersion:p.consumerScreenDataChannel?1:0,producerScreenDataChannelVersion:p.producerScreenDataChannel?1:0,onDemandTracks:!0,unifiedPlan:Te._isUnifiedPlanSupported(),singleSession:!0,videoTracksCount:p.videoTracksCount};this._signaling.allocateConsumer(null,e)}_acceptProducer(e){return c(this,null,function*(){if(this._producerOfferIsProcessing){this._producerNextOffer=e,o.debug("[single] wait until other remote offer is processed");return}this._producerOfferIsProcessing=!0;let t=new RTCSessionDescription({type:"offer",sdp:e});if(o.debug("[single] set remote offer",{offer:t}),!this._pc)throw new Error("Interrupt allocation");this._pc.setRemoteDescription(t).catch(i=>{throw o.error("[single] unable to set remote offer",i),m.log(g.ERROR,"setRemoteDescription-single"),i}).then(()=>c(this,null,function*(){if(o.debug("[single] create local answer"),!this._pc)throw new Error("Interrupt allocation");return this._pc.createAnswer()})).catch(i=>{throw o.error("[single] unable to create answer",i),m.log(g.ERROR,"createAnswer-single"),i}).then(i=>(i.sdp=E.patchSDP(i.sdp,!1,y.isBrokenH264(),!1),i)).then(i=>c(this,null,function*(){if(o.debug("[single] set local answer",{answer:i}),!this._pc)throw new Error("Interrupt allocation");return yield this._pc.setLocalDescription(i),i})).catch(i=>{throw o.error("[single] unable to set local answer",i),m.log(g.ERROR,"setLocalDescription-single"),i}).then(i=>c(this,null,function*(){o.debug("[single] transmit local answer",{answer:i}),this._updateSSRCMap(t),yield this._signaling.acceptProducer(i,Object.keys(this._ssrcMap)),o.debug("[single] remote offer has been processed")})).catch(i=>{o.warn("[single] unable to send local answer",i),m.log(g.ERROR,"acceptProducer")}).then(()=>c(this,null,function*(){if(this._producerOfferIsProcessing=!1,this._producerNextOffer){o.debug("[single] there is other unprocessed remote offer, process it");let i=this._producerNextOffer;return this._producerNextOffer=null,this._acceptProducer(i)}})).catch(i=>this.close(i))})}_onSignalingNotification(e){return c(this,null,function*(){if(!!this._isOpen)switch(e.notification){case A.PRODUCER_UPDATED:yield this._onProducerUpdated(e);break;case A.REALLOC_CON:this._reconnect();break;case A.AUDIO_ACTIVITY:this._signalActiveParticipants(e.activeParticipants);break;case A.SPEAKER_CHANGED:this._signalSpeakerChanged(e.speaker);break;case A.STALLED_ACTIVITY:this._signalStalledParticipants(e.stalledParticipants);break;case A.NETWORK_STATUS:this._signalNetworkStatus(e.statuses);break}})}_onProducerUpdated(e){return c(this,null,function*(){this._producerSessionId&&this._producerSessionId!==e.sessionId&&this._reconnect(),p.breakVideoPayloadTypes&&(o.log("test mode enabled, video switched off"),this._signaling.requestTestMode("breakVideoPayloadTypes")),this._producerSessionId=e.sessionId,yield this._acceptProducer(e.description)})}_onAddTrack(e,t){o.debug("[single] remote track (added)",{track:t.track});let i=t.streams[0];i?(i.onremovetrack||(i.onremovetrack=n=>{this._triggerEvent(N.REMOTE_TRACK_REMOVED,i.id,i,n.track)}),i.getTracks().find(n=>n.id===t.track.id)||i.addTrack(t.track),this._rtpReceiversByStreamId[i.id]=t.receiver,this._triggerEvent(N.REMOTE_TRACK_ADDED,i.id,i,t.track)):o.error("[single] unable to get media stream from track event")}static _onSignalingStateChange(e,t){o.debug("[single] signaling state changed",{state:e.signalingState},t)}_onConnectionStateChange(e,t){switch(o.debug("[single] connection state changed",{state:e.connectionState},t),m.log(g.ICE_CONNECTION_STATE,e.connectionState),e.connectionState){case"failed":this._reconnectionPrevented?this.close(new Error("Ice connection failed")):this._reconnect();break;case"connecting":let i=this.getState();i===L.IDLE||i===L.OPENED?this._setState(L.CONNECTING):e.iceConnectionState==="checking"&&this._setState(L.RECONNECTING);break;case"disconnected":this._reconnectionPrevented?this.close(new Error("Ice connection disconnected")):this._setState(L.RECONNECTING);break;case"connected":this._setState(L.CONNECTED),E.getPeerConnectionHostInfo(e).then(r=>{r&&m.log(g.ICE_CONNECTION_TYPE,r.type)});break}}_onReplacedTrack(e,t){this._pc&&(p.consumerScreenDataChannel&&t&&(e=t),this._pc.getSenders().forEach(i=>{i.track&&i.track.kind===e.kind&&!this._disabledSenders.has(i)&&(i.track.enabled=e.enabled,i.replaceTrack(e).catch(r=>{o.error("ServerTransport: Unable to replace track",r),m.log(g.ERROR,"replaceTrack-single")}))})),this._applyConsumerSettings()}static _isUnifiedPlanSupported(){let e=y.baseChromeVersion();return e?p.isUnifiedPlanSupported("Chrome",e):p.isUnifiedPlanSupported(y.browserName(),y.browserVersion())}getStreamWaitingTimeMs(e,t){if(!this._pc)return m.log(g.PAT_WAITING_TIME_ERROR,"noConnection"),o.error("Cannot get stream waiting time, peer connection is not initialized"),0;let i=this._rtpReceiversByStreamId[e];if(!i)return m.log(g.PAT_WAITING_TIME_ERROR,"noReceiver"),o.error(`Cannot get stream waiting time, cannot find RTP receiver by stream ID: ${e}`),0;let r=i.getSynchronizationSources();if(!r||!r.length)return o.log(`Cannot get stream waiting time, ${e} receiver has no synchronization sources`),0;let s=r[0].rtpTimestamp;if(!Number.isInteger(s))return m.log(g.PAT_WAITING_TIME_ERROR,"timestampNotInteger"),o.error(`Cannot get stream waiting time, ${e} receiver's RTP timestamp is not an integer: ${s}`),0;let d=t-s&dn,l=Math.ceil(d/cn);return Math.min(100,Math.max(0,l))}};var N=(x=>(x.REMOTE_TRACK_ADDED="REMOTE_TRACK_ADDED",x.REMOTE_TRACK_REMOVED="REMOTE_TRACK_REMOVED",x.REMOTE_STREAM_SECOND="REMOTE_STREAM_SECOND",x.REMOTE_ALL_STALL="REMOTE_ALL_STALL",x.REMOTE_DATA_STATS="REMOTE_DATA_STATS",x.STATE_CHANGED="STATE_CHANGED",x.LOCAL_STATE_CHANGED="LOCAL_STATE_CHANGED",x.SIGNALLED_ACTIVE_PARTICIPANTS="SIGNALLED_ACTIVE_PARTICIPANTS",x.ACTIVE_PARTICIPANTS_NO_SIGNAL="ACTIVE_PARTICIPANTS_NO_SIGNAL",x.SIGNALLED_SPEAKER_CHANGED="SIGNALLED_SPEAKER_CHANGED",x.SIGNALLED_STALLED_PARTICIPANTS="SIGNALLED_STALLED_PARTICIPANTS",x.TOPOLOGY_CHANGED="TOPOLOGY_CHANGED",x.NETWORK_STATUS="NETWORK_STATUS",x.PEER_CONNECTION_CLOSED="PEER_CONNECTION_CLOSED",x))(N||{}),L=(d=>(d.IDLE="IDLE",d.OPENED="OPENED",d.CONNECTING="CONNECTING",d.RECONNECTING="RECONNECTING",d.CONNECTED="CONNECTED",d.CLOSED="CLOSED",d.FAILED="FAILED",d))(L||{}),Ee=(t=>(t.DIRECT="DIRECT",t.SERVER="SERVER",t))(Ee||{}),ki=class extends z{constructor(e,t,i,r){super();this._allocated=[];this._opened=[];this._directTransport=null;this._serverTransport=null;this._dtListeners=[];this._stListeners=[];this._states={};this._localState="IDLE";this._signaling=t,this._mediaSource=i,this._topology=e,this._serverSettings=r,this.subscribe(this._signaling,ue.NOTIFICATION,this._onSignalingNotification.bind(this)),e==="SERVER"&&(this._serverTransport=this._createServerTransport())}updateSettings(e){this._serverSettings=e,this._directTransport&&this._directTransport.updateSettings(e),this._serverTransport&&this._serverTransport.updateSettings(e)}updateStatisticsInterval(){this._directTransport&&this._directTransport.updateStatisticsInterval(),this._serverTransport&&this._serverTransport.updateStatisticsInterval()}allocate(e,t=!1){if(this._allocated.indexOf(e)!==-1){o.warn(`The participant [${e}] has already had allocated transport`);return}this._allocated.push(e),this._topology==="DIRECT"&&!this._directTransport&&(this._directTransport=this._createDirectTransport(e,t)),this._topology==="SERVER"&&!this._serverTransport&&(this._serverTransport=this._createServerTransport())}open(e,t=null){let i=!1;for(let r of e){if(this._opened.indexOf(r)!==-1){o.warn(`The participant [${r}] has already had opened transport`);continue}if(this._allocated.indexOf(r)===-1){o.warn(`The participant [${r}] has no allocated transport`);continue}this._opened.push(r),i=!0}!i||(this._topology==="DIRECT"&&this._directTransport&&this._directTransport.open(t),this._topology==="SERVER"&&this._serverTransport&&(this._serverTransport.open(),this._setStates(e,this._serverTransport.getState()),this._setLocalState(this._serverTransport.getState())),o.debug("The transport has been opened",e))}close(e){var r;let t=this._allocated.indexOf(e),i=this._opened.indexOf(e);t<0&&o.warn(`The participant [${e}] transport has already deallocated`),this._topology==="DIRECT"&&this._directTransport&&(this._directTransport.close(),this._directTransport=null),this._topology==="SERVER"&&((r=this._serverTransport)==null||r.removeParticipant(e),this._setState(e,"CLOSED")),i>=0&&this._opened.splice(i,1),t>=0&&this._allocated.splice(t,1)}destroy(){this.unsubscribe(),this._dtListeners&&this._dtListeners.forEach(e=>{e.dispose()}),this._stListeners&&this._stListeners.forEach(e=>{e.dispose()}),this._directTransport&&(this._directTransport.close(),this._directTransport=null),this._serverTransport&&(this._serverTransport.close(),this._serverTransport=null),this._allocated=[],this._opened=[]}getTopology(){return this._topology}isAllocated(e){return this._allocated.indexOf(e)>=0}allocated(){return this._allocated.slice()}opened(){return this._opened.slice()}_setStates(e,t){let i=e.filter(r=>this._states[r]!==t?(this._states[r]=t,!0):!1);i.length&&this._triggerEvent("STATE_CHANGED",i,t)}_setState(e,t){this._states[e]!==t&&(this._states[e]=t,this._triggerEvent("STATE_CHANGED",[e],t))}_setLocalState(e){this._localState!==e&&(this._localState=e,this._triggerEvent("LOCAL_STATE_CHANGED",e))}_onSignalingNotification(e){if(e.notification===A.TOPOLOGY_CHANGED)return this._onTopologyChanged(e);if(e.notification===A.RECORD_STARTED)return this._onRecordStarted(e)}_onTopologyChanged(e){var t;if(e.topology!==this._topology){if(o.log(`Topology changed ${this._topology} -> ${e.topology}`),m.log(g.TOPOLOGY_CHANGE_REQUESTED,e.topology),this._topology=e.topology,this._topology==="SERVER"&&(this._serverTransport?this._serverTransport.allowRestart():(this._serverTransport=this._createServerTransport(),this._opened.length>0&&((t=this._directTransport)==null||t.preventRestart(),this._serverTransport.open()))),this._topology==="DIRECT"){let i=e.offerTo||[],r=e.offerToTypes||[],n=e.offerToDeviceIdxs||[],s=i.length&&r.length?E.composeParticipantId(i[0],r[0],n[0]):null;if(this._serverTransport&&this._serverTransport.preventRestart(),!this._allocated||this._allocated.length===0){o.error("Topology changed to DIRECT, but the list of allocated participants is empty");return}this._allocated.length>1&&o.warn("Topology changed to DIRECT, but the allocated participants count more then one");let d=this._allocated[0];if(this._directTransport)this._directTransport.allowRestart();else{let l=s===d;this._directTransport=this._createDirectTransport(d,l)}this._opened.indexOf(d)>=0&&this._directTransport.open()}this._triggerEvent("TOPOLOGY_CHANGED",this._topology)}}_onRecordStarted(e){this._serverTransport&&this._serverTransport.open()}_createDirectTransport(e,t=!1){let i=new ze(e,t,this._signaling,this._mediaSource,this._serverSettings);return this._setLocalNoiseSuppression(!0),this._dtListeners&&this._dtListeners.length>0&&o.warn(`The list of direct listeners for the participant [${e}] is not empty`),this._dtListeners=[],this._dtListeners.push(i.addEventListener("REMOTE_TRACK_ADDED",this._onDirectRemoteTrackAdded.bind(this,e)),i.addEventListener("REMOTE_TRACK_REMOVED",this._onDirectRemoteTrackRemoved.bind(this,e)),i.addEventListener("REMOTE_DATA_STATS",this._onDirectRemoteDataStats.bind(this)),i.addEventListener("STATE_CHANGED",this._onDirectTransportChanged.bind(this,e)),i.addEventListener("NETWORK_STATUS",this._onTransportNetworkStatus.bind(this)),i.addEventListener("PEER_CONNECTION_CLOSED",this._onPeerConnectionClosed.bind(this,"DIRECT"))),i}_createServerTransport(){let e=new Te(this._signaling,this._mediaSource,this._serverSettings);return this._setLocalNoiseSuppression(!1),this._stListeners&&this._stListeners.length>0&&o.warn("The list of server transport listeners is not empty"),this._stListeners=[],this._stListeners.push(e.addEventListener("REMOTE_TRACK_ADDED",this._onServerRemoteTrackAdded.bind(this)),e.addEventListener("REMOTE_TRACK_REMOVED",this._onServerRemoteTrackRemoved.bind(this)),e.addEventListener("REMOTE_ALL_STALL",this._onServerRemoteAllStall.bind(this)),e.addEventListener("REMOTE_DATA_STATS",this._onServerRemoteDataStats.bind(this)),e.addEventListener("STATE_CHANGED",this._onServerTransportChanged.bind(this)),e.addEventListener("ACTIVE_PARTICIPANTS_NO_SIGNAL",this._onTransportActiveParticipantsNoSignal.bind(this)),e.addEventListener("SIGNALLED_ACTIVE_PARTICIPANTS",this._onTransportActiveParticipants.bind(this)),e.addEventListener("SIGNALLED_SPEAKER_CHANGED",this._onTransportSpeakerChanged.bind(this)),e.addEventListener("SIGNALLED_STALLED_PARTICIPANTS",this._onTransportStalledParticipants.bind(this)),e.addEventListener("NETWORK_STATUS",this._onTransportNetworkStatus.bind(this)),e.addEventListener("REMOTE_STREAM_SECOND",this._onRemoteStreamSecond.bind(this)),e.addEventListener("PEER_CONNECTION_CLOSED",this._onPeerConnectionClosed.bind(this,"SERVER"))),e}_releaseDirectTransport(e){this._directTransport&&(e&&this._directTransport.close(),this._directTransport=null),this._dtListeners&&(this._dtListeners.forEach(t=>{t.dispose()}),this._dtListeners=[])}_releaseServerTransport(e){this._serverTransport&&(e&&this._serverTransport.close(),this._serverTransport=null),this._stListeners&&(this._stListeners.forEach(t=>{t.dispose()}),this._stListeners=[])}_setLocalNoiseSuppression(e){var t;p.noiseSuppression!==e&&(p.noiseSuppression=e,(t=this._mediaSource)==null||t.updateNoiseSuppression())}_onDirectTransportChanged(e,t){if(t==="CONNECTED"&&this._topology==="DIRECT"&&this._releaseServerTransport(!0),(t==="CLOSED"||t==="FAILED")&&(this._releaseDirectTransport(!1),this._topology==="DIRECT")){let i=this._opened.indexOf(e);i>=0&&this._opened.splice(i,1);let r=this._allocated.indexOf(e);r>=0&&this._allocated.splice(r,1)}this._topology==="DIRECT"&&(this._setState(e,t),this._setLocalState(t))}_onServerTransportChanged(e){let t=this._opened.slice();e==="CONNECTED"&&this._topology==="SERVER"&&this._releaseDirectTransport(!0),(e==="CLOSED"||e==="FAILED")&&(this._releaseServerTransport(!1),this._topology==="SERVER"&&(this._allocated=[],this._opened=[])),this._topology==="SERVER"&&(this._setStates(t,e),this._setLocalState(e))}_onTransportActiveParticipantsNoSignal(){this._triggerEvent("ACTIVE_PARTICIPANTS_NO_SIGNAL")}_onTransportActiveParticipants(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_ACTIVE_PARTICIPANTS",e)}_onTransportStalledParticipants(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_STALLED_PARTICIPANTS",e)}_onTransportSpeakerChanged(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_SPEAKER_CHANGED",e)}_onTransportNetworkStatus(e){this._triggerEvent("NETWORK_STATUS",e)}_onRemoteStreamSecond(e,t){this._triggerEvent("REMOTE_STREAM_SECOND",e,t)}_onPeerConnectionClosed(e){this._triggerEvent("PEER_CONNECTION_CLOSED",e)}_onServerRemoteAllStall(e){this._topology==="SERVER"&&this._triggerEvent("REMOTE_ALL_STALL",e)}_onServerRemoteDataStats(e){this._triggerEvent("REMOTE_DATA_STATS",e)}_onDirectRemoteTrackAdded(e,t,i){this._triggerEvent("REMOTE_TRACK_ADDED",e,t,i)}_onDirectRemoteTrackRemoved(e,t,i){this._triggerEvent("REMOTE_TRACK_REMOVED",e,t,i)}_onDirectRemoteDataStats(e){this._triggerEvent("REMOTE_DATA_STATS",e)}_onServerRemoteTrackAdded(e,t,i){this._triggerEvent("REMOTE_TRACK_ADDED",e,t,i)}_onServerRemoteTrackRemoved(e,t,i){this._triggerEvent("REMOTE_TRACK_REMOVED",e,t,i)}getStreamWaitingTimeMs(e,t){return this._topology!=="SERVER"?(m.log(g.PAT_WAITING_TIME_ERROR,"wrongTopology"),o.error(`Cannot get stream waiting time, incorrect topology: ${this._topology}`),0):this._serverTransport?this._serverTransport.getStreamWaitingTimeMs(e,t):(m.log(g.PAT_WAITING_TIME_ERROR,"noTransport"),o.error("Cannot get stream waiting time, server transport is not initialized"),0)}};var Xe=(e=>(e.VOLUMES_DETECTED="VOLUMES_DETECTED",e))(Xe||{}),wi=class extends z{constructor(e){super();this._detector=null;this._interval=null;this.subscribe(e,N.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(e,N.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(e,N.SIGNALLED_ACTIVE_PARTICIPANTS,this._onSignalledActiveParticipants.bind(this)),this.subscribe(e,N.ACTIVE_PARTICIPANTS_NO_SIGNAL,this._onActiveParticipantsNoSignal.bind(this))}destroy(){var e;this._interval&&(window.clearTimeout(this._interval),this._interval=null),this.unsubscribe(),(e=this._detector)==null||e.destroy(),this._detector=null}_onRemoteTrackAdded(e,t,i){var r;if(i.kind===se.audio&&((r=this._detector)==null||r.destroy(),this._detector=new yt(e,t),!this._interval)){let n=()=>{this._collectVolumes(),this._interval=window.setTimeout(n,p.voiceParams.interval)};this._interval=window.setTimeout(n,p.voiceParams.interval)}}_onRemoteTrackRemoved(e,t,i){i.kind===se.audio&&(!this._detector||this._detector.stream!==t||(this._detector.destroy(),this._detector=null))}_collectVolumes(){if(!this._detector)return;let e={},t=this._detector.trackId,i=this._detector.getLevel();if(t===ye.AUDIO_MIX){if(this._activeParticipants)for(let r of this._activeParticipants)e[r]=i}else e[t]=i;this._triggerEvent("VOLUMES_DETECTED",e)}_onSignalledActiveParticipants(e){this._activeParticipants=e}_onActiveParticipantsNoSignal(){this._activeParticipants=null}};var Ni=(e=>(e.SPEAKER_CHANGED="SPEAKER_CHANGED",e))(Ni||{}),xi=class extends z{constructor(e,t){super();this._speakerId=null;this._serverAudioActivityAvailable=!1;this.subscribe(e,Xe.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this.subscribe(t,N.SIGNALLED_SPEAKER_CHANGED,this._onServerSpeakerChanged.bind(this)),this.subscribe(t,N.SIGNALLED_ACTIVE_PARTICIPANTS,this._onReceivedServerAudioActivity.bind(this)),this.subscribe(t,N.ACTIVE_PARTICIPANTS_NO_SIGNAL,this._onStoppedReceivingServerAudioActivity.bind(this))}destroy(){this.unsubscribe()}_onVolumesDetected(e){if(this._serverAudioActivityAvailable)return;let t=0,i=null;if(Object.keys(e).forEach(r=>{let n=e[r].smoothed;n>t&&n>p.voiceParams.threshold&&(t=n,i=r)}),i&&i!==this._speakerId){let r=this._speakerId&&e.hasOwnProperty(this._speakerId)?e[this._speakerId].smoothed:0;t>r*p.voiceParams.speakerLevelMultiplier&&(this._speakerId=i,this._triggerEvent("SPEAKER_CHANGED",i))}}_onServerSpeakerChanged(e){this._serverAudioActivityAvailable&&this._triggerEvent("SPEAKER_CHANGED",e)}_onReceivedServerAudioActivity(){this._serverAudioActivityAvailable=!0}_onStoppedReceivingServerAudioActivity(){this._serverAudioActivityAvailable=!1}};var Jt=class extends z{constructor(e,t,i){super();this._states={};this._volumes={};this._participants={};this._connectionTimeout=0;this._volumeTimeout=0;this._transport=e,this._participants=i,this.subscribe(e,N.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(t,Xe.VOLUMES_DETECTED,this._onVolumesDetected.bind(this))}destroy(){this.unsubscribe(),this._connectionTimeout&&window.clearTimeout(this._connectionTimeout),this._volumeTimeout&&window.clearTimeout(this._volumeTimeout)}onChangeRemoteMediaSettings(e,t){t.isAudioEnabled||(this._volumes[e]=1),t.isAudioEnabled&&(this._volumes[e]=0)}_onTransportStateChanged(e,t){e.forEach(i=>this._states[i]=t),t===L.OPENED&&(this._connectionTimeout||(this._connectionTimeout=window.setTimeout(this._onConnectionTimeout.bind(this),p.specListenerParams.connectionTimeout)),this._volumeTimeout||(this._volumeTimeout=window.setTimeout(this._onVolumeTimeout.bind(this),p.specListenerParams.volumeTimeout))),t===L.FAILED&&this._connectionTimeout&&(o.warn("Transport failed, send callSpecError"),m.log(g.CALL_SPEC_ERROR,`${this._transport.getTopology()}_CONNECTION_TIMEOUT`))}_onVolumesDetected(e){Object.keys(e).forEach(t=>{this._volumes[t]=Math.max(e[t].real,this._volumes[t]||0)})}_onConnectionTimeout(){let e=i=>i!==L.CONNECTED;(()=>Object.values(this._states).filter(e).length>0)()&&(o.warn("There is not connected transport, send callSpecError"),m.log(g.CALL_SPEC_ERROR,`${this._transport.getTopology()}_CONNECTION_TIMEOUT`)),this._connectionTimeout=0}_onVolumeTimeout(){let e=[];Object.keys(this._volumes).forEach(t=>{if(this._volumes[t]>0)return;let i="UNKNOWN",r=this._participants[t];r&&r.platform&&(i=r.platform),e.indexOf(i)<0&&(e.push(i),m.log(g.CALL_SPEC_ERROR,`${this._transport.getTopology()}_VOLUME_TIMEOUT_${i}`))}),e.length&&o.warn("There is silent participant, send callSpecError"),this._volumeTimeout=0}};var pn=1e3,ln=1e4;var un=15,B=class extends z{constructor(e,t,i){super();this._mediaSource=null;this._conversation=null;this._state="IDLE";this._participantState=G.CALLED;this._participants={};this._transport=null;this._debugInfo=null;this._volumesDetector=null;this._speakerDetector=null;this._localVolumeDetector=null;this._specListener=null;this._activeSpeakerId=null;this._lastSignalledActiveSpeakerId=null;this._serverSettings={camera:null,screenSharing:null};this._lastStalled={};this._remoteAllStalled=!1;this._audioFix=null;this._streamByStreamId=new Map;this._streamIdByStreamDescription=new Map;this._streamWaitTimerByStreamDescription=new Map;this._sequenceNumberByStreamDescription=new Map;this._cooldownTimestampByStreamDescription=new Map;this._cooldownQueueCleanupTimer=null;m.create(e,i),this._api=e,this._signaling=t,this._onUnload=()=>{this._conversation&&this._api&&this._api.hangupConversation(this._conversation.id),m.destroy()},window.addEventListener("unload",this._onUnload),this._audioOutput=new Wt,p.videoTracksCount>0&&(this._cooldownQueueCleanupTimer=window.setInterval(this._cleanupCooldownQueue.bind(this),pn))}static current(){return B._current}static hangupAfterInit(){B._activationMutex&&!B._current&&(B._delayedHangup=!0)}static id(){var e,t;return((t=(e=B._current)==null?void 0:e._conversation)==null?void 0:t.id)||null}onStart(e,t,i,r="",n=!1,s=!1){return c(this,null,function*(){if(B._activationMutex)throw m.log(g.ERROR,"startCall"),o.warn("Conversation: there is already running activation"),new O(M.FAILED);B._activationMutex=!0;try{this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(i);let d=this._mediaSource.getMediaSettings();t===De.CHAT||e.length>1?this._logWithMediaSettings(g.OUTGOING_MULTIPARTY_CALL,d):this._logWithMediaSettings(g.OUTGOING_CALL,d);let l=yield this._startConversation(e,t,Ne.OUTGOING,i,r,n,s);if(!this._conversation)throw new O(M.UNKNOWN_ERROR);if(this._participantState=G.ACCEPTED,this._signaling.changeMediaSettings(d),yield this._registerParticipants(l.conversation.participants),this._processConnectionData(l),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),B._delayedHangup)throw new O(M.CANCELED);o.debug("Outgoing call",{opponentIds:e,opponentType:t,mediaOptions:i});let h=Object.values(this._participants),P;return p.batchParticipantsOnStart&&(P=E.mapSharedParticipants(h)),T.onLocalStream(this._mediaSource.getStream(),this._mediaSource.getMediaSettings()),T.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,P),T.onLocalStatus(q.WAITING),this._toggleJoinAvailability(),this._changeFeatureSet(),this._changeNeedRate(),B._current=this,this._conversation.concurrent?yield this._acceptConcurrent():p.batchParticipantsOnStart||this._setParticipantsStatus(h,q.WAITING),this._conversation}catch(d){throw this._close(d,"Unable to start conversation"),d}finally{B._activationMutex=!1}})}onJoin(e){return c(this,null,function*(){if(B._activationMutex)throw m.log(g.ERROR,"joinCall"),o.warn("Conversation: there is already running activation"),new O(M.FAILED);B._activationMutex=!0,this._state="PROCESSING";try{this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(e.mediaOptions);let t=this._mediaSource.getMediaSettings();this._logWithMediaSettings(g.JOIN_CONVERSATION,t);let i=yield this._joinConversation(e);if(!this._conversation)throw new O(M.UNKNOWN_ERROR);return T.onLocalStream(this._mediaSource.getStream(),t),this._conversation.waitingHall?(o.log("In waiting hall"),B._current=this,B._activationMutex=!1,this._signaling.readyToSend(),T.onLocalStatus(q.WAITING_HALL),this._conversation):this._onJoinPart2(i)}catch(t){throw B._activationMutex=!1,this._close(t,"Unable to join conversation"),t}})}_onJoinPart2(e){return c(this,null,function*(){o.debug("Join conversation part 2"),B._activationMutex=!0;try{if(this._participantState=G.ACCEPTED,!this._conversation||!this._mediaSource)throw new O(M.UNKNOWN_ERROR);if(this._signaling.changeMediaSettings(this._mediaSource.getMediaSettings()),yield this._registerParticipants(e.conversation.participants),this._processConnectionData(e),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),B._delayedHangup)throw new O(M.CANCELED);let t=Object.values(this._participants),i;return p.batchParticipantsOnStart&&(i=E.mapSharedParticipants(t)),T.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,i),T.onLocalStatus(q.WAITING),this._toggleJoinAvailability(),this._changeNeedRate(),this._state="ACTIVE",this._changeFeatureSet(),B._current=this,p.batchParticipantsOnStart||this._setParticipantsStatus(t,q.WAITING),this._openTransport(t,!1),this._conversation}catch(t){throw this._close(t,"Unable to join conversation"),t}finally{B._activationMutex=!1}})}onPush(r){return c(this,arguments,function*(e,t=Q.USER,i){if(B._activationMutex)throw o.warn("Conversation: there is already running activation"),new O(M.REJECTED);B._activationMutex=!0;try{let n=yield this._prepareConversation(e,t,i);if(this._mediaSource=this._createMediaSource(),!this._conversation)throw new O(M.UNKNOWN_ERROR);if(!n.conversation.participants.find(d=>{var l;return d.state===G.CALLED&&d.id===((l=this._conversation)==null?void 0:l.userId)}))throw o.log("Push rejected (there is an active call)"),m.log(g.PUSH,"rejected"),new O(M.REJECTED);if(yield this._registerParticipants(n.conversation.participants),this._processConnectionData(n),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),m.log(g.PUSH,"accepted"),B._current=this,B._delayedHangup)throw new O(M.CANCELED);B._activationMutex=!1}catch(n){throw B._activationMutex=!1,this._close(n,"Unable to handle inbound call push"),n}})}_isInWaitingHall(e){if(!e.conversation||(e.conversation.options||[]).indexOf(At.WAITING_HALL)<0)return!1;let t=(e.conversation.participants||[]).find(i=>E.comparePeerId(i.peerId,e.peerId));return t&&t.restricted||!1}_acceptConcurrent(){return c(this,null,function*(){if(!this._mediaSource||!this._conversation)throw new O(M.UNKNOWN_ERROR);this._state="PROCESSING";let e=this._mediaSource.getMediaSettings();this._logWithMediaSettings(g.ACCEPT_CONCURRENT,e),o.debug("Concurrent call",{conversationId:this._conversation.id});try{yield this._signaling.acceptCall(this._mediaSource.getMediaSettings()),T.onCallAccepted(),this._state="ACTIVE",this._participantState=G.ACCEPTED,this._changeFeatureSet(),this._openTransport(Object.values(this._participants),!0)}catch(t){this._close(t,"Unable to accept concurrent call")}})}accept(e){return c(this,null,function*(){if(this._state!=="IDLE")throw m.log(g.ERROR,"acceptIncoming"),o.error("Unable to accept a call - invalid state"),new Error("Unable to accept a call - invalid state");if(!this._mediaSource||!this._conversation)throw new O(M.UNKNOWN_ERROR);this._state="PROCESSING",o.debug("Accept incoming call",e);try{yield this._mediaSource.request(e);let t=this._mediaSource.getMediaSettings();this._logWithMediaSettings(g.ACCEPT_INCOMING,t),this._signaling.changeMediaSettings(t),yield this._signaling.acceptCall(t),this._participantState=G.ACCEPTED;let i=Object.values(this._participants),r;p.batchParticipantsOnStart&&(r=E.mapSharedParticipants(i)),T.onCallAccepted(),T.onLocalStream(this._mediaSource.getStream(),t),T.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,r),T.onLocalStatus(q.WAITING),this._toggleJoinAvailability(),this._changeNeedRate();let n=Object.values(this._conversation.muteStates);return(n.includes(xe.MUTE)||n.includes(xe.MUTE_PERMANENT))&&(yield this._processMuteState(Object.keys(this._conversation.muteStates))),this._state="ACTIVE",this._changeFeatureSet(),p.batchParticipantsOnStart||this._setParticipantsStatus(i,q.WAITING),this._openTransport(i,!0),this._conversation}catch(t){throw this._close(t,"Unable to accept call"),t}})}decline(){return c(this,null,function*(){var e;if(this._state!=="IDLE")throw m.log(g.ERROR,"declineIncoming"),o.error("Unable to decline a call - invalid state"),new Error("Unable to decline a call - invalid state");this._state="PROCESSING",o.debug("Decline incoming call"),this._logWithMediaSettings(g.DECLINE_INCOMING,(e=this._mediaSource)==null?void 0:e.getMediaSettings()),this._participantState=G.HUNGUP,this._signaling.ready&&(yield this._signaling.hangup(M.REJECTED)),this._close(new O(M.REJECTED))})}hangup(){return c(this,null,function*(){o.debug("Hangup");let e=this._state==="ACTIVE"?M.HUNGUP:M.CANCELED;m.log(g.HANGUP,e),this._signaling.ready?(yield this._signaling.hangup(e),this._close(new O(e))):T.onHangup(new O(M.HUNGUP),this._conversation&&this._conversation.id)})}addParticipant(e,t){return c(this,null,function*(){if(!this._signaling.ready){this._close(new O(M.UNKNOWN_ERROR),"Unable to add participant");return}let i=yield this._signaling.addParticipant(e,t),r=null;i.type==="error"&&(i.error==="call-unfeasible"?r=i.status:r=M.UNKNOWN_ERROR);let n=i.participant;yield this._onAddParticipant(E.composeId(n),n,r)})}removeParticipant(e,t=!1){return c(this,null,function*(){this._signaling.ready&&(yield this._signaling.removeParticipant(e,t),this._onRemoveParticipant(e))})}setVolume(e){this._audioOutput.volume=e}updateStatisticsInterval(){this._transport&&this._transport.updateStatisticsInterval()}_openTransport(e,t){if(!this._transport)return;let i=[];for(let r of e)(r.state===G.CALLED||r.state===G.ACCEPTED)&&this._transport&&!this._transport.isAllocated(r.id)&&this._transport.allocate(r.id,t),this._transport&&r.state===G.ACCEPTED&&i.push(r.id);i.length&&this._transport.open(i)}_close(e,t){t&&o.error(t,e),o.debug("Close conversation",e),e.error?this._signaling.ready&&this._signaling.hangup(M.FAILED):m.log(g.ERROR,e.hangup),B._activationMutex=!1;let i=this._conversation&&this._conversation.id;if([M.CANCELED,M.NOT_FRIENDS,M.CALLEE_IS_OFFLINE,M.CALLER_IS_BLOCKED].indexOf(e.hangup)!==-1||e.hangup===M.REJECTED&&!e.remote){T.onHangup(e,i),this.destroy();return}if(e.hangup===M.HUNGUP&&(!e.remote||this._participantState===G.CALLED)){T.onHangup(e,i),this.destroy();return}if(e.hangup===M.MISSED&&!e.remote){T.onHangup(e,i),this.destroy();return}if(e.hangup===M.SOCKET_CLOSED&&B._current&&!this._conversation){this._cleanupSignaling(),this._cleanupMediaSource();return}if(e.hangup===M.BUSY&&!e.remote){this._cleanupSignaling(),this._cleanupMediaSource();return}this._state="CLOSE",this._participantState=G.HUNGUP,this._changeFeatureSet(),this._cleanupMediaSource(),this._cleanupParticipants(),this._cleanupParticipantAgnosticStreams(),this._cleanupTransport(),this._cleanupSpeakerDetector(),this._cleanupSpecListener(),this._cleanupSignaling(),this._api.cleanup(),m.destroy(),this._conversation=null,B._current=null,B._delayedHangup=!1,T.onHangup(e||new O(M.UNKNOWN_ERROR),i),this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null)}destroy(){let e=this._conversation&&this._conversation.id;o.debug("Destroy conversation",{conversationId:e}),this._cleanupMediaSource(),this._cleanupParticipants(),this._cleanupParticipantAgnosticStreams(),this._cleanupTransport(),this._cleanupSpeakerDetector(),this._cleanupSpecListener(),this._cleanupSignaling(),this._api.cleanup(),this._cleanupListeners(),m.destroy(),this._conversation=null,B._current=null,B._delayedHangup=!1,this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null)}_getConversationParams(e){return c(this,null,function*(){let t=yield this._api.getConversationParams(e);o.debug("Api.getConversationParams",t);let i=[],{turn_server:r,stun_server:n}=t;if(n&&i.push(n),r){let s=r.urls.filter((d,l,h)=>h.indexOf(d)===l);s.push(`${s[s.length-1]}?transport=tcp`),i.push({urls:s,username:r.username,credential:r.credential})}return p.iceServers=i,p.wssBase=t.endpoint,p.wssToken=t.token,t.client_type&&(p.clientType=t.client_type),t})}_startConversation(e,t,i,r,n="",s=!1,d=!1){return c(this,null,function*(){let l=E.uuid();o.debug("Conversation: start",{conversationId:l,opponentIds:e,opponentType:t,direction:i});let h=r.includes(re.VIDEO),P=yield this._api.startConversation(l,e,t,h,n,s,d);o.debug("Api.startConversation",P),yield this._getConversationParams(P.id);let b=yield this._connectSignaling(Ae.START,P);return yield this._setConversation(P,b,i),b})}_joinConversation(e){return c(this,null,function*(){let{conversationId:t,mediaOptions:i,chatId:r,joinLink:n}=e;o.debug("Conversation: join",{conversationId:t,joinLink:n});let s=i.includes(re.VIDEO),d;if(t)d=yield this._api.joinConversation(t,s,r);else if(n)d=yield this._api.joinConversationByLink(n,s);else throw new O(M.UNKNOWN_ERROR);o.debug("Api.joinConversation",d),yield this._getConversationParams(d.id);let l=yield this._connectSignaling(Ae.JOIN,d);return yield this._setConversation(d,l,Ne.JOINING),l})}_prepareConversation(r){return c(this,arguments,function*(e,t=Q.USER,i){o.debug("Conversation: push",{conversationId:e,type:t,peerId:i});let n=this._api.getUserId();if(!n)throw new O(M.UNKNOWN_ERROR);let d=(yield this._getConversationParams(e)).device_idx||0,l={id:e,peerId:i,endpoint:`${p.wssBase}?userId=${n}&entityType=${t}&deviceIdx=${d}&conversationId=${e}&token=${p.wssToken}`,is_concurrent:!1,p2p_forbidden:!1,device_idx:d},h=yield this._connectSignaling(Ae.ACCEPT,l);return B._current&&(B._current._participantState===G.ACCEPTED||B._current._participantState===G.CALLED)?(o.log("Push rejected (busy)"),m.log(g.PUSH,"busy"),this._signaling.ready&&this._signaling.hangup(M.BUSY),Promise.reject({hangup:M.BUSY})):(B._current&&(B._current.destroy(),B._current=null),yield this._setConversation(l,h,Ne.INCOMING,t),h)})}_createParticipant(e){return c(this,null,function*(){let t=Object.assign({id:null,externalId:null,mediaSettings:he(),participantState:{},state:G.CALLED,status:null,remoteStream:null,mediaSource:null,platform:null,clientType:null,roles:[],networkRating:1,lastRequestedLayouts:{},muteStates:{},unmuteOptions:[]},e);if(e.externalId){let i=E.decomposeParticipantId(t.id).compositeUserId;this._api.cacheExternalId(i,e.externalId)}else t.externalId=yield this._getParticipantId(t.id);return t})}_getParticipantId(e){return c(this,null,function*(){try{let t=E.decomposeParticipantId(e),i=yield this._api.userId(t.compositeUserId);return Object.assign({deviceIdx:t.deviceIdx},i)}catch(t){throw this._close(new O(M.NETWORK_ERROR),t),t}})}_setConversation(n,s,d){return c(this,arguments,function*(e,t,i,r=Q.USER){let l=t.conversation.participants.map(W=>W.id);yield this._api.prepareUserIds(l);let h=this._api.getUserId(),P=e.device_idx||0;if(!h){let W=(t.conversation.participants||[]).find(x=>E.comparePeerId(x.peerId,t.peerId));if(!W)throw new O(M.UNKNOWN_ERROR);h=Number(W.id),W.idType&&(r=W.idType),W.deviceIdx&&(P=W.deviceIdx),this._api.setUserId(h)}let b=E.composeParticipantId(h,r,P),j=yield this._getParticipantId(b);this._conversation={userId:h,compositeUserId:b,externalId:j,acceptTime:t.conversation.acceptTime,features:t.conversation.features||[],id:t.conversation.id||e.id,participantsLimit:t.conversation.participantsLimit||30,topology:t.conversation.topology||Ee.DIRECT,direction:i,concurrent:t.isConcurrent||e.is_concurrent||!1,needRate:!1,chatId:t.conversation.multichatId,roles:[],recordInfo:null,joinLink:e.join_link,pinnedParticipantId:null,mediaModifiers:t.mediaModifiers,options:[],muteStates:{},unmuteOptions:[],networkRating:1,waitingHall:this._isInWaitingHall(t)},this._signaling.setConversationId(e.id),e.p2p_forbidden&&(p.forceRelayPolicy=e.p2p_forbidden),m.log(g.RELAY_POLICY,p.forceRelayPolicy?"1":"0"),this._changeFeatureSet(),this._logDevices()})}_updateConversation(e){if(!this._conversation)throw new O(M.UNKNOWN_ERROR);this._conversation.acceptTime=e.conversation.acceptTime,this._conversation.features=e.conversation.features||[],this._conversation.participantsLimit=e.conversation.participantsLimit||30,this._conversation.topology=e.conversation.topology||Ee.DIRECT,this._conversation.concurrent=e.isConcurrent||!1,this._conversation.chatId=e.conversation.multichatId,this._conversation.mediaModifiers=e.mediaModifiers,this._conversation.waitingHall=!1}_createMediaSource(){let e=new pi;return this.subscribe(e,Se.SOURCE_CHANGED,this._onLocalMediaStreamChanged.bind(this)),this.subscribe(e,Se.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._audioFix=new Ct(e),e}_connectSignaling(e,t){return c(this,null,function*(){return this._signaling.setEndpoint(t.endpoint),this.subscribe(this._signaling,ue.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._signaling,ue.FAILED,this._onSignalingFailed.bind(this)),this.subscribe(this._signaling,ue.RECONNECT,this._onSignalingReconnect.bind(this)),this._signaling.connect(e,t)})}_registerParticipants(e){return c(this,null,function*(){if(!!this._conversation)for(let t of e){let i=E.composeId(t);if(i===this._conversation.compositeUserId){this._conversation.roles=t.roles||[],this._conversation.roles.length&&(o.debug(`Local roles changed: ${t.roles}`),T.onLocalRolesChanged(this._conversation.roles)),t.muteStates&&(yield this._onMuteParticipant({muteStates:t.muteStates,unmuteOptions:t.unmuteOptions,mediaOptions:Object.keys(t.muteStates)}));continue}if(t.state===G.HUNGUP||t.state===G.REJECTED){this._participants[t.id]&&this._removeParticipant(this._participants[t.id],M.HUNGUP);continue}this._participants[i]=yield this._createParticipant({id:i,externalId:t.externalId&&pe.fromSignaling(t.externalId,t.deviceIdx||0),mediaSettings:he(t.mediaSettings),participantState:E.mapParticipantState(t),state:t.state,roles:t.roles||[],status:p.batchParticipantsOnStart?q.WAITING:null,muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[]}),t.roles&&t.roles.length&&(o.debug(`Roles for participant [${i}] changed: ${t.roles}`),T.onRolesChanged(this._participants[i].externalId,t.roles))}})}_processConnectionData(e){E.isEmptyObject(this._conversation.muteStates)&&e.conversation.muteStates&&this._onMuteParticipant({muteStates:e.conversation.muteStates,unmuteOptions:e.unmuteOptions,mediaOptions:Object.keys(e.conversation.muteStates),muteAll:!0}),e.conversation.pinnedParticipantId&&this._onPinParticipant(e.conversation.pinnedParticipantId),this._onRecordInfo(e.conversation.recordInfo),this._onOptionsChanged(e.conversation.options),e.chatRoom&&e.chatRoom.totalCount&&this._onChatRoomUpdated(Dt.ATTENDEE,e.chatRoom.totalCount,e.chatRoom.firstParticipants)}_allocateTransport(){if(!this._conversation||!this._mediaSource)return;this._transport=new ki(this._conversation.topology,this._signaling,this._mediaSource,this._serverSettings),this._debugInfo=new jt,this.subscribe(this._transport,N.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(this._transport,N.LOCAL_STATE_CHANGED,this._onTransportLocalStateChanged.bind(this)),this.subscribe(this._transport,N.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(this._transport,N.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(this._transport,N.REMOTE_ALL_STALL,this._onRemoteAllStall.bind(this)),this.subscribe(this._transport,N.REMOTE_DATA_STATS,this._onRemoteDataStats.bind(this)),this.subscribe(this._transport,N.SIGNALLED_STALLED_PARTICIPANTS,this._onRemoteSignalledStall.bind(this)),this.subscribe(this._transport,N.ACTIVE_PARTICIPANTS_NO_SIGNAL,this._onRemoteActivityNoSignal.bind(this)),this.subscribe(this._transport,N.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this)),this.subscribe(this._transport,N.NETWORK_STATUS,this._onNetworkStatus.bind(this)),this.subscribe(this._transport,N.REMOTE_STREAM_SECOND,this._onRemoteStreamSecond.bind(this)),this.subscribe(this._transport,N.PEER_CONNECTION_CLOSED,this._onPeerConnectionClosed.bind(this));let e=this._conversation.direction===Ne.OUTGOING&&!this._conversation.concurrent;for(let t of Object.values(this._participants))(t.state===G.ACCEPTED||t.state===G.CALLED)&&this._transport.allocate(t.id,e)}_createSpeakerDetector(){this._transport&&(this._volumesDetector=new wi(this._transport),this.subscribe(this._volumesDetector,Xe.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this._speakerDetector=new xi(this._volumesDetector,this._transport),this.subscribe(this._speakerDetector,Ni.SPEAKER_CHANGED,this._onSpeakerChanged.bind(this)),this._localVolumeDetector=new Kt(this._mediaSource))}_createSpecListener(){this._transport&&this._volumesDetector&&(this._specListener=new Jt(this._transport,this._volumesDetector,this._participants))}_logDevices(){let e=y.getCameras().length,t=y.getMicrophones().length;o.debug("Cameras: "+e+(y.hasCameraPermission()?"✔":"✖")+", Microphones: "+t+(y.hasMicrophonePermission()?"✔":"✖")),m.log(g.DEVICES,`${e}_${t}`)}_logWithMediaSettings(e,t){m.log(e,[(t==null?void 0:t.isAudioEnabled)&&"audio",(t==null?void 0:t.isVideoEnabled)&&"video"].filter(Boolean).join("_"))}_removeParticipant(e,t){var i;e.state===G.CALLED||e.state===G.ACCEPTED||this._state==="CLOSE"||!this._participants[e.id]||(t===M.HUNGUP?this._setParticipantsStatus([e],q.HANGUP):this._setParticipantsStatus([e],q.ERROR,t),(i=e.mediaSource)==null||i.disconnect(),this._conversation&&this._conversation.pinnedParticipantId===e.id&&(this._conversation.pinnedParticipantId=null),this.updateDisplayLayout([{uid:e.externalId,mediaType:fe.CAMERA,stopStream:!0}]),delete this._participants[e.id],T.onRemoteRemoved(e.externalId))}_cleanupListeners(){this.unsubscribe(),window.removeEventListener("unload",this._onUnload)}_cleanupMediaSource(){this._mediaSource&&(this._mediaSource.destroy(),this._mediaSource=null)}_cleanupParticipants(){Object.values(this._participants).forEach(e=>{var t,i,r;(t=e.remoteStream)==null||t.getTracks().forEach(n=>n.stop()),(i=e.secondStream)==null||i.getTracks().forEach(n=>n.stop()),(r=e.mediaSource)==null||r.disconnect()}),this._participants={},this._audioOutput&&this._audioOutput.destroy()}_cleanupParticipantAgnosticStreams(){o.debug("cleaning up participant-agnostic streams"),this._streamByStreamId.forEach(e=>{e.getTracks().forEach(t=>{t.stop()})}),this._streamByStreamId=new Map,this._streamWaitTimerByStreamDescription.forEach(e=>{window.clearTimeout(e)}),this._streamWaitTimerByStreamDescription=new Map,this._streamIdByStreamDescription=new Map,this._sequenceNumberByStreamDescription=new Map,this._cooldownTimestampByStreamDescription=new Map}_cleanupTransport(){this._transport&&(this._transport.destroy(),this._transport=null),this._debugInfo&&(this._debugInfo=null)}_cleanupSpeakerDetector(){this._speakerDetector&&(this._speakerDetector.destroy(),this._speakerDetector=null),this._volumesDetector&&(this._volumesDetector.destroy(),this._volumesDetector=null),this._localVolumeDetector&&(this._localVolumeDetector.destroy(),this._localVolumeDetector=null)}_cleanupSpecListener(){this._specListener&&(this._specListener.destroy(),this._specListener=null)}_cleanupSignaling(){this._signaling.close(),this._signaling.cleanup()}_onAddParticipant(e,t,i){return c(this,null,function*(){o.debug(`Add new participant [${e}]`);let r=this._participants[e];if(r&&(r.state===G.ACCEPTED||r.state===G.CALLED)){o.warn(`Participant [${r.id}:${r.state}] is already in conversation`);return}r||(this._participants[e]=yield this._createParticipant({id:e,externalId:t.externalId&&pe.fromSignaling(t.externalId,t.deviceIdx||0),mediaSettings:he(t.mediaSettings),state:t.state,roles:t.roles||[],muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[]}),r=this._participants[e]),this._setParticipantsStatus([r],q.WAITING),i?(r.state=G.HUNGUP,this._removeParticipant(r,i)):this._transport&&(r.state=G.CALLED,this._transport.allocate(r.id,!0),m.log(g.ADD_PARTICIPANT),this._invokeRolesChangedCallbackIfNeeded(r))})}_onRemoveParticipant(e){o.debug(`Remove participant [${e}]`);let t=[];for(let i=0;i<=un;i++){let r=E.compose(e,i),n=this._participants[r];n&&t.push(n)}if(!t.length){o.warn(`Participant [${e}] isn't in conversation`);return}if(this._transport)for(let i of t)this._transport.close(i.id);m.log(g.REMOVE_PARTICIPANT)}changeDevice(e){return c(this,null,function*(){return e==="audiooutput"?this._audioOutput.changeOutput():this._mediaSource?(e==="audioinput"&&(this._audioFix=new Ct(this._mediaSource)),this._mediaSource.changeDevice(e)):Promise.reject(Z.UNKNOWN)})}toggleScreenCapturing(e){return c(this,null,function*(){return this._mediaSource?this._mediaSource.toggleScreenCapturing(e):Promise.reject(Z.UNKNOWN)})}setVideoStream(e,t=!1){return c(this,null,function*(){if(this._mediaSource)return this._mediaSource.setVideoStream(e,t)})}setAudioStream(e){return c(this,null,function*(){if(this._mediaSource)return this._mediaSource.setAudioStream(e)})}toggleLocalVideo(e){return c(this,null,function*(){if(this._mediaSource)return m.log(g.MEDIA_STATUS,e?"video_1":"video_0"),this._mediaSource.toggleVideo(e)})}toggleLocalAudio(e){return c(this,null,function*(){if(this._mediaSource)return m.log(g.MEDIA_STATUS,e?"audio_1":"audio_0"),this._mediaSource.toggleAudio(e)})}changePriorities(e){return c(this,null,function*(){if(e.length<2||!this._signaling.ready)return;let t={},i={};for(let r of e){let n=typeof r.uid=="object"?r.uid:pe.fromId(r.uid),s=pe.toString(n);i[s]=r.priority}for(let r of Object.values(this._participants)){let n=pe.toString(r.externalId);i.hasOwnProperty(n)&&(t[r.id]=i[n])}yield this._signaling.changePriorities(t)})}changeParticipantState(e){return c(this,null,function*(){for(let[t,i]of Object.entries(e))if(t.length>5||i.length>5)throw new Error("key/value max length is 5 chars, mappings with empty values (null or empty string) are discarded");yield this._signaling.changeParticipantState(e)})}requestKeyFrame(e){return c(this,null,function*(){let t={};return t[Be(e)]="kf",this._signaling.updateDisplayLayout(t)})}updateDisplayLayout(e){return c(this,null,function*(){if(e.length<1||!this._signaling.ready)return;o.log(`Update display layout [${this._signaling.getNextCommandSequenceNumber()}]`,e);let t={};for(let r of e){let n=typeof r.uid=="object"?r.uid:pe.fromId(r.uid),s=this._api.getCachedOkIdByExternalId(n);if(!s){let P=pe.toString(n);o.log(`Unknown participant external ID ${P}`);continue}let d=E.compose(s,n.deviceIdx),l=Be({participantId:d,mediaType:r.mediaType,streamName:r.streamName}),h=this._participants[d];h&&(h.lastRequestedLayouts[l]=r),B._isStopStreaming(r)?this._streamIdByStreamDescription.has(l)&&!this._cooldownTimestampByStreamDescription.has(l)&&this._cooldownTimestampByStreamDescription.set(l,Date.now()):(this._cooldownTimestampByStreamDescription.delete(l),!this._streamIdByStreamDescription.has(l)&&p.videoTracksCount>0&&this._streamIdByStreamDescription.set(l,null),t[l]=B._layoutToString(r))}let i=this._cooldownTimestampByStreamDescription.keys();for(;this._streamIdByStreamDescription.size>p.videoTracksCount;){let r=i.next();if(r.done){o.error("Cannot accommodate all streaming requests: tracks available "+p.videoTracksCount+"; requested streams: "+Array.from(this._streamIdByStreamDescription.keys()));break}this._stopStreaming(r.value),t[r.value]=B._layoutToString({stopStream:!0})}yield this._sendUpdateDisplayLayout(t)})}_stopStreaming(e){if(this._cooldownTimestampByStreamDescription.delete(e),this._sequenceNumberByStreamDescription.set(e,this._signaling.getNextCommandSequenceNumber()),this._streamWaitTimerByStreamDescription.has(e)&&(o.log("Client asked to stop streaming before stream became available",e),window.clearTimeout(this._streamWaitTimerByStreamDescription.get(e)),this._streamWaitTimerByStreamDescription.delete(e)),this._streamIdByStreamDescription.get(e)){let i=It(e),r=this._participants[i.participantId];r?(i.streamName&&(i.mediaType===fe.STREAM||i.mediaType===fe.SCREEN)?T.onRemoteLive(r.externalId,i.streamName,null):T.onRemoteStream(r.externalId,null),m.log(g.PAT_DEALLOCATED)):o.log(`Cannot find participant to stop streaming: ${i.participantId}`)}this._streamIdByStreamDescription.delete(e)}_sendUpdateDisplayLayout(e){return c(this,null,function*(){if(Object.keys(e).length===0)return;let t=yield this._signaling.updateDisplayLayout(e);if(!t)return;let i=[];for(let[r,n]of Object.entries(t.errorCodeByParticipantId||{})){let s=It(r),d=this._participants[s.participantId];if(d){let l;typeof n!="number"?(o.warn(`Unexpected error code ${n} received for participant ${s.participantId}`),l=mr.UNKNOWN_ERROR):l=hr(n),i.push({externalId:d.externalId,errorReason:l})}}if(i&&i.length)throw new Yt("Could not allocate one or more participants",i)})}_cleanupCooldownQueue(){let e={},t=this._cooldownTimestampByStreamDescription.entries();do{let i=t.next();if(i.done)break;let r=i.value;if(r[1]+ln>Date.now())break;let s=r[0];this._stopStreaming(s),e[s]=B._layoutToString({stopStream:!0})}while(!0);this._sendUpdateDisplayLayout(e)}static _isStopStreaming(e){return e.stopStream}static _layoutToString(e){if(B._isStopStreaming(e))return"ss";let t="";return e.priority!==void 0&&(t+="p="+e.priority),e.width!==void 0&&e.height!==void 0&&(t!==""&&(t+=":"),t+="sz="+Math.round(e.width)+"x"+Math.round(e.height)),e.fit!==void 0&&(t!==""&&(t+=":"),t+="fit="+e.fit),t}_onParticipantSourcesUpdate(e){if(this._conversation){o.log("Received participant sources update notification",e);for(let t of e)this._waitForStreamIfNeeded(t)}}_onParticipantPromoted(e){return c(this,null,function*(){o.log("Promoted in waiting hall",!e.demote),e.demote?(o.log("Kicked from waiting hall"),this._close(new O(M.REMOVED))):(this._updateConversation(e),yield this._onJoinPart2(e))})}_onChatRoomUpdated(r){return c(this,arguments,function*(e,t=0,i=[]){o.log(`Chat room updated: ${e}`);let n=[],s=[];i.length&&(i.forEach(d=>{if(d.externalId){let l=de.fromSignaling(d.externalId);n.push(l),this._api.cacheExternalId(d.id.id,l)}else s.push(E.decomposeId(d.id.id).id)}),s.length&&!n.length&&(n=yield this._api.getExternalIdsByOkIds(s))),T.onChatRoomUpdated(e,t,n)})}_waitForStreamIfNeeded(e){var d,l;let t=this._matchStreamDescription(e.participantStreamDescription);if(!t||p.producerScreenTrack&&t.mediaType===fe.SCREEN)return;let i=Be(t),r=this._sequenceNumberByStreamDescription.get(i);if(r&&r>e.sequenceNumber){o.warn(`Participant ${t.participantId} received outdated PAT response: sequence number ${e.sequenceNumber}; last sent sequence number for given participant is ${r}`),m.log(g.PAT_OUTDATED_RESPONSE);return}let n=e.streamId,s=e.rtpTimestamp?this._getWaitingTime(n,e.rtpTimestamp):0;if(s<=0){this._streamWaitTimerByStreamDescription.delete(i);let h=t.participantId,P=this._participants[h];if(!P){m.log(g.PAT_ERROR,"participantMissing"),o.error(`Could not find participant by ID: ${h}`);return}let b=this._streamByStreamId.get(n);if(!b){m.log(g.PAT_ERROR,"streamNotFound"),o.error(`Could not find stream by ID: ${n}`);return}m.log(g.PAT_ALLOCATED),this._streamIdByStreamDescription.set(i,n);let j=(d=e.participantStreamDescription)==null?void 0:d.mediaType;if(j===fe.STREAM||j===fe.MOVIE)((l=e.participantStreamDescription)==null?void 0:l.streamName)&&T.onRemoteLive(P.externalId,e.participantStreamDescription.streamName,b);else{let W=(p.producerScreenTrack?null:P.secondStream)||b;T.onRemoteStream(P.externalId,W)}}else{o.debug(`Waiting for ${s} until stream ${n} for ${i} is switched`);let h=window.setTimeout(this._waitForStreamIfNeeded.bind(this,e),s);this._streamWaitTimerByStreamDescription.set(i,h)}}_matchStreamDescription(e){if(!e)return null;if(this._streamIdByStreamDescription.has(Be(e)))return e;let t=e.participantId;if(e.mediaType){let i={participantId:t,mediaType:null};if(this._streamIdByStreamDescription.has(Be(i)))return i}else{let i={participantId:t,mediaType:fe.CAMERA};if(this._streamIdByStreamDescription.has(Be(i)))return i;let r={participantId:t,mediaType:fe.SCREEN};if(this._streamIdByStreamDescription.has(Be(r)))return r}return o.error("Received unrequested allocation",e),null}_getWaitingTime(e,t){if(this._transport)return this._transport.getStreamWaitingTimeMs(e,t);throw new Error("transport is not initialized")}_isCallAdmin(){return this._conversation?E.includesOneOf(this._conversation.roles,[Ge.ADMIN,Ge.CREATOR]):!1}_checkAdminRole(){if(!!this._conversation&&!E.includesOneOf(this._conversation.roles,[Ge.ADMIN,Ge.CREATOR]))throw new Error("You don't have the required permission")}grantRoles(e,t,i){return c(this,null,function*(){this._checkAdminRole(),yield this._signaling.grantRoles(e,t,i)})}muteParticipant(){return c(this,arguments,function*(e=null,t,i=[]){this._checkAdminRole(),yield this._signaling.muteParticipant(e,t,i)})}pinParticipant(e,t){return c(this,null,function*(){this._checkAdminRole(),yield this._signaling.pinParticipant(e,t)})}updateMediaModifiers(e){return c(this,null,function*(){this._signaling.ready&&this._conversation&&(this._conversation.mediaModifiers=e,yield this._signaling.updateMediaModifiers(e))})}changeOptions(e){return c(this,null,function*(){if(this._signaling.ready&&this._conversation){this._checkAdminRole(),yield this._signaling.changeOptions(e);let t=tr(this._conversation.options,e);this._onOptionsChanged(t)}})}getWaitingHall(e,t,i){return c(this,null,function*(){if(!this._signaling)return Promise.reject();let r=null;e&&(r=Kr(e));let n=yield this._signaling.getWaitingHall(r,t,i);if(n.error)return Promise.reject(n.message);let s=n.participants||[],d=[],l=[],h=null;return s.length&&(s.forEach(P=>{if(P.externalId){let b=de.fromSignaling(P.externalId);d.push(b),this._api.cacheExternalId(P.id.id,b)}else l.push(E.decomposeId(P.id.id).id)}),l.length&&!d.length&&(d=yield this._api.getExternalIdsByOkIds(l)),n.hasMore&&(h=jr(s[s.length-1].id))),{participants:d,pageMarker:h,totalCount:n.totalCount||0}})}promoteParticipant(e,t){return c(this,null,function*(){this._signaling&&(yield this._signaling.promoteParticipant(e,t))})}chatMessage(e,t=null){return c(this,null,function*(){this._signaling.ready&&(yield this._signaling.chatMessage(e,t))})}chatHistory(e){return c(this,null,function*(){if(this._signaling.ready){let t=yield this._signaling.chatHistory(e);for(let i=t.messages.length-1;i>=0;i--){let r=t.messages[i];yield this._onChatMessage(r)}}})}customData(e,t=null){return c(this,null,function*(){this._signaling.ready&&(yield this._signaling.customData(e,t))})}createJoinLink(){return c(this,null,function*(){if(this._conversation){let t=(yield this._api.createJoinLink(this._conversation.id)).join_link;if(t)return this._conversation.joinLink=t,t}return Promise.reject()})}removeJoinLink(){return c(this,null,function*(){if(this._conversation&&(yield this._api.removeJoinLink(this._conversation.id)).success){delete this._conversation.joinLink;return}return Promise.reject()})}addMovie(e){return c(this,null,function*(){var r;let t={movieId:e,participantId:(r=this._conversation)==null?void 0:r.compositeUserId},i=yield this._signaling.addMovie(t);if(i.error)throw new Error(i.error);return{movieId:i.movieId,streamType:i.streamType}})}updateMovie(e,t,i,r){return c(this,null,function*(){var d;let n={movieId:e,participantId:(d=this._conversation)==null?void 0:d.compositeUserId};(t||t===0)&&(n.gain=t),i&&(n.offset=i),typeof r!==void 0&&(n.pause=r);let s=yield this._signaling.updateMovie(n);if(s.error)throw new Error(s.error)})}removeMovie(e){return c(this,null,function*(){var r;let t={movieId:e,participantId:(r=this._conversation)==null?void 0:r.compositeUserId},i=yield this._signaling.removeMovie(t);if(i.error)throw new Error(i.error)})}startStream(e=!1,t=null,i=null,r="DIRECT_LINK",n=null){return c(this,null,function*(){let s={movieId:i,name:t,privacy:r,groupId:n,streamMovie:!e},d=yield this._signaling.startStream(s);return d.error?Promise.reject(d.message):d})}stopStream(){return c(this,null,function*(){let e=yield this._signaling.stopStream();return e.error?Promise.reject():e})}recordSetRole(e,t){return c(this,null,function*(){let i=yield this._signaling.recordSetRole(e,t);if(i.error)throw new Error(i.error)})}getStreamInfo(){return c(this,null,function*(){let e=yield this._signaling.getRecordStatus();return{movieId:e.recordMovieId,preview:e.recordMoviePreviewUrl}})}setLocalResolution(e,t,i){return c(this,null,function*(){var r;if(e<p.videoMinWidth||t<p.videoMinHeight)throw new Error("Sizes received are less than the `videoMinWidth` or `videoMinHeight`");if(i==null?void 0:i.effect){if(i.effect.width<p.videoMinWidth||i.effect.height<p.videoMinHeight)throw new Error("Sizes of effect received are less than the `videoMinWidth` or `videoMinHeight`");p.videoEffectMaxHeight=i.effect.height,p.videoEffectMaxWidth=i.effect.width}return p.videoMaxWidth=e,p.videoMaxHeight=t,(r=this._mediaSource)==null?void 0:r.setResolution(e,t)})}videoEffect(e){return c(this,null,function*(){var t;return(t=this._mediaSource)==null?void 0:t.videoEffect(e)})}_onLocalMediaStreamChanged(e){return c(this,null,function*(){var t;!this._conversation||(o.debug("Local media stream changed",e.mediaSettings),T.onLocalStreamUpdate(e.mediaSettings,e.kind),this._signaling.ready&&!((t=this._conversation)==null?void 0:t.waitingHall)&&(yield this._signaling.changeMediaSettings(e.mediaSettings)))})}_onScreenSharingStatus(e){return c(this,null,function*(){var t;if(o.log("Screen sharing changed",e.track,e.mediaSettings),p.consumerScreenTrack){let i=e.track?new MediaStream([e.track]):null;T.onScreenStream(i,e.mediaSettings),this._signaling.ready&&!((t=this._conversation)==null?void 0:t.waitingHall)&&(yield this._signaling.changeMediaSettings(e.mediaSettings))}})}_changeRemoteMediaSettings(e,t){o.debug(`Remote media settings changed [${e}]`,t);let i=this._participants[e];!i||(i.mediaSettings=t,this._state==="ACTIVE"&&T.onRemoteMediaSettings(i.externalId,t),this._specListener&&this._specListener.onChangeRemoteMediaSettings(e,t))}_changeRemoteParticipantState(e,t){o.debug(`Remote participant state changed [${e}]`,t);let i=this._participants[e];!i||(i.participantState=t||{},this._state==="ACTIVE"&&(p.participantStateMapped?T.onRemoteParticipantState(i.externalId,i.participantState):T.onRemoteParticipantState(i.externalId,E.mapLegacyParticipantState(i.participantState))))}_invokeRolesChangedCallbackIfNeeded(e){this._state==="ACTIVE"&&e.roles&&e.roles.length&&(o.debug(`Roles for participant [${e.id}] changed: ${e.roles}`),T.onRolesChanged(e.externalId,e.roles))}_onSignalingNotification(e){switch(e.notification){case A.ACCEPTED_CALL:return this._onAcceptedCall(e);case A.HUNGUP:return this._onHungup(e);case A.PARTICIPANT_ADDED:return this._onAddedParticipant(e);case A.PARTICIPANT_JOINED:return this._onJoinedParticipant(e);case A.CLOSED_CONVERSATION:return this._onClosedConversation(e);case A.MEDIA_SETTINGS_CHANGED:return this._onMediaSettingsChanged(e);case A.PARTICIPANT_STATE_CHANGED:return this._onParticipantStateChanged(e);case A.RATE_CALL_DATA:return this._onNeedRate();case A.FEATURE_SET_CHANGED:return this._onFeatureSetChanged(e);case A.MULTIPARTY_CHAT_CREATED:return this._onMultipartyChatCreated(e);case A.FORCE_MEDIA_SETTINGS_CHANGE:return this._onForceMediaSettingsChange(e);case A.SETTINGS_UPDATE:return this._onSettingsUpdate(e);case A.VIDEO_QUALITY_UPDATE:return this._onVideoQualityUpdate(e);case A.REGISTERED_PEER:return this._onPeerRegistered(e);case A.SWITCH_MICRO:return this._onMicSwitched(e);case A.CHAT_MESSAGE:return this._onChatMessage(e);case A.CUSTOM_DATA:return this._onCustomData(e);case A.RECORD_STARTED:return this._onRecordInfo(e.recordInfo);case A.RECORD_STOPPED:return this._onRecordInfo(null);case A.ROLES_CHANGED:return this._onRolesChanged(e.participantId,e.roles||[]);case A.MUTE_PARTICIPANT:return this._onMuteParticipant(e);case A.PIN_PARTICIPANT:return this._onPinParticipant(e.participantId,e.unpin);case A.OPTIONS_CHANGED:return this._onOptionsChanged(e.options||[]);case A.PARTICIPANT_SOURCES_UPDATE:return this._onParticipantSourcesUpdate(e.participantUpdateInfos);case A.PROMOTE_PARTICIPANT:return this._onParticipantPromoted(e);case A.CHAT_ROOM_UPDATED:return this._onChatRoomUpdated(e.eventType,e.totalCount,e.firstParticipants)}}_onSignalingReconnect(e){return c(this,null,function*(){if(!this._conversation)return;e.conversation.acceptTime&&(this._conversation.acceptTime=e.conversation.acceptTime),e.conversation.participantsLimit&&(this._conversation.participantsLimit=e.conversation.participantsLimit),e.conversation.features&&(this._conversation.features=e.conversation.features,this._changeFeatureSet()),e.conversation.pinnedParticipantId!==this._conversation.pinnedParticipantId&&(e.conversation.pinnedParticipantId?this._onPinParticipant(e.conversation.pinnedParticipantId,!1):this._conversation.pinnedParticipantId&&this._onPinParticipant(this._conversation.pinnedParticipantId,!0)),e.conversation.state;let t=null;if(e.conversation.participants){let i=Object.keys(this._participants),r=[];for(let n of e.conversation.participants){let s=E.composeId(n),d=n.roles||[];if(s===this._conversation.compositeUserId){t=he(n.mediaSettings),_t(this._conversation.roles,d)||this._onRolesChanged(s,d);continue}r.push(s);let l=this._participants[s];if(!l)yield this._onJoinedParticipant({participantId:n.id,participant:n,mediaSettings:n.mediaSettings});else{let h=he(n.mediaSettings);Cr(h,l.mediaSettings)||this._changeRemoteMediaSettings(s,h);let P=E.mapParticipantState(n),b=l.participantState;E.isEqualParticipantState(P,b)||this._changeRemoteParticipantState(s,P),_t(d,l.roles)||this._onRolesChanged(l.id,d)}}for(let n of i)r.indexOf(n)<0&&this._removeParticipant(this._participants[n],M.HUNGUP)}this._onMuteParticipant({muteStates:e.conversation.muteStates,unmuteOptions:e.unmuteOptions,mediaOptions:[]},t),this._onRecordInfo(e.conversation.recordInfo),this._onOptionsChanged(e.conversation.options)})}_onSignalingFailed(e){o.error("Signaling failed",e),this._close(e)}_onAcceptedCall(e){return c(this,null,function*(){let t=E.composeMessageId(e),i=E.getPeerIdString(e.peerId);if(o.debug(`Participant accepted call [${t}]`),this._conversation&&t===this._conversation.compositeUserId){this._close(new O(M.MISSED),"Call accepted on other device");return}let r=this._participants[t];r||(this._participants[t]=yield this._createParticipant({id:t,mediaSettings:he(e.mediaSettings)}),r=this._participants[t]),r.state=G.ACCEPTED,r.mediaSettings=he(e.mediaSettings),this._logWithMediaSettings(g.ACCEPTED_OUTGOING,r.mediaSettings),this._conversation&&this._conversation.direction===Ne.OUTGOING&&(this._state==="IDLE"||this._state==="PROCESSING")&&(this._state="ACTIVE",this._changeFeatureSet()),this._state==="ACTIVE"&&this._transport&&this._transport.open([r.id],i),this._changeRemoteMediaSettings(t,r.mediaSettings),this._changeRemoteParticipantState(t)})}_onHungup(e){o.debug(`Participant hungup [${e.participantId}]`,{reason:e.reason});let t=E.composeMessageId(e);if(this._conversation&&this._conversation.compositeUserId===t){this._close(new O(e.reason));return}let i=this._participants[t];if(!i){o.warn(`Participant [${t}] isn't in conversation`);return}this._transport&&this._transport.close(t),i.state=e.reason===M.REJECTED?G.REJECTED:G.HUNGUP,this._state!=="CLOSE"&&this._removeParticipant(i,M.HUNGUP)}_onAddedParticipant(e){return c(this,null,function*(){var r,n;o.debug(`Participant added [${e.participantId}]`);let t=E.composeMessageId(e),i=this._participants[t];if(i&&i.state!==G.HUNGUP&&i.state!==G.REJECTED){o.debug(`Participant [${t}] is already in conversation and is active`);return}i||(this._participants[t]=yield this._createParticipant({id:t,externalId:e.participant.externalId&&pe.fromSignaling(e.participant.externalId,e.participant.deviceIdx||0),mediaSettings:he(e.participant.mediaSettings),state:e.participant.state,participantState:E.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},unmuteOptions:e.participant.unmuteOptions||[]}),i=this._participants[t]),i.state=G.CALLED,i.mediaSettings=he((r=e.participant)==null?void 0:r.mediaSettings),i.participantState=E.mapParticipantState(e.participant),i.roles=((n=e.participant)==null?void 0:n.roles)||[],this._setParticipantsStatus([i],q.WAITING),this._state==="ACTIVE"&&this._transport&&this._transport.allocate(i.id,!0),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState),this._invokeRolesChangedCallbackIfNeeded(i)})}_onJoinedParticipant(e){return c(this,null,function*(){var r;o.debug(`Participant joined [${e.participantId}]`);let t=E.composeMessageId(e),i=this._participants[t];if(i&&i.state===G.ACCEPTED){o.warn(`Participant [${t}] is already in conversation and is active`);return}i||(this._participants[t]=yield this._createParticipant({id:t,externalId:e.participant.externalId&&pe.fromSignaling(e.participant.externalId,e.participant.deviceIdx||0),mediaSettings:he(e.participant.mediaSettings),state:e.participant.state,participantState:E.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},unmuteOptions:e.participant.unmuteOptions||[]}),i=this._participants[t]),this._conversation&&this._conversation.direction===Ne.OUTGOING&&(this._state==="IDLE"||this._state==="PROCESSING")&&(this._state="ACTIVE",this._changeFeatureSet()),i.state=G.ACCEPTED,i.mediaSettings=he(e.mediaSettings),i.participantState=E.mapParticipantState(e.participant),i.roles=e.participant.roles||[],((r=this._transport)==null?void 0:r.isAllocated(i.id))?this._setParticipantsStatus([i],q.CONNECTED):this._setParticipantsStatus([i],q.WAITING),this._state==="ACTIVE"&&this._transport&&(this._transport.isAllocated(i.id)||this._transport.allocate(i.id,!0),this._transport.open([i.id])),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState),this._invokeRolesChangedCallbackIfNeeded(i)})}_onClosedConversation(e){this._toggleJoinAvailability(),this._close(new O(e.reason,{remote:!0}))}_onMediaSettingsChanged(e){let t=E.composeMessageId(e);this._changeRemoteMediaSettings(t,he(e.mediaSettings))}_onParticipantStateChanged(e){let t=E.composeMessageId(e);this._changeRemoteParticipantState(t,E.mapParticipantState(e))}_onNeedRate(){this._conversation&&(this._conversation.needRate=!0,this._changeNeedRate())}_onFeatureSetChanged(e){this._conversation&&(this._conversation.features=e.features,this._changeFeatureSet())}_onMultipartyChatCreated(e){this._conversation&&(this._conversation.chatId=e.chatId,this._toggleJoinAvailability(),T.onMultipartyChatCreated(this._conversation))}_onForceMediaSettingsChange(e){return c(this,null,function*(){if(!this._mediaSource)return;let t=this._mediaSource.getMediaSettings(),i=he(e.mediaSettings);t.isAudioEnabled!==i.isAudioEnabled&&(yield this._mediaSource.toggleAudio(i.isAudioEnabled)),t.isVideoEnabled!==i.isVideoEnabled&&(yield this._mediaSource.toggleVideo(i.isVideoEnabled)),p.consumerScreenTrack&&t.isScreenSharingEnabled!==i.isScreenSharingEnabled&&(yield this._mediaSource.toggleScreenCapturing(i.isScreenSharingEnabled))})}_onSettingsUpdate(e){let t={camera:e.camera,screenSharing:e.screenSharing};this._serverSettings=Di(this._serverSettings,t),this._transport&&this._transport.updateSettings(this._serverSettings)}_onVideoQualityUpdate(e){let t=Math.round(e.quality.maxBitrate/1024),i=e.quality.maxDimension,r={camera:Object.assign({},this._serverSettings.camera,{maxBitrateK:t,maxDimension:i}),screenSharing:null};this._serverSettings=Di(this._serverSettings,r),o.log("Got video quality update notification",this._serverSettings),this._transport&&this._transport.updateSettings(this._serverSettings)}_onPeerRegistered(e){let t=E.composeMessageId(e);this._participants[t]&&(this._participants[t].clientType=e.clientType,this._participants[t].platform=e.platform)}_onMicSwitched(e){return c(this,null,function*(){T.onDeviceSwitched(re.AUDIO,!e.mute),yield this.toggleLocalAudio(!e.mute)})}_onChatMessage(e){return c(this,null,function*(){let t=E.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getParticipantId(t),T.onChatMessage(e.message,i,e.direct)})}_onCustomData(e){return c(this,null,function*(){if(e.data.hasOwnProperty("sdk"))return;let t=E.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getParticipantId(t),T.onCustomData(e.data,i,e.direct)})}_onRecordInfo(e){return c(this,null,function*(){if(!this._conversation)return;let t=!1;if(!this._conversation.recordInfo!=!e?t=!0:this._conversation.recordInfo&&e&&(t=this._conversation.recordInfo.recordMovieId!==e.recordMovieId),t)if(e){let i=yield this._getParticipantId(e.initiator);T.onRecordStarted(i,e.recordMovieId,e.recordStartTime,e.recordType,e.recordExternalMovieId,e.recordExternalOwnerId)}else T.onRecordStopped();this._conversation.recordInfo=e})}_onRolesChanged(e,t){if(this._conversation&&e===this._conversation.compositeUserId&&!_t(this._conversation.roles,t)){o.debug(`Local roles changed: ${t}`),this._conversation.roles=t,T.onLocalRolesChanged(t),this._processMuteState(Object.keys(this._conversation.muteStates));return}let i=this._participants[e];i&&!_t(i.roles,t)&&(o.debug(`Roles for participant [${e}] changed: ${t}`),i.roles=t,T.onRolesChanged(i.externalId,t))}_onMuteParticipant(e,t=null){return c(this,null,function*(){if(!this._conversation)return;let i=e.muteStates||{},r=e.unmuteOptions||[],n=e.mediaOptions||[],s=e.adminId?this._participants[e.adminId]:null;if(e.participantId&&e.participantId!==this._conversation.compositeUserId){if(!this._isCallAdmin()){o.warn(`Not admin got mute states for participant [${e.participantId}]`);return}let d=this._participants[e.participantId];d&&(o.debug(`Mute states for participant [${e.participantId}] changed`,i),T.onMuteStates(i,r,n,e.muteAll,e.unmute,d.externalId,s==null?void 0:s.externalId));return}E.isObjectsEquals(this._conversation.muteStates,i)&&E.isArraysEquals(this._conversation.unmuteOptions,r)&&!n.length||(this._conversation.muteStates=i,this._conversation.unmuteOptions=r,e.adminId!==this._conversation.compositeUserId&&(yield this._processMuteState(n,e.muteAll,e.unmute,t,s)))})}_processMuteState(){return c(this,arguments,function*(e=[],t=!1,i=!1,r=null,n=null){if(!this._conversation||!this._mediaSource||this._participantState!==G.ACCEPTED)return;let s=Object.assign({},this._conversation.muteStates),d=this._conversation.unmuteOptions,l=this._mediaSource.getMediaSettings(),h=Object.entries(s);for(let[P,b]of h)if(!(b!==xe.MUTE&&b!==xe.MUTE_PERMANENT)&&(this._isCallAdmin()&&b===xe.MUTE_PERMANENT&&(s[P]=xe.MUTE),!(!e.includes(P)||i)))switch(P){case re.VIDEO:l.isVideoEnabled&&!(r==null?void 0:r.isVideoEnabled)&&(T.onDeviceSwitched(re.VIDEO,!1),yield this.toggleLocalVideo(!1));break;case re.AUDIO:l.isAudioEnabled&&!(r==null?void 0:r.isAudioEnabled)&&(T.onDeviceSwitched(re.AUDIO,!1),yield this.toggleLocalAudio(!1));break;case re.SCREEN_SHARING:l.isScreenSharingEnabled&&!(r==null?void 0:r.isScreenSharingEnabled)&&(T.onDeviceSwitched(re.SCREEN_SHARING,!1),yield this.toggleScreenCapturing(!1));break}T.onMuteStates(s,d,e,t,i,null,n==null?void 0:n.externalId)})}_onPinParticipant(e,t=!1){if(!this._conversation)return;let i=this._conversation.pinnedParticipantId;i&&i!==e&&(this._participants[i]?T.onPinnedParticipant(this._participants[i].externalId,!0):this._conversation.compositeUserId===i&&T.onLocalPin(!0)),this._participants[e]?T.onPinnedParticipant(this._participants[e].externalId,t):this._conversation.compositeUserId===e&&T.onLocalPin(t),this._conversation.pinnedParticipantId=t?null:e}_onOptionsChanged(e){this._conversation&&!er(this._conversation.options,e)&&(this._conversation.options=e,T.onOptionsChanged(e))}_onNetworkStatus(e){if(this._conversation){let t=[];for(let[i,r]of Object.entries(e)){let n;if(i===this._conversation.compositeUserId||i==="")n=this._conversation.networkRating;else if(this._participants[i])n=this._participants[i].networkRating;else continue;if(n!==r)if(i===this._conversation.compositeUserId||i==="")this._conversation.networkRating=r,T.onLocalNetworkStatusChanged(r);else{let s=this._participants[i];s.networkRating=r,t.push({uid:s.externalId,rating:r})}}if(t.length===0)return;o.log("Received network status update: ",e),T.onNetworkStatusChanged(t)}}_onRemoteStreamSecond(e,t){let i=this._participants[e];if(!!i){if(p.producerScreenTrack){T.onRemoteScreenStream(i.externalId,t);return}if(i.secondStream=t,p.videoTracksCount>0){let r=e;if(!this._streamIdByStreamDescription.has(r)){o.error("Received remote stream notification for a participant that has no track associated with it",r);return}let n=this._streamIdByStreamDescription.get(r);if(!n||this._streamWaitTimerByStreamDescription.has(r)){o.log("Delaying secondary stream start/stop until main stream becomes available",r);return}let s=this._streamByStreamId.get(n);if(!s){m.log(g.PAT_ERROR,"streamNotFound"),o.error(`Could not find stream by ID: ${n}`);return}T.onRemoteStream(i.externalId,i.secondStream||s)}else{let r=t||i.remoteStream;r&&T.onRemoteStream(i.externalId,r)}}}_onPeerConnectionClosed(e){e===Ee.SERVER&&this._cleanupParticipantAgnosticStreams()}_changeFeatureSet(){if(this._conversation){let e=this._state==="ACTIVE",t=this._conversation.features.includes(Xi.ADD_PARTICIPANT);T.onCallState(e,t,this._conversation)}}_changeNeedRate(){this._conversation&&this._conversation.needRate&&T.onRateNeeded()}_onVolumesDetected(e){let t=[];for(let[i,r]of Object.entries(e)){let n=this._participants[i];n&&n.externalId&&t.push({uid:n.externalId,volume:r.real})}T.onVolumesDetected(t)}_onSpeakerChanged(e){this._activeSpeakerId=e,this._participants[e]&&this._lastSignalledActiveSpeakerId!==e&&(T.onSpeakerChanged(this._participants[e].externalId),this._lastSignalledActiveSpeakerId=e)}_onTransportStateChanged(e,t){return c(this,null,function*(){o.debug(`Transport state has changed: ${t}`,e);let i;if(t===L.CONNECTED?i=q.CONNECTED:t===L.CONNECTING||t===L.OPENED?i=q.CONNECTING:t===L.RECONNECTING&&(i=q.RECONNECT),!i)return;let r=e.reduce((n,s)=>{if(s in this._participants){let d=this._participants[s];n.push(d),t===L.CONNECTED&&(d.remoteStream||(d.mediaSettings&&this._changeRemoteMediaSettings(s,d.mediaSettings),this._changeRemoteParticipantState(s,d.participantState)),this._updateDisplayLayoutFromCache(s))}else o.warn(`Participant [${s}] isn't in conversation`);return n},[]);!r.length||this._setParticipantsStatus(r,i)})}_onTransportLocalStateChanged(e){return c(this,null,function*(){o.debug(`Local transport state has changed: ${e}`),e===L.CONNECTED&&T.onLocalStatus(q.CONNECTED),e===L.CONNECTING&&T.onLocalStatus(q.CONNECTING),e===L.RECONNECTING&&T.onLocalStatus(q.RECONNECT),e===L.FAILED&&this._transport&&this._transport.allocated().length===0&&(this._signaling.ready&&(yield this._signaling.hangup(M.FAILED)),this._close(new O(M.FAILED),"Transport failed"))})}_onRemoteTrackAdded(e,t,i){return c(this,null,function*(){if(e.endsWith(ye.AUDIO_MIX))o.debug("Remote audio mix track added"),this._audioOutput.add(i);else if(e.startsWith(ye.PARTICIPANT_AGNOSTIC_TRACK_PREFIX))o.debug(`Participant-agnostic track added: ${e}`),this._streamByStreamId.set(e,t);else{o.debug(`Remote track added on the participant [${e}]`,{kind:i.kind});let r=this._participants[e];if(r||(o.warn(`Conversation: track added before participant [${e}]`),this._participants[e]=yield this._createParticipant({id:e}),r=this._participants[e],this._setParticipantsStatus([r],q.WAITING),this._activeSpeakerId===e&&this._lastSignalledActiveSpeakerId!==e&&(T.onSpeakerChanged(r.externalId),this._lastSignalledActiveSpeakerId=e)),this._transport&&!this._transport.isAllocated(r.id)&&this._transport.allocate(r.id,!1),i.kind===se.audio&&this._audioOutput.add(i),r.remoteStream!==t){if(r.remoteStream=t,r.secondStream)return;T.onRemoteStream(r.externalId,t)}r.mediaSettings&&this._changeRemoteMediaSettings(e,r.mediaSettings),p.batchParticipantsOnStart||this._changeRemoteParticipantState(e,r.participantState)}})}_onRemoteTrackRemoved(e,t,i){switch(o.debug(`[${e}] remote track (removed)`,{track:i}),i.kind){case se.audio:this._removeAudioTrack(e,t,i);break;case se.video:case se.screen:this._removeVideoTrack(e,t,i);break}}_removeAudioTrack(e,t,i){if(e!==ye.AUDIO_MIX){let r=this._participants[e];if(!r||r.remoteStream&&r.remoteStream!==t)return}this._audioOutput.remove(i)}_removeVideoTrack(e,t,i){}_onRemoteActivityNoSignal(){this._onRemoteSignalledStall([]),this._onRemoteAllStall(!1)}_onTopologyChanged(e){this._conversation&&(this._conversation.topology=e,this._changeFeatureSet())}_onRemoteAllStall(e){if(this._remoteAllStalled===e)return;this._remoteAllStalled=e;let t=[],i=[];for(let r in this._participants)if(this._participants.hasOwnProperty(r)){let n=this._participants[r];e||this._lastStalled[r]?t.push(n):i.push(n)}t.length&&this._setParticipantsStatus(t,q.RECONNECT),i.length&&this._setParticipantsStatus(i,q.CONNECTED)}_onRemoteSignalledStall(e){let t={},i=[],r=[];e.forEach(n=>{if(t[n]=!0,!this._lastStalled[n]){let s=this._participants[n];s&&!this._remoteAllStalled&&i.push(s)}delete this._lastStalled[n]}),Object.keys(this._lastStalled).forEach(n=>{let s=this._participants[n];s&&!this._remoteAllStalled&&r.push(s)}),i.length&&this._setParticipantsStatus(i,q.RECONNECT),r.length&&this._setParticipantsStatus(r,q.CONNECTED),this._lastStalled=t}_onRemoteDataStats(e){this._debugInfo&&this._debugInfo.onRemoteDataStats(e,this._participants),this._fixAudioDevice(e.outbound.rtps)}_fixAudioDevice(e){var t;!y.hasMicrophone()||!this._audioFix||!((t=this._mediaSource)==null?void 0:t.getMediaSettings().isAudioEnabled)||this._audioFix.fix(e)}_toggleJoinAvailability(){let e=this._conversation&&this._conversation.chatId,t=e&&this._state!=="CLOSE"||!1;e&&(o.debug("Toggle join availability",{available:t,chatId:e}),T.onJoinStatus(t,e))}_updateDisplayLayoutFromCache(e){return c(this,null,function*(){var i;if(((i=this._transport)==null?void 0:i.getTopology())!==Ee.SERVER)return;let t=this._participants[e];t&&t.lastRequestedLayouts&&Object.keys(t.lastRequestedLayouts).length&&(yield this.updateDisplayLayout(Object.values(t.lastRequestedLayouts)))})}_setParticipantsStatus(e,t,i=null){if(!e.length)return;let r=e.reduce((n,s)=>(s.status!==t&&(s.status=t,p.batchParticipantsOnStart?n.push(s.externalId):T.onParticipantStatus(s.externalId,t,i)),n),[]);!r.length||p.batchParticipantsOnStart&&T.onRemoteStatus(r,t,i)}},w=B;w._delayedHangup=!1;var Yt=class extends Error{constructor(e,t){super(e);Object.setPrototypeOf(this,Yt.prototype),this.participantErrors=t}};var zt;function mn(){return c(this,null,function*(){var a;if(p.apiEnv!=="AUTO")return p.apiEndpoint;try{let e=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),i=yield(yield fetch(e,{method:"GET",mode:"cors",cache:"no-cache"})).json(),r=(a=i==null?void 0:i.Answer[0])==null?void 0:a.data;if(!r)throw new Error("Wrong DNS response");return o.debug("Resolved API endpoint",r),r}catch(e){return o.warn("Failed to resolve API endpoint using DNS, default is used",e),p.apiEndpoint}})}function Yr(){if(!p.apiKey)throw new O(Z.API,{message:"Required argument apiAppKey not passed"})}function Li(a,e={},t=!1){if(!window.Blob||!window.navigator.sendBeacon)return;let i=Qr(a,e,t),r=new window.Blob([i],{type:"application/x-www-form-urlencoded"});window.navigator.sendBeacon(`${zt}/fb.do`,r)}function zr(i){return c(this,arguments,function*(a,e={},t=!1){zt||(zt=yield mn());let r=Qr(a,e,t);return hn(r)})}function hn(a){return c(this,null,function*(){return new Promise((e,t)=>{let i=new XMLHttpRequest;i.open("POST",`${zt}/fb.do`,!0),i.setRequestHeader("Content-type","application/x-www-form-urlencoded"),i.onreadystatechange=()=>{if(i.readyState!==XMLHttpRequest.DONE)return;let r;try{r=JSON.parse(i.responseText)}catch(n){r={result:i.responseText}}i.status!==200||r.hasOwnProperty("error_msg")?t(r):e(r)},i.send(a)})})}function Qr(a,e={},t=!1){e.method=a,e.format="JSON",e.application_key||(e.application_key=p.apiKey),t||(X.sessionKey?e.session_key=X.sessionKey:X.accessToken&&(e.access_token=X.accessToken));for(let[r,n]of Object.entries(e))typeof n=="object"&&(e[r]=JSON.stringify(n));let i="";for(let[r,n]of Object.entries(e))i&&(i+="&"),i+=`${r}=${encodeURIComponent(n)}`;return i}var gn=10,fn=700,Sn=3e3,bt=class extends Ze{constructor(){super(...arguments);this._userId=null;this._externalUidsCache={}}_callUnsafe(r){return c(this,arguments,function*(e,t={},i=!1){let n=s=>c(this,null,function*(){try{return yield zr(e,t,i)}catch(d){if(!d.hasOwnProperty("error_msg")&&(s++,o.debug(`${e} network error, attempt ${s}...`),s<gn))return yield E.delay(Math.min(s*fn,Sn)),n(s);throw o.warn(e,"error",d),d}});return n(0)})}_call(r){return c(this,arguments,function*(e,t={},i=!1){try{return yield this._callUnsafe(e,t,i)}catch(n){o.warn("Api call error",n);let s=Z.API;switch(n.error_code){case 102:case 103:case 104:return yield this.authorize(),this._callUnsafe(e,t,i);case 1101:s=M.SERVICE_DISABLED;break;case 1102:s=M.CALLEE_IS_OFFLINE;break;case 1103:s=M.NOT_FRIENDS;break;case 1104:case 1106:s=M.EXTERNAL_API_ERROR;break}throw new O(s,{message:n.error_msg,code:n.error_code})}})}userId(e){return c(this,null,function*(){let t=E.decomposeId(e).id;return X.isEmpty()?de.fromId(String(t)):(this._externalUidsCache.hasOwnProperty(t)||Object.assign(this._externalUidsCache,yield this._getExternalIdsByOkIds([t])),de.fromString(this._externalUidsCache[t]))})}prepareUserIds(e){return c(this,null,function*(){X.isEmpty()||Object.assign(this._externalUidsCache,yield this._getExternalIdsByOkIds(e))})}authorize(){return c(this,null,function*(){if(!this._uuid){let t=Ue.get("uuid");t||(t=E.uuid(),Ue.set("uuid",t)),this._uuid=String(t)}let e={session_data:{version:2,device_id:this._uuid,client_version:p.appVersion,client_type:"SDK_JS"}};return p.authToken&&(e.session_data.auth_token=p.authToken,e.session_data.version=3),this._callUnsafe("auth.anonymLogin",e,!0).then(t=>{t.uid&&(this._userId=Number(t.uid)),X.sessionKey=t.session_key,X.sessionSecretKey=t.session_secret_key}).catch(t=>{throw t.error_code===401&&T.onTokenExpired(),new O(Z.AUTH,{message:t.error_msg,code:t.error_code})})})}log(e){let t={collector:"ok.mobile.apps.video",data:JSON.stringify({application:`${p.appName}:${p.sdkVersion}`,platform:p.platform,items:e})};Li("log.externalLog",t)}init(){Yr()}joinConversation(e,t=!1,i){return c(this,null,function*(){let r={conversationId:e,isVideo:t,protocolVersion:p.protocolVersion};return i&&(r.chatId=i),this._call("vchat.joinConversation",r)})}createConversation(e,t="",i=!1){return c(this,null,function*(){let r={conversationId:e,createJoinLink:!0,isVideo:!1};return t&&(r.payload=t),p.domain&&(r.domainId=p.domain),i&&(r.requireAuthToJoin=!0),this._startConversation(r)})}startConversation(e,t,i,r=!1,n="",s=!1,d=!1){return c(this,null,function*(){let l={conversationId:e,isVideo:r};if(t&&t.length)switch(i){case De.USER:l.uids=t.join(",");break;case De.GROUP:l.gid=t[0];break;case De.CHAT:l.chatId=t[0];break}return s&&(l.createJoinLink=!0),n&&(l.payload=n),p.domain&&(l.domainId=p.domain),d&&(l.requireAuthToJoin=!0),this._startConversation(l)})}_startConversation(e){return c(this,null,function*(){return this._call("vchat.startConversation",e)})}createJoinLink(e){return c(this,null,function*(){return this._call("vchat.createJoinLink",{conversationId:e})})}removeJoinLink(e){return c(this,null,function*(){return this._call("vchat.removeJoinLink",{conversationId:e})})}getAnonymTokenByLink(e,t){return c(this,null,function*(){let i={joinLink:e};t&&(i.anonymName=t);let r=yield this._call("vchat.getAnonymTokenByLink",i);return this._userId=Number(r.uid),r.token})}joinConversationByLink(e,t=!1){return c(this,null,function*(){let i={joinLink:e,isVideo:t,protocolVersion:p.protocolVersion};return p.anonymToken&&(i.anonymToken=p.anonymToken),this._call("vchat.joinConversationByLink",i)})}getOkIdsByExternalIds(e){return c(this,null,function*(){let t=de.fromIds(e),i=[],r={methods:[]},n=[],s=Object.keys(this._externalUidsCache),d=Object.values(this._externalUidsCache);for(let h of t){let P=de.toString(h),b=d.indexOf(P);b>-1?i.push(Number(s[b])):(n.push(P),r.methods.push({"vchat.getOkIdByExternalId":{params:{externalId:h.id,anonym:h.type===Je.ANONYM},onError:"SKIP"}}))}return r.methods.length&&(yield this._call("batch.executeV2",r)).forEach((h,P)=>{if(h.ok){let b=Number(h.ok.ok_id);this._externalUidsCache[b]=n[P],i.push(b)}}),i})}getExternalIdsByOkIds(e){return c(this,null,function*(){let t=[],i=[];for(let n of e)this._externalUidsCache.hasOwnProperty(n)?t.push(de.fromString(this._externalUidsCache[n])):i.push(n);if(!i.length)return t;let r=yield this._getExternalIdsByOkIds(i);Object.assign(this._externalUidsCache,r);for(let n of i)r.hasOwnProperty(n)&&t.push(de.fromString(r[n]));return t})}getCachedOkIdByExternalId(e){let t=Object.keys(this._externalUidsCache),i=Object.values(this._externalUidsCache),r=de.toString(e),n=i.indexOf(r);return n>-1?E.composeUserId(t[n],Q.USER):null}cacheExternalId(e,t){let i=E.decomposeId(e).id;this._externalUidsCache[i]=de.toString(t)}getConversationParams(e){return c(this,null,function*(){let t={};return p.anonymToken&&(t.anonymToken=p.anonymToken),e&&(t.conversationId=e),this._call("vchat.getConversationParams",t)})}getUserId(){return this._userId}setUserId(e){this._userId=e}hangupConversation(e){let t={conversationId:e,reason:M.HUNGUP};p.anonymToken&&(t.anonymToken=p.anonymToken),Li("vchat.hangupConversation",t)}removeHistoryRecords(e){return c(this,null,function*(){yield this._call("vchat.removeHistoryRecords",{recordIds:e.join(",")})})}cleanup(){}_getExternalIdsByOkIds(e){return c(this,null,function*(){let t={};try{let i=yield this._call("vchat.getExternalIdsByOkIds",{uids:e.join(",")});if(i.external_ids)for(let[r,n]of Object.entries(i.external_ids))t[r]=de.fromIdToString(n,Je.USER);if(i.anonym_ids)for(let[r,n]of Object.entries(i.anonym_ids))t[r]=de.fromIdToString(n,Je.ANONYM);return t}catch(i){return t}})}getTokenForAnonym(e,t){return c(this,null,function*(){let i={id:e};return t&&(i.application_key=t),(yield this._callUnsafe("auth.getTokenForAnonym",i,!0)).token})}call(i){return c(this,arguments,function*(e,t={}){return this._call(e,t)})}};var Xr=(R=>(R.RECOVER="recover",R.ACCEPT_CALL="accept-call",R.ADD_PARTICIPANT="add-participant",R.REMOVE_PARTICIPANT="remove-participant",R.HANGUP="hangup",R.TRANSMIT_DATA="transmit-data",R.ACCEPT_PRODUCER="accept-producer",R.ALLOCATE_CONSUMER="allocate-consumer",R.CHANGE_MEDIA_SETTINGS="change-media-settings",R.CHANGE_PARTICIPANT_STATE="change-participant-state",R.CHANGE_STREAM_PRIORITIES="change-streams-priorities",R.UPDATE_DISPLAY_LAYOUT="update-display-layout",R.REPORT_PERF_STAT="report-perf-stat",R.RECORD_START="record-start",R.RECORD_STOP="record-stop",R.RECORD_SET_ROLE="record-set-role",R.RECORD_GET_STATUS="record-get-status",R.SWITCH_MICRO="switch-micro",R.SWITCH_TOPOLOGY="switch-topology",R.REQUEST_REALLOC="request-realloc",R.CHAT_MESSAGE="chat-message",R.CHAT_HISTORY="chat-history",R.CUSTOM_DATA="custom-data",R.GRANT_ROLES="grant-roles",R.MUTE_PARTICIPANT="mute-participant",R.PIN_PARTICIPANT="pin-participant",R.UPDATE_MEDIA_MODIFIERS="update-media-modifiers",R.CHANGE_OPTIONS="change-options",R.GET_WAITING_HALL="get-waiting-hall",R.PROMOTE_PARTICIPANT="promote-participant",R.REQUEST_TEST_MODE="request-test-mode",R.ADD_MOVIE="add-movie",R.UPDATE_MOVIE="update-movie",R.REMOVE_MOVIE="remove-movie",R))(Xr||{}),H=Xr;var Zr="open",ea=[()=>p.producerScreenTrack,()=>p.videoTracksCount>0,()=>!0,()=>p.filteredMessages,()=>p.consumerScreenTrack,()=>!0,()=>p.movieShare],vn=10,Ie=class extends tt{constructor(){super(...arguments);this.socket=null;this.sequence=1;this.lastStamp=0;this.websocketCommandsQueue=[];this.datachannelCommandsQueue=[];this.incomingCache=[];this.responseHandlers={};this.reconnectCount=0;this.conversationResolve=null;this.conversationReject=null;this.connected=!1;this.listenersReady=!1;this.postfix="&platform="+p.platform+"&appVersion="+p.appVersion+"&version="+p.protocolVersion+"&device="+p.device+"&capabilities="+Ie._getCapabilityFlags();this.peerId=null;this.conversationId=null;this.reconnectTimer=0;this.connectionMessageWaitTimer=0;this.doctorTimer=0;this.participantIdRegistry=null;this.producerNotificationDataChannel=null;this.producerCommandDataChannel=null}static _getCapabilityFlags(){let e=0;for(let t=0;t<ea.length;t++)ea[t]()&&(e|=1<<t);return e.toString(16).toUpperCase()}get ready(){return this.socket!==null}setEndpoint(e){this.endpoint=e}setConversationId(e){this.conversationId=e}setParticipantIdRegistry(e){this.participantIdRegistry=e}setProducerNotificationDataChannel(e){this.producerNotificationDataChannel=e,this.producerNotificationDataChannel.onmessage=t=>{var r;let i=(r=this.participantIdRegistry)==null?void 0:r.handleMessage(t.data);i&&this._handleMessage(i)}}setProducerCommandDataChannel(e){this.producerCommandDataChannel=e,this.producerCommandDataChannel.onmessage=this._onMessage.bind(this),this._handleCommandsQueue(this.datachannelCommandsQueue)}cleanup(){this.datachannelCommandsQueue=[]}connect(e){return c(this,null,function*(){return this.postfix+=`&clientType=${p.clientType}`,new Promise((t,i)=>{if(this.socket&&this.socket.readyState<WebSocket.CLOSING){m.log(g.SOCKET_ACTION,"already_opened"),i(Error("Socket already opened"));return}this.conversationResolve=r=>{t(r),this.conversationResolve=null,this.conversationReject=null},this.conversationReject=r=>{i(r),this.conversationResolve=null,this.conversationReject=null},this._connect(e)})})}_send(r){return c(this,arguments,function*(e,t={},i=0){if(t.participantId){let n=E.decomposeParticipantId(t.participantId),s=E.decomposeId(n.compositeUserId);t=Object.assign({},t,{participantId:s.id,participantType:s.type}),n.deviceIdx&&(t.deviceIdx=n.deviceIdx)}return this._sendRaw(e,t,i)})}_sendRaw(r){return c(this,arguments,function*(e,t={},i=0){let n=s=>{var l;if(this._isDataChannelCommand(e))this.datachannelCommandsQueue.push(s),((l=this.producerCommandDataChannel)==null?void 0:l.readyState)===Zr&&this._handleCommandsQueue(this.datachannelCommandsQueue);else{if(!this.socket){m.log(g.SOCKET_ACTION,"not_opened"),o.warn("Socket not opened"),s.reject(new Error(`Socket not opened [${e}]`),!0);return}this.socket.readyState>WebSocket.OPEN&&(m.log(g.SOCKET_ACTION,"invalid_state"),o.warn(`Socket is not opened, state ${this.socket.readyState}`)),this.websocketCommandsQueue.push(s),this.socket&&this.socket.readyState===WebSocket.OPEN&&this._handleCommandsQueue(this.websocketCommandsQueue)}};return new Promise((s,d)=>{let l=(P,b=!1)=>{!i||b?d(P):(o.debug("Resending a signaling message",e,h.sequence),i--,n(h))},h={sequence:this.sequence++,name:e,params:t,responseTimer:0,resolve:s,reject:l};n(h)})})}_isDataChannelCommand(e){return this.producerCommandDataChannel?e===H.UPDATE_DISPLAY_LAYOUT||e===H.REPORT_PERF_STAT:!1}static _isDataChannelResponseRequired(e){return e===H.UPDATE_DISPLAY_LAYOUT||e===H.REPORT_PERF_STAT}getNextCommandSequenceNumber(){return this.sequence}hangup(e){return c(this,null,function*(){return this._send(H.HANGUP,{reason:e}).catch(()=>{})})}sendCandidate(e,t){return c(this,null,function*(){return this._send(H.TRANSMIT_DATA,{participantId:e,data:{candidate:t}})})}requestTestMode(e){return c(this,null,function*(){return this._send(H.REQUEST_TEST_MODE,{consumerCommand:e})})}sendSdp(e,t){return c(this,null,function*(){return this._send(H.TRANSMIT_DATA,{participantId:e,data:{sdp:t}})})}acceptCall(e){return c(this,null,function*(){return this._send(H.ACCEPT_CALL,{mediaSettings:e})})}changeMediaSettings(e){return c(this,null,function*(){return this._send(H.CHANGE_MEDIA_SETTINGS,{mediaSettings:e},vn)})}changeParticipantState(e){return c(this,null,function*(){return this._send(H.CHANGE_PARTICIPANT_STATE,{participantState:{state:e}})})}addParticipant(e,t){return c(this,null,function*(){return this._send(H.ADD_PARTICIPANT,$i({participantId:e},t))})}removeParticipant(e,t=!1){return c(this,null,function*(){return this._send(H.REMOVE_PARTICIPANT,{participantId:e,ban:t})})}allocateConsumer(e,t){return c(this,null,function*(){let i={capabilities:t};return e&&(i.description=e.sdp),this._send(H.ALLOCATE_CONSUMER,i)})}acceptProducer(e,t){return c(this,null,function*(){let i={description:e.sdp};return t&&(i.ssrcs=t),this._send(H.ACCEPT_PRODUCER,i)})}changePriorities(e){return c(this,null,function*(){return this._send(H.CHANGE_STREAM_PRIORITIES,{typedPriorities:e}).catch(()=>{})})}updateDisplayLayout(e){return c(this,null,function*(){return this._send(H.UPDATE_DISPLAY_LAYOUT,{layouts:e})})}addMovie(e){return c(this,null,function*(){return this._send(H.ADD_MOVIE,e)})}updateMovie(e){return c(this,null,function*(){return this._send(H.UPDATE_MOVIE,e)})}removeMovie(e){return c(this,null,function*(){return this._send(H.REMOVE_MOVIE,e)})}startStream(e){return c(this,null,function*(){return this._send(H.RECORD_START,e)})}stopStream(){return c(this,null,function*(){return this._send(H.RECORD_STOP)})}recordSetRole(e,t){return c(this,null,function*(){return this._send(H.RECORD_SET_ROLE,{participantId:e,role:t})})}getRecordStatus(){return c(this,null,function*(){return this._send(H.RECORD_GET_STATUS)})}switchTopology(e,t=!1){return c(this,null,function*(){return this._send(H.SWITCH_TOPOLOGY,{topology:e,force:t})})}requestRealloc(){return c(this,null,function*(){return this._send(H.REQUEST_REALLOC)})}reportPerfStat(e){return c(this,null,function*(){return this._send(H.REPORT_PERF_STAT,{report:e})})}chatMessage(e,t=null){return c(this,null,function*(){return this._send(H.CHAT_MESSAGE,{message:e,participantId:t})})}chatHistory(e){return c(this,null,function*(){return this._send(H.CHAT_HISTORY,{count:e})})}customData(e,t){return c(this,null,function*(){return this._send(H.CUSTOM_DATA,{data:e,participantId:t})})}grantRoles(e,t,i){return c(this,null,function*(){let r={participantId:e,roles:t};return i&&(r.revoke=!0),this._sendRaw(H.GRANT_ROLES,r)})}muteParticipant(e,t,i){return c(this,null,function*(){return this._sendRaw(H.MUTE_PARTICIPANT,{participantId:e,muteStates:t,requestedMedia:i})})}pinParticipant(e,t){return c(this,null,function*(){let i={participantId:e};return t&&(i.unpin=!0),this._sendRaw(H.PIN_PARTICIPANT,i)})}updateMediaModifiers(e){return c(this,null,function*(){return this._send(H.UPDATE_MEDIA_MODIFIERS,{mediaModifiers:e})})}changeOptions(e){return c(this,null,function*(){return this._send(H.CHANGE_OPTIONS,{options:e})})}getWaitingHall(e=null,t,i=!1){return c(this,null,function*(){let r={};return e&&(r.fromId=e),t&&(r.count=t),i&&(r.backward=i),this._send(H.GET_WAITING_HALL,r)})}promoteParticipant(e,t=!1){return c(this,null,function*(){let i={participantId:e};return t&&(i.demote=t),this._sendRaw(H.PROMOTE_PARTICIPANT,i)})}close(){this.socket&&this.socket.readyState<WebSocket.CLOSING&&this._closeSocket(),this._stopWaitConnectionMessage(),this._stopDoctor(),clearTimeout(this.reconnectTimer)}readyToSend(){this.listenersReady=!0,this._handleCachedMessages()}_connect(e){if(this.socket&&this.socket.readyState<WebSocket.CLOSING)return;let t="";e&&(t+=`&tgt=${e}`),e===Ae.RETRY&&this.lastStamp&&(t+=`&recoverTs=${this.lastStamp}`),o.debug("Connecting to "+this.endpoint+this.postfix+t),this.socket=new WebSocket(this.endpoint+this.postfix+t),this.socket.onopen=this._onOpen.bind(this),this.socket.onmessage=this._onMessage.bind(this),this.socket.onerror=this._onError.bind(this),this.socket.onclose=this._onClose.bind(this),this._startDoctor()}_disconnect(){this.socket&&this.socket.readyState<WebSocket.CLOSING&&(this.socket.onopen=null,this.socket.onmessage=null,this.socket.onerror=null,this.socket.onclose=null,this.socket.close(),this.socket=null),this._stopWaitConnectionMessage(),this._stopDoctor(),clearTimeout(this.reconnectTimer)}_onOpen(){o.debug("Socket opened"),m.log(g.SOCKET_ACTION,"opened"),this._waitConnectionMessage(),this._startDoctor()}_onMessage(e){if(this._startDoctor(),e.data==="ping"){this.socket&&this.socket.readyState===WebSocket.OPEN&&this.socket.send("pong");return}try{this._handleMessage(JSON.parse(e.data))}catch(t){m.log(g.SOCKET_ACTION,"parse_error"),o.error("Unable to parse message",t,e.data)}}_handleMessage(e){var t;e.type==="notification"?e.notification==="connection"?(o.debug("Signaling connected",e),this.connected=!0,this.reconnectCount=0,this.endpoint=e.endpoint,e.peerId&&this.peerId!==e.peerId.id&&(this.postfix+=`&peerId=${e.peerId.id}`,this.peerId=e.peerId.id),this._stopWaitConnectionMessage(),this.conversationResolve?this.conversationResolve(e):(this._triggerEvent(ue.RECONNECT,e),e.conversation.topology&&this._triggerEvent(ue.NOTIFICATION,{type:"notification",notification:A.TOPOLOGY_CHANGED,topology:e.conversation.topology})),this.lastStamp&&this._handleCachedMessages(),(t=e.recoverMessages)==null||t.forEach(i=>this._handleMessage(i)),this._handleCommandsQueue(this.websocketCommandsQueue)):!this.connected||!this.listenersReady?this.incomingCache.push(e):this._triggerEvent(ue.NOTIFICATION,e):e.type==="response"&&this.responseHandlers[e.sequence]?this._handleCommandResponse(!0,e):e.type==="error"&&this.responseHandlers[e.sequence]?(m.log(g.SOCKET_ACTION,`error-${e.error}`),this._handleCommandResponse(!1,e)):e.type==="error"?(m.log(g.SOCKET_ACTION,`error-${e.error}`),e.error==="service-unavailable"?this._reconnect():e.error==="conversation-ended"?this.conversationReject?this.conversationReject(new O(M.SOCKET_CLOSED,{message:`Unable to connect to the signaling: ${e.error}`})):this._triggerEvent(ue.NOTIFICATION,{notification:A.CLOSED_CONVERSATION,reason:e.reason}):this.connected||e.error==="invalid-token"?this._throwError(new Error(`Signaling error: ${e.error}`)):e.sequence||(this.conversationReject&&this.conversationReject(new O(Z.SIGNALING_FAILED,{message:`Unable to connect to the signaling: ${e.error}`})),this._closeSocket())):(m.log(g.SOCKET_ACTION,"unknown_message"),o.warn("Unhandled message",e)),this.lastStamp=e.stamp||this.lastStamp}_handleCachedMessages(){let e=[...this.incomingCache];for(this.incomingCache=[];e.length>0;){let t=e.shift();this._handleMessage(t)}}_throwError(e){this._triggerEvent(ue.FAILED,e)}_onError(e){m.log(g.SOCKET_ACTION,"error"),o.error("Signaling error",e)}_onClose(e){m.log(g.SOCKET_ACTION,"closed"),o.debug("Connection closed",{code:e.code,reason:e.reason}),this.connected=!1,this._stopDoctor(),this.socket&&this.reconnectCount++<Ie.RECONNECT_MAX_COUNT?this._reconnect():this.socket&&this._closeSocket(new Error("Connection closed"))}_closeSocket(e=null){!this.socket||(this._disconnect(),Object.values(this.responseHandlers).forEach(t=>{window.clearTimeout(t.responseTimer),e&&t.reject(new Error("Connection closed"),!0)}),this.websocketCommandsQueue=[],this.responseHandlers={},this.lastStamp=0,e&&this._throwError(new Error("Connection closed")))}_reconnect(){let e=Math.min(Ie.RECONNECT_MAX_DELAY,Ie.RECONNECT_DELAY*Math.pow(2,this.reconnectCount-1));o.log(`Reconnect websocket after ${e}ms (${this.reconnectCount})`),m.log(g.SOCKET_ACTION,"reconnect"),this.reconnectTimer=window.setTimeout(this._connect.bind(this,Ae.RETRY),e)}_handleCommandResponse(e,t){var r;if(!this.responseHandlers.hasOwnProperty(t.sequence))return;let i=this.responseHandlers[t.sequence];window.clearTimeout(i.responseTimer),e?(delete this.responseHandlers[t.sequence],i.resolve(t)):((r=this.socket)==null?void 0:r.readyState)===WebSocket.OPEN?(delete this.responseHandlers[t.sequence],m.log(g.SOCKET_ACTION,"response-timeout"),i.reject(new Error(t.error||`Response timeout [${i.name}]`))):i.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,t),Ie.WAIT_RESPONSE_DELAY)}_handleCommandsQueue(e){var t,i;for(;e.length>0;){let r=e.shift(),n=Object.assign({command:r.name,sequence:r.sequence},r.params);if(this._isDataChannelCommand(r.name)){if(((t=this.producerCommandDataChannel)==null?void 0:t.readyState)!==Zr){r.reject(new Error(`Invalid data channel state: ${(i=this.producerCommandDataChannel)==null?void 0:i.readyState}`));return}Ie._isDataChannelResponseRequired(r.name)&&(r.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,n),Ie.WAIT_RESPONSE_DELAY),this.responseHandlers[r.sequence]=r),this.producerCommandDataChannel.send(JSON.stringify(n))}else{if(!this.socket||this.socket.readyState!==WebSocket.OPEN){r.reject(new Error("Invalid state or socket already closed"));continue}r.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,n),Ie.WAIT_RESPONSE_DELAY),this.responseHandlers[r.sequence]=r,this.socket.send(JSON.stringify(n))}}}_waitConnectionMessage(){this.connectionMessageWaitTimer=window.setTimeout(()=>{this.conversationReject&&this.conversationReject(new O(Z.SIGNALING_FAILED,{message:"Unable to connect to the signaling: connection timeout"}))},Ie.WAIT_CONNECTION_DELAY)}_stopWaitConnectionMessage(){window.clearTimeout(this.connectionMessageWaitTimer),this.connectionMessageWaitTimer=0}_startDoctor(){this._stopDoctor(),this.doctorTimer=window.setTimeout(()=>{o.warn("Socket is dead, trying to reconnect"),this._disconnect(),this._connect(Ae.RETRY)},Ie.WAIT_MESSAGE_DELAY)}_stopDoctor(){window.clearTimeout(this.doctorTimer),this.doctorTimer=0}},Pe=Ie;Pe.RECONNECT_DELAY=p.signalingReconnectDelay,Pe.RECONNECT_MAX_DELAY=p.signalingReconnectMaxDelay,Pe.RECONNECT_MAX_COUNT=p.signalingReconnectMaxCount,Pe.WAIT_CONNECTION_DELAY=p.waitConnectionDelay,Pe.WAIT_RESPONSE_DELAY=p.waitResponseDelay,Pe.WAIT_MESSAGE_DELAY=p.waitMessageDelay;var ta=(t=>(t.KING="KING",t.PAWN="PAWN",t))(ta||{}),ia=ta;var lt,ee,Mt=null,En={getCameras:y.getCameras,getMicrophones:y.getMicrophones,getOutput:y.getOutput,hasCamera:y.hasCamera,hasMicrophone:y.hasMicrophone,getSavedCamera:y.getSavedCamera,getSavedMicrophone:y.getSavedMicrophone,getSavedOutput:y.getSavedOutput,hasCameraPermission:y.hasCameraPermission,hasMicrophonePermission:y.hasMicrophonePermission,hasPermissions:y.hasPermissions,getUserMedia:y.getUserMedia,getUserVideo:y.getUserVideo,getUserAudio:y.getUserAudio,saveDeviceId:y.saveDeviceId,isBrowserSupported:y.isBrowserSupported,isScreenCapturingSupported:y.isScreenCapturingSupported,os:y.os,isMobile:y.isMobile,browserName:y.browserName,browserVersion:y.browserVersion,baseChromeVersion:y.baseChromeVersion,getAudioContext:y.getAudioContext};function ra(a){ee=a}function aa(a){lt=a}function Tn(a){Mt=a}function In(a){p.videoEffects=a}function Cn(a){return c(this,null,function*(){if(p.set(a),y.browserName()==="Sferum"&&(p.platform=`SFERUM:${y.browserVersion()}`),ee||ra(new bt),lt||aa(()=>new Pe),p.debug&&(Ui.default.disableLog(!1),o.toggle(!0)),o.log(`Calls SDK ${p.sdkVersion}`,a),yield y.init(),!y.isBrowserSupported())throw new O(Z.UNSUPPORTED);ee.init()})}function yn(n){return c(this,arguments,function*(a,e=[re.AUDIO],t="",i=!1,r=!1){let s=[],d=[];if(Array.isArray(a)?s=a.length?a:[]:a&&(s=[a]),s.length&&(d=yield ee.getOkIdsByExternalIds(s),!d.length))throw new O(M.CALLEE_IS_OFFLINE);return na(d,De.USER,e,t,i,r)})}function na(s){return c(this,arguments,function*(a,e=De.USER,t,i="",r=!1,n=!1){if(w.current())throw o.error("There is already active call"),new O(M.FAILED);return new w(ee,lt(),Mt).onStart(a,e,t,i,r,n)})}function Rn(a){return c(this,null,function*(){return sa(a)})}function sa(i){return c(this,arguments,function*(a,e=Q.USER,t){if(a===w.id())throw new Error("Push has already been processed");return new w(ee,lt(),Mt).onPush(a,e,t)})}function Pn(a,e){return c(this,null,function*(){return ee.getTokenForAnonym(a,e)})}function bn(t){return c(this,arguments,function*(a,e={}){return ee.call(a,e)})}function Mn(a){return c(this,null,function*(){return a&&(p.authToken=a),ee.authorize()})}function Dn(){return c(this,arguments,function*(a=[re.AUDIO]){let e=w.current();if(e)return e.accept(a);throw new Error("Conversation not found")})}function An(){return c(this,null,function*(){let a=w.current();if(a)return a.decline()})}function On(t){return c(this,arguments,function*(a,e=[re.AUDIO]){return oa(a,e)})}function oa(a,e,t){return c(this,null,function*(){if(w.current())throw o.error("There is already active call"),new O(M.FAILED);return new w(ee,lt(),Mt).onJoin({conversationId:a,mediaOptions:e,chatId:t})})}function kn(i){return c(this,arguments,function*(a,e=[re.AUDIO],t){if(w.current())throw o.error("There is already active call"),new O(M.FAILED);return t&&(p.anonymToken=t),new w(ee,lt(),Mt).onJoin({joinLink:a,mediaOptions:e})})}function wn(){return c(this,null,function*(){let a=w.current();if(a)return a.hangup();w.hangupAfterInit()})}function Nn(a,e){return c(this,null,function*(){let t=yield ee.getOkIdsByExternalIds([a]);if(!t.length)throw new Error("User not found");return ca(t[0],e)})}function ca(a,e){return c(this,null,function*(){let t=w.current();t&&(yield t.addParticipant(E.composeUserId(a,Q.USER),e))})}function xn(a,e=!1){return c(this,null,function*(){let t=yield ee.getOkIdsByExternalIds([a]);return da(t[0],e)})}function da(a,e=!1){return c(this,null,function*(){let t=w.current();t&&(yield t.removeParticipant(E.composeUserId(a,Q.USER),e))})}function Ln(a,e){return c(this,null,function*(){let t=yield y.saveDeviceId(a,e),i=w.current();return t&&i?i.changeDevice(a):Promise.reject()})}function Un(a){return c(this,null,function*(){let e=w.current();return e?e.toggleScreenCapturing(a):Promise.reject()})}function Bn(a,e=!1){return c(this,null,function*(){let t=w.current();t&&(yield t.setVideoStream(a,e))})}function Vn(a){return c(this,null,function*(){let e=w.current();e&&(yield e.toggleLocalVideo(a))})}function Fn(a){return c(this,null,function*(){let e=w.current();e&&(yield e.toggleLocalAudio(a))})}function Hn(a,e,t){return c(this,null,function*(){let i=w.current();if(i)return i.setLocalResolution(a,e,t)})}function Gn(a){return c(this,null,function*(){let e=w.current();e&&(yield e.changePriorities(a))})}function Wn(a){return c(this,null,function*(){let e=w.current();e&&(yield e.changeParticipantState(a))})}function jn(a){return c(this,null,function*(){let e=w.current();e&&(yield e.updateDisplayLayout(a))})}function Kn(a,e,t=!1){return c(this,null,function*(){let i=yield ee.getOkIdsByExternalIds([a]);return pa(i[0],e,t)})}function pa(a,e,t=!1){return c(this,null,function*(){let i=w.current();i&&(yield i.grantRoles(E.composeUserId(a,Q.USER),e,t))})}function $n(){return c(this,arguments,function*(a=null,e,t=[]){let i=null;return a&&(i=(yield ee.getOkIdsByExternalIds([a]))[0]),la(i,e,t,pe.getDeviceIdx(a))})}function la(){return c(this,arguments,function*(a=null,e,t=[],i=0){let r=w.current();if(r){let n=a?E.composeParticipantId(a,Q.USER,i):null;yield r.muteParticipant(n,e,t)}})}function qn(a,e=!1){return c(this,null,function*(){let t=yield ee.getOkIdsByExternalIds([a]);return ua(t[0],e,pe.getDeviceIdx(a))})}function ua(a,e=!1,t=0){return c(this,null,function*(){let i=w.current();i&&(yield i.pinParticipant(E.composeParticipantId(a,Q.USER,t),e))})}function Jn(a){return c(this,null,function*(){let e=w.current();e&&(yield e.updateMediaModifiers(a))})}function Yn(a){return c(this,null,function*(){let e=w.current();e&&(yield e.changeOptions(a))})}function zn(a,e=null){return c(this,null,function*(){let t=null;return e&&(t=(yield ee.getOkIdsByExternalIds([e]))[0]),ma(a,t)})}function ma(a,e=null){return c(this,null,function*(){let t=w.current();if(t){let i=e?E.composeUserId(e,Q.USER):null;yield t.chatMessage(a,i)}})}function Qn(a=10){return c(this,null,function*(){let e=w.current();if(e)return e.chatHistory(a)})}function Xn(a,e=null){return c(this,null,function*(){let t=null;return e&&(t=(yield ee.getOkIdsByExternalIds([e]))[0]),ha(a,t,pe.getDeviceIdx(e))})}function ha(a,e=null,t=0){return c(this,null,function*(){let i=w.current();if(i){let r=e?E.composeParticipantId(e,Q.USER,t):null;yield i.customData(a,r)}})}function Zn(a="",e=!1){return c(this,null,function*(){return(yield ee.createConversation(E.uuid(),a,e)).join_link})}function es(){return c(this,null,function*(){let a=w.current();return a?a.createJoinLink():Promise.reject()})}function ts(){return c(this,null,function*(){let a=w.current();return a?a.removeJoinLink():Promise.reject()})}function is(a,e){return c(this,null,function*(){return ee.getAnonymTokenByLink(a,e)})}function rs(a){let e=w.current();e&&e.setVolume(a)}function as(a){p.forceRelayPolicy=a}function ns(a=!1,e=null,t=null,i="DIRECT_LINK",r=null){return c(this,null,function*(){let n=w.current();return n?n.startStream(a,e,t,i,r):Promise.reject()})}function ss(){return c(this,null,function*(){let a=w.current();return a?a.stopStream():Promise.reject()})}function os(a,e){return c(this,null,function*(){let t=w.current();if(t){let i=yield ee.getOkIdsByExternalIds([a]),r=pe.getDeviceIdx(a);return t.recordSetRole(E.composeParticipantId(i[0],Q.USER,r),e)}return Promise.reject()})}function cs(){return c(this,null,function*(){let a=w.current();return a?a.getStreamInfo():Promise.reject()})}function ds(a){return c(this,null,function*(){let e=w.current();return e?e.addMovie(a):Promise.reject()})}function ps(a,e,t,i){return c(this,null,function*(){let r=w.current();return r?r.updateMovie(a,e,t,i):Promise.reject()})}function ls(a){return c(this,null,function*(){let e=w.current();return e?e.removeMovie(a):Promise.reject()})}function us(a){p.statisticsInterval=a;let e=w.current();if(e)return e.updateStatisticsInterval()}function ms(a){Ui.default.disableLog(!a),o.toggle(a)}function hs(a,...e){!p.debugLog||o.send(a,"[external]",...e)}function _s(a){return c(this,null,function*(){let e=w.current();if(e)return e.videoEffect(a)})}function gs(a){return c(this,null,function*(){let e=w.current();e&&(yield e.setAudioStream(a))})}function fs(a=null,e,t=!1){return c(this,null,function*(){let i=w.current();if(!i)throw new Error("Conversation not found");return i.getWaitingHall(a,e,t)})}function Ss(a,e=!1){return c(this,null,function*(){let t=w.current();if(!t)throw new Error("Conversation not found");let i=yield ee.getOkIdsByExternalIds([a]);return t.promoteParticipant(E.composeUserId(i[0],Q.USER),e)})}function vs(a){return c(this,null,function*(){yield ee.removeHistoryRecords(a)})}