@vinay.kumar.ha/videosdk-ui-toolkit 2.3.5-1.5 → 2.3.5-1.7

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 (54) hide show
  1. package/dist/lib/annoter.min.js +3 -0
  2. package/dist/lib/audio.encode.wasm +0 -0
  3. package/dist/lib/audio.light.simd.wasm +0 -0
  4. package/dist/lib/audio.simd.wasm +0 -0
  5. package/dist/lib/audio_light_simd.min.js +2 -0
  6. package/dist/lib/audio_simd.min.js +2 -0
  7. package/dist/lib/graphics.min.js +2 -0
  8. package/dist/lib/js_audio_level_worklet_process.min.js +2 -0
  9. package/dist/lib/js_audio_level_worklet_process_light.min.js +2 -0
  10. package/dist/lib/js_audio_process.min.js +2 -0
  11. package/dist/lib/js_audio_processor_worklet.min.js +2 -0
  12. package/dist/lib/js_audio_worklet.min.js +2 -0
  13. package/dist/lib/js_audio_worklet_light_simd.min.js +2 -0
  14. package/dist/lib/js_audio_worklet_process.min.js +2 -0
  15. package/dist/lib/js_audio_worklet_simd.min.js +2 -0
  16. package/dist/lib/js_media.min.js +3 -0
  17. package/dist/lib/js_sharing_audio_worklet.min.js +2 -0
  18. package/dist/lib/manifest.json +338 -0
  19. package/dist/lib/mesh_thread.min.js +2 -0
  20. package/dist/lib/net.wasm +0 -0
  21. package/dist/lib/net_thread.min.js +2 -0
  22. package/dist/lib/pako.min.js +2 -0
  23. package/dist/lib/qrscanner.min.js +2 -0
  24. package/dist/lib/share_processor.min.js +2 -0
  25. package/dist/lib/sharing_m.min.js +3 -0
  26. package/dist/lib/sharing_mtsimd.min.js +3 -0
  27. package/dist/lib/sharing_s.min.js +2 -0
  28. package/dist/lib/sharing_simd.min.js +2 -0
  29. package/dist/lib/tp.min.js +2 -0
  30. package/dist/lib/tp.wasm +0 -0
  31. package/dist/lib/vb-resource/dualModel.bin +0 -0
  32. package/dist/lib/vb-resource/tf.min.js +18 -0
  33. package/dist/lib/vb.min.js +2 -0
  34. package/dist/lib/vb_worker.min.js +2 -0
  35. package/dist/lib/video.decode.js +1 -0
  36. package/dist/lib/video.decode.wasm +0 -0
  37. package/dist/lib/video.mt.js +1 -0
  38. package/dist/lib/video.mt.wasm +0 -0
  39. package/dist/lib/video.mtsimd.js +1 -0
  40. package/dist/lib/video.mtsimd.wasm +0 -0
  41. package/dist/lib/video.simd.js +1 -0
  42. package/dist/lib/video.simd.wasm +0 -0
  43. package/dist/lib/video_m.min.js +3 -0
  44. package/dist/lib/video_mtsimd.min.js +3 -0
  45. package/dist/lib/video_processor.min.js +2 -0
  46. package/dist/lib/video_s.min.js +2 -0
  47. package/dist/lib/video_share_mtsimd.min.js +3 -0
  48. package/dist/lib/video_simd.min.js +2 -0
  49. package/dist/lib/wasm_ssrc_stream_service_dynmod.min.js +2 -0
  50. package/dist/lib/webgpu_renderer_dynmod.min.js +2 -0
  51. package/dist/lib/wmsc.min.js +2 -0
  52. package/dist/videosdk-ui-toolkit.min.esm.js +1832 -1832
  53. package/dist/videosdk-ui-toolkit.min.umd.js +82 -82
  54. package/package.json +1 -1
@@ -0,0 +1,2 @@
1
+ (self.__MEDIA_SDK_CHUNK_LOADER__=self.__MEDIA_SDK_CHUNK_LOADER__||[]).push([[557],{7378:(e,t,i)=>{"use strict";i.r(t),i.d(t,{WMSCManager:()=>Ei,eventExt:()=>F});var s={};i.r(s),i.d(s,{TO:()=>I,NS:()=>b,mz:()=>A,GA:()=>R,FK:()=>_,pO:()=>S,fZ:()=>v,Rz:()=>D,r3:()=>w,By:()=>L,ey:()=>y,rF:()=>T,wK:()=>g,LA:()=>B,tT:()=>V,ul:()=>u,j$:()=>m,Y7:()=>p,RJ:()=>l,bl:()=>M,Dz:()=>O,c$:()=>P,lN:()=>C,zk:()=>N,nd:()=>o,ue:()=>k,pg:()=>f,S$:()=>E,tP:()=>a,qe:()=>U});var a,n,o,r,c=i(7857),d=i(129),h=i.n(d);!function(e){e[e.ERROR=0]="ERROR",e[e.WARN=1]="WARN",e[e.INFO=2]="INFO",e[e.DEBUG=3]="DEBUG",e[e.VERBOSE=4]="VERBOSE"}(a||(a={})),function(e){e[e._90P=0]="_90P",e[e._180P=1]="_180P",e[e._360P=2]="_360P",e[e._720P=3]="_720P",e[e._1080P=4]="_1080P",e[e._2160P=5]="_2160P"}(n||(n={})),function(e){e[e.AUDIO=1]="AUDIO",e[e.VIDEO=2]="VIDEO",e[e.SHARE=3]="SHARE"}(o||(o={})),function(e){e[e.VIDEO=1]="VIDEO",e[e.AUDIO=2]="AUDIO",e[e.SHARE=3]="SHARE"}(r||(r={}));const l=0;var u;!function(e){e[e.IDLE=0]="IDLE",e[e.CONNECTING=1]="CONNECTING",e[e.CONNECTED=2]="CONNECTED"}(u||(u={}));const m=6e3,p=2e3,g=1e4,S=3,_=3,v=3,f=15e3;var y,M,C;!function(e){e.STREAM="STREAM",e.SDP="SDP",e.PC_STATE_CHANGE="PC_STATE_CHANGE",e.UPDATE_BITRATE="UPDATE_BITRATE",e.ERROR="ERROR"}(y||(y={})),function(e){e.LAYERS_UPDATE="LAYERS_UPDATE",e.MIN_BITRATE_UPDATE="MIN_BITRATE_UPDATE",e.ENCODER_RESET="ENCODER_RESET"}(M||(M={})),function(e){e[e.NONE=0]="NONE",e[e.UNDERUSING=1]="UNDERUSING",e[e.NORMAL=2]="NORMAL",e[e.OVERUSING=3]="OVERUSING"}(C||(C={}));const I=1;var E;!function(e){e[e.PLAIN=0]="PLAIN",e[e.GZIP_BASE64=1]="GZIP_BASE64"}(E||(E={}));const T=2,R=100,A=62464,b=17120,w=26,D=w+1,L=16,O=299,P=6;var V,B,N,k;!function(e){e[e.NET_QUALITY_UNKNOWN=-1]="NET_QUALITY_UNKNOWN",e[e.NET_QUALITY_VERY_BAD=0]="NET_QUALITY_VERY_BAD",e[e.NET_QUALITY_BAD=1]="NET_QUALITY_BAD",e[e.NET_QUALITY_NOT_GOOD=2]="NET_QUALITY_NOT_GOOD",e[e.NET_QUALITY_NORMAL=3]="NET_QUALITY_NORMAL",e[e.NET_QUALITY_GOOD=4]="NET_QUALITY_GOOD",e[e.NET_QUALITY_EXCELLENT=5]="NET_QUALITY_EXCELLENT"}(V||(V={})),function(e){e[e.NET_BW_LEVEL_UNKNOWN=-1]="NET_BW_LEVEL_UNKNOWN",e[e.NET_BW_LEVEL_VERY_LOW=0]="NET_BW_LEVEL_VERY_LOW",e[e.NET_BW_LEVEL_LOW=1]="NET_BW_LEVEL_LOW",e[e.NET_BW_LEVEL_NORMAL=2]="NET_BW_LEVEL_NORMAL"}(B||(B={})),function(e){e[e.ICE=0]="ICE",e[e.MEDIA=1]="MEDIA",e[e.ADD_MLINE=2]="ADD_MLINE",e[e.REMOVE_MLINE=3]="REMOVE_MLINE",e[e.UPDATE_BITRATE=4]="UPDATE_BITRATE"}(N||(N={})),function(e){e[e.HD_VIDEO=2097152]="HD_VIDEO",e[e.FULL_HD_VIDEO=4096]="FULL_HD_VIDEO",e[e.DUAL_CALL=1]="DUAL_CALL",e[e.AV1_CODEC=262144]="AV1_CODEC"}(k||(k={}));const U="WMSC_DETECT_CANPLAY_VIDEO",x=new class{constructor(){this.confId="",this.nodeId="",this.webrtcMode=0,this.isMacIntel=!1,this.videoSettings={maxCaptureVideoSize:4,maxRecvVideoNum:w,hdVideoEnabled:!1},this._enabledLayerIds=[],this._layersSettings=null,this.iceServers=[]}setConfig(e){const{confId:t,nodeId:i,webrtcMode:s,isMacIntel:a,videoSettings:n,qosOptions:o,iceServers:r,avSyncMode:c}=e;void 0!==t&&(this.confId=t),void 0!==i&&(this.nodeId=i),void 0!==s&&(this.webrtcMode=s),void 0!==a&&(this.isMacIntel=a),void 0!==n&&(this.videoSettings=Object.assign(Object.assign({},this.videoSettings),n)),void 0!==o&&(this.qosOptions=o),null!=r&&(this.iceServers=r||[]),void 0!==c&&(this.avSyncMode=c)}getConfig(){const{confId:e,nodeId:t,webrtcMode:i,isMacIntel:s,videoSettings:a,qosOptions:n,iceServers:o}=this;return{confId:e,nodeId:t,webrtcMode:i,isMacIntel:s,videoSettings:a,qosOptions:n,iceServers:o}}setEnabledLayerIds(e){this._enabledLayerIds=e}get enabledLayerIds(){return this._enabledLayerIds}setLayersSettings(e){this._layersSettings=e}get layersSettings(){return this._layersSettings}};var F,W,z;!function(e){e.NOTIFY_SDK_JOIN_RWG_SUCCESS="NOTIFY_SDK_JOIN_RWG_SUCCESS",e.NOTIFY_SDK_JOIN_RWG_FAILURE="NOTIFY_SDK_JOIN_RWG_FAILURE",e.VIDEO_STREAMS="VIDEO_STREAMS",e.WMSC_MESSAGE_FROM_RWG="WMSC_MESSAGE_FROM_RWG",e.NOTIFY_WMSC_VIDEO_TAG_MAPPING="NOTIFY_WMSC_VIDEO_TAG_MAPPING",e.NOTIFY_SDK_SUBSCRIBE_VIDEO="NOTIFY_SDK_SUBSCRIBE_VIDEO",e.NOTIFY_SDK_UNSUBSCRIBE_VIDEO="NOTIFY_SDK_UNSUBSCRIBE_VIDEO",e.NOTIFY_SDK_ACTIVE_VIDEO_INDICATION="NOTIFY_SDK_ACTIVE_VIDEO_INDICATION",e.UPDATE_WMSC_PARAMS="UPDATE_WMSC_PARAMS",e.UPDATE_VIDEO_SOURCE_SETTINGS="UPDATE_VIDEO_SOURCE_SETTINGS"}(F||(F={})),function(e){e.ERROR="ERROR",e.WMSC_MESSAGE_TO_RWG_BY_SDK="WMSC_MESSAGE_TO_RWG_BY_SDK",e.WMSC_MAPPING_STREAMID_AND_MID="WMSC_MAPPING_STREAMID_AND_MID",e.GLOBAL_TRACE="GLOBAL_TRACE",e.MONITOR="MONITOR",e.DIRECT_MONITOR="DIRECT_MONITOR",e.CREATE_VIDEO_STREAMS_SUCCESS="CREATE_VIDEO_STREAMS_SUCCESS",e.CREATE_VIDEO_STREAMS_FAIL="CREATE_VIDEO_STREAMS_FAIL",e.PC_CONNECTED="PC_CONNECTED",e.VIDEO_SOURCE_UPDATED="VIDEO_SOURCE_UPDATED",e.VIDEO_TAG_MAPPED="VIDEO_TAG_MAPPED",e.VIDEO_QOS_DATA="VIDEO_QOS_DATA",e.UPDATE_VIDEO_CAPTURE_CONSTRAINTS="UPDATE_VIDEO_CAPTURE_CONSTRAINTS",e.ERROR_MESSAGE="ERROR_MESSAGE",e.NETWORK_QUALITY_CHANGE="NETWORK_QUALITY_CHANGE",e.NETWORK_QUALITY_CHANGE_AUDIO="NETWORK_QUALITY_CHANGE_AUDIO",e.VIDEO_CAPABILITIES_CHANGE="VIDEO_CAPABILITIES_CHANGE",e.UPDATE_VIDEO_SUBSCRIPTION="UPDATE_VIDEO_SUBSCRIPTION",e.UPDATE_VIDEO_UNSUBSCRIPTION="UPDATE_VIDEO_UNSUBSCRIPTION",e.SDP_NEGOTIATION_FAIL="SDP_NEGOTIATION_FAIL",e.PC_FAIL="PC_FAIL",e.VIDEO_FAIL="VIDEO_FAIL",e.PC_CLOSED="PC_CLOSED",e.AUDIO_RECAPTURE="AUDIO_RECAPTURE",e.CURRENT_DECODE_VIDEO_QUALITY="CURRENT_DECODE_VIDEO_QUALITY",e.CURRENT_DECODE_VIDEO_FPS="CURRENT_DECODE_VIDEO_FPS"}(W||(W={})),function(e){e[e.None=0]="None",e[e.App_SYNC=1]="App_SYNC",e[e.WEBRTC_SYNC=2]="WEBRTC_SYNC"}(z||(z={}));var j=i(7201),G=i.n(j),H=function(e,t,i,s){return new(i||(i=Promise))((function(a,n){function o(e){try{c(s.next(e))}catch(e){n(e)}}function r(e){try{c(s.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?a(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}c((s=s.apply(e,t||[])).next())}))};function Q(e){return(4294966272&e)>>>0}function q(e,t){return H(this,void 0,void 0,(function*(){switch(t){case E.GZIP_BASE64:{const t=yield function(e){return H(this,void 0,void 0,(function*(){const t=(new TextEncoder).encode(e);if(window.CompressionStream){const e=new CompressionStream("gzip"),i=e.writable.getWriter();return i.write(t),i.close(),new Response(e.readable).arrayBuffer()}{const{gzip:e}=yield i.e(404).then(i.bind(i,3075));return e(t).buffer}}))}(e);return function(e){let t="";const i=new Uint8Array(e);for(let e=0;e<i.byteLength;e++)t+=String.fromCharCode(i[e]);return btoa(t)}(t)}case E.PLAIN:return e;default:return null}}))}function Y(e,t){return e.length===t.length&&e.every(((e,i)=>e===t[i]))}function K(e,t){return e-t}function J(e,t){return t=t||{},{width:(e=e||{}).width||t.width,height:e.height||t.height,frameRate:e.frameRate||t.frameRate}}function X(e){var t;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"|";return e?G()(t=e.toString()).call(t,/[,,]/g,i):""}function Z(){return parseInt((arguments.length>0&&void 0!==arguments[0]?arguments[0]:"").substring(0,2),16)===R}function $(){return parseInt((arguments.length>0&&void 0!==arguments[0]?arguments[0]:"").substring(0,4),16)===A}function ee(){return parseInt((arguments.length>0&&void 0!==arguments[0]?arguments[0]:"").substring(0,4),16)===b}const te=new class{constructor(){this.setTrace()}setTrace(e,t){t&&(t.log||t.info)&&t.error&&t.warn?(this.log=t.log||t.info,this.info=t.info||t.log,this.debug=t.debug||t.log,this.verbose=this._verbose,this.error=t.error,this.warn=t.warn):(this.verbose=this._verbose.bind(this),this.log=this._log.bind(this),this.info=this._info.bind(this),this.debug=this._debug.bind(this),this.error=this._error.bind(this),this.warn=this._warn.bind(this)),this.level=e||a.INFO,this.level=this.level<a.ERROR?a.ERROR:this.level,this.level=this.level>a.VERBOSE?a.VERBOSE:this.level,this.getLevel=()=>this.level,this._trace=(e,t)=>{switch(e){case"log":console.log(...t);break;case"debug":console.debug(...t);break;case"info":console.info(...t);break;case"warn":console.warn(...t);break;case"error":console.error(...t)}}}getTracer(e){return{log:()=>{},debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}}}setTelemetry(e){this._telemetry="function"==typeof e?e:null}monitorLog(e){e&&this._telemetry&&this._telemetry({type:W.MONITOR,data:e})}directSendMonitorLog(e){e&&this._telemetry&&this._telemetry({type:W.DIRECT_MONITOR,data:e})}globalTrace(e){e&&this._telemetry&&this._telemetry({type:W.GLOBAL_TRACE,data:e})}_verbose(){if(this.level>=a.VERBOSE){const e=[...arguments];return e.unshift("[VERBOSE]"),this._trace("log",e),!0}return!1}_debug(){return this.level>=a.DEBUG&&(this._trace("debug",arguments),!0)}_log(){return this.level>=a.INFO&&(this._trace("log",arguments),!0)}_info(){return this.level>=a.INFO&&(this._trace("info",arguments),!0)}_warn(){return this.level>=a.WARN&&(this._trace("warn",arguments),!0)}_error(){return this.level>=a.ERROR&&(this._trace("error",arguments),!0)}};var ie=i(1265),se=i.n(ie),ae=i(8048),ne=i.n(ae);function oe(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,s)}return i}function re(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?oe(Object(i),!0).forEach((function(t){(0,c.A)(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):oe(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class ce{static splitSections(e){return e.split("\r\nm=").map(((e,t)=>t>0?"m="+e:e))}static splitLines(e){return e.split("\r\n")}static parseVersionLine(e){return parseInt(e.substring(2),10)}static writeVersionLine(e){return"v=".concat(e)}static parseOriginLine(e){const[t,i,s,a,n,o]=e.substring(2).split(" ");return{userName:t,sessionId:i,sessionVersion:parseInt(s,10),netType:a,addressType:n,address:o}}static writeOriginLine(e){const{userName:t,sessionId:i,sessionVersion:s,netType:a,addressType:n,address:o}=e;return"o=".concat(t," ").concat(i," ").concat(s," ").concat(a," ").concat(n," ").concat(o)}static parseSessionNameLine(e){return e.substring(2)}static writeSessionNameLine(e){return"s=".concat(e)}static parseInformationLine(e){return e.substring(2)}static writeInformationLine(e){return"i=".concat(e)}static parseConnectionLine(e){const[t,i,s]=e.substring(2).split(" ");return{netType:t,addressType:i,address:s}}static writeConnectionLine(e){const{netType:t,addressType:i,address:s}=e;return"c=".concat(t," ").concat(i," ").concat(s)}static parseBandwidthLine(e){return parseInt(e.substring(7),10)}static writeBandwidthLine(e){return"b=TIAS:".concat(e)}static parseTimingLine(e){const[t,i]=e.substring(2).split(" ");return{startTime:parseInt(t,10),stopTime:parseInt(i,10)}}static writeTimingLine(e){const{startTime:t,stopTime:i}=e;return"t=".concat(t," ").concat(i)}static parseRtpMapLine(e){const t=e.substring(9).match(/^(\d+) (.*)/),i=t[2].split("/");return{payloadType:parseInt(t[1],10),codecName:i[0],clockRate:parseInt(i[1],10),channels:i.length>=3?parseInt(i[2],10):null}}static writeRtpMapLine(e){const{payloadType:t,codecName:i,clockRate:s,channels:a}=e;let n="a=rtpmap:".concat(t," ").concat(i,"/").concat(s);return null!=a&&(n+="/"+a),n}static parseFmtpLine(e){const t=e.substring(7).match(/^(\d+) (.*)/),i={payloadType:parseInt(t[1],10)};return t[2].includes("=")?i.params=new Map(t[2].split(";").map((e=>se()(e).call(e).split("=")))):i.plain=t[2],i}static writeFmtpLine(e){const{payloadType:t,params:i,plain:s}=e;let a="a=fmtp:".concat(t," ");return i?(i.forEach(((e,t)=>{null!=e&&(a+="".concat(t,"=").concat(e,";"))})),a=a.slice(0,-1)):a+=s,a}static parseRtcpFbLine(e){const t=e.substring(10).match(/^(\d+) (.*)/);return{payloadType:parseInt(t[1],10),params:t[2].split(" ")}}static writeRtcpFbLine(e){const{payloadType:t,params:i}=e;let s="a=rtcp-fb:".concat(t);return i.forEach((e=>{s+=" "+e})),s}static parseRidLine(e){const t=e.substring(6).match(/^(\S+)\s+(send|recv|sendrecv)\s*(.*)$/),i=new Map;return t[3]&&t[3].split(";").forEach((e=>{const[t,s]=e.split("=");i.set(t,s)})),{rid:t[1],direction:t[2],params:i}}static writeRidLine(e){const{rid:t,direction:i,params:s}=e;let a;return(null==s?void 0:s.size)>0&&(a=Array.from(s.entries()).map((e=>{let[t,i]=e;return"".concat(t,"=").concat(i)})).join(";")),"a=rid:".concat(t," ").concat(i).concat(a?" "+a:"")}static parseSimulcastLine(e){const t=e.substring(12).match(/^(send|recv) (.*)/);return{direction:t[1],rids:t[2].split(";").map((e=>"~"===e[0]?{id:e.substring(1),paused:!0}:{id:e,paused:!1}))}}static writeSimulcastLine(e){const{direction:t,rids:i}=e;let s="a=simulcast:".concat(t," ");return i.forEach((e=>{const t=e.paused?"~"+e.id:e.id;s+=t+";"})),s.slice(0,-1)}static parseExtensionMapLine(e){var t;const i=e.substring(9).match(/^(\d+)(\/sendrecv|\/sendonly|\/recvonly|\/inactive)? (\S+)(\s\S+)?/);return{id:parseInt(i[1],10),direction:i[2]?i[2].substring(1):null,uri:i[3],attributes:i[4]?ne()(t=i[4]).call(t):null}}static writeExtensionMapLine(e){const{id:t,direction:i,uri:s,attributes:a}=e;let n="a=extmap:".concat(t);return null!=i&&(n+="/"+i),n+=" "+s,null!=a&&(n+=" "+a),n}static parseMidLine(e){return e.substring(6)}static writeMidLine(e){return"a=mid:".concat(e)}static writeDirectionLine(e){return"a=".concat(e)}static parseMsidLine(e){const[t,i]=e.substring(7).split(" ");return{streamId:t,trackId:i}}static writeMsidLine(e){const{streamId:t,trackId:i}=e;return"a=msid:".concat(t," ").concat(i)}static parseSsrcLine(e){const t=e.indexOf(" ");return{ssrc:parseInt(e.substring(7,t),10),attribute:e.substring(t+1)}}static writeSsrcLine(e){const{ssrc:t,attribute:i}=e;return"a=ssrc:".concat(t," ").concat(i)}static parseSsrcGroupLine(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t}}static writeSsrcGroupLine(e){const{semantics:t,ssrcs:i}=e;let s="a=ssrc-group:".concat(t);return i.forEach((e=>{s+=" "+e})),s}static parseGroupLine(e){const t=e.indexOf(" ");return{semantics:e.substring(8,t),ids:e.substring(t+1).split(" ")}}static writeGroupLine(e){const{semantics:t,ids:i}=e;let s="a=group:".concat(t);return i.forEach((e=>{s+=" "+e})),s}static writeExtMapAllowMixedLine(){return"a=extmap-allow-mixed"}static writeRtcpMuxLine(){return"a=rtcp-mux"}static writeRtcpReducedSizeLine(){return"a=rtcp-rsize"}static parseCandidateLine(e){const t=e.substring(12).split(" "),i={foundation:t[0],componentId:parseInt(t[1],10),transport:t[2],priority:parseInt(t[3],10),address:t[4],port:parseInt(t[5],10),candType:t[6],type:t[7],relAddress:null,relPort:null,candExtensions:[]};return"raddr"===t[8]&&"rport"===t[10]?(i.relAddress=t[9],i.relPort=parseInt(t[11],10),i.candExtensions=t.slice(12)):i.candExtensions=t.slice(8),i}static writeCandidateLine(e){const{foundation:t,componentId:i,transport:s,priority:a,address:n,port:o,candType:r,type:c,relAddress:d,relPort:h,candExtensions:l}=e;let u="a=candidate:".concat(t," ").concat(i," ").concat(s," ").concat(a)+" ".concat(n," ").concat(o," ").concat(r," ").concat(c);return null!=d&&null!=h&&(u+=" raddr ".concat(d," rport ").concat(h)),l.length&&(u+=" "+l.join(" ")),u}static parseSessionSection(e){const t={version:0,origin:null,sessionName:null,information:null,connection:null,bandwidth:null,timing:null,groups:[],extMapAllowMixed:null,otherLines:[]},i=this.splitLines(e);for(let e=0;e<i.length;e++){const s=i[e];s.length&&(s.match(/^v=/)?t.version=this.parseVersionLine(s):s.match(/^o=/)?t.origin=this.parseOriginLine(s):s.match(/^s=/)?t.sessionName=this.parseSessionNameLine(s):s.match(/^i=/)?t.information=this.parseInformationLine(s):s.match(/^c=/)?t.connection=this.parseConnectionLine(s):s.match(/^b=TIAS:/)?t.bandwidth=this.parseBandwidthLine(s):s.match(/^t=/)?t.timing=this.parseTimingLine(s):s.match(/^a=group:/)?t.groups.push(this.parseGroupLine(s)):s.match(/^a=extmap-allow-mixed$/)?t.extMapAllowMixed=!0:t.otherLines.push(s))}return t}static writeSessionSection(e){const t=[];return t.push(this.writeVersionLine(e.version)),null!=e.origin&&t.push(this.writeOriginLine(e.origin)),null!=e.sessionName&&t.push(this.writeSessionNameLine(e.sessionName)),null!=e.information&&t.push(this.writeInformationLine(e.information)),null!=e.connection&&t.push(this.writeConnectionLine(e.connection)),null!=e.bandwidth&&t.push(this.writeBandwidthLine(e.bandwidth)),null!=e.timing&&t.push(this.writeTimingLine(e.timing)),e.groups.forEach((e=>{t.push(this.writeGroupLine(e))})),e.extMapAllowMixed&&t.push(this.writeExtMapAllowMixedLine()),e.otherLines.length&&t.push(...e.otherLines),t.join("\r\n")+"\r\n"}static parseMediaSection(e){const t={type:null,port:null,protocol:null,connection:null,bandwidth:null,mid:null,direction:null,msid:null,rtcpMux:null,rtcpReducedSize:null,icePwd:null,iceUfrag:null,rtcp:null,codecs:[],extensionMap:new Map,rids:[],simulcast:null,ssrcs:[],ssrcGroups:[],candidates:[],otherLines:[]},i=[],s=[],a=this.splitLines(e),n=a[0].split(" ");t.type=n[0].substring(2),t.port=parseInt(n[1],10),t.protocol=n[2],t.payloadTypes=n.slice(3).map((e=>parseInt(e,10)));for(let e=1;e<a.length;e++){let n;const o=a[e];if(o.length)if(o.match(/^c=/))t.connection=this.parseConnectionLine(o);else if(o.match(/^b=TIAS:/))t.bandwidth=this.parseBandwidthLine(o);else if(o.match(/^a=rtpmap:/)){const e=this.parseRtpMapLine(o);t.codecs.push(re({},e))}else if(o.match(/^a=fmtp:/))i.push(o);else if(o.match(/^a=rtcp-fb:/))s.push(o);else if(o.match(/^a=rid:/))t.rids.push(this.parseRidLine(o));else if(o.match(/^a=simulcast:/))t.simulcast=this.parseSimulcastLine(o);else if(o.match(/^a=ssrc:/))t.ssrcs.push(this.parseSsrcLine(o));else if(o.match(/^a=ssrc-group:/))t.ssrcGroups.push(this.parseSsrcGroupLine(o));else if(o.match(/^a=extmap:/)){const e=this.parseExtensionMapLine(o);t.extensionMap.set(e.id,e)}else o.match(/^a=mid:/)?t.mid=this.parseMidLine(o):(n=o.match(/^a=(sendrecv|sendonly|recvonly|inactive)/))?t.direction=n[1]:o.match(/^a=msid:/)?t.msid=this.parseMsidLine(o):o.match(/^a=rtcp-mux$/)?t.rtcpMux=!0:o.match(/^a=rtcp-rsize$/)?t.rtcpReducedSize=!0:o.match(/^a=candidate:/)?t.candidates.push(this.parseCandidateLine(o)):o.match(/^a=rtcp:/)?t.rtcp=o:o.match(/^a=ice-ufrag:/)?t.iceUfrag=o.substring(12):o.match(/^a=ice-pwd:/)?t.icePwd=o.substring(10):t.otherLines.push(o)}return i.forEach((e=>{const i=this.parseFmtpLine(e),s=t.codecs.find((e=>e.payloadType===i.payloadType));s&&(i.params?(s.codecParams=new Map,i.params.forEach(((e,t)=>{"apt"===t&&(s.associatedPayloadType=parseInt(e,10)),s.codecParams.set(t,e)}))):(s.fmtpLines=[i.plain],"red"===s.codecName&&(s.associatedPayloadType=parseInt(i.plain.split("/")[0],10))))})),s.forEach((e=>{const i=this.parseRtcpFbLine(e),s=t.codecs.find((e=>e.payloadType===i.payloadType));s&&(s.rtcpFbParams=s.rtcpFbParams||[],s.rtcpFbParams.push(i.params))})),t}static writeMediaSection(e){var t,i,s,a;const n=[];let o="m=".concat(e.type," ").concat(e.port," ").concat(e.protocol);return e.payloadTypes.forEach((e=>{o+=" "+e})),n.push(o),e.connection&&n.push(this.writeConnectionLine(e.connection)),e.bandwidth&&n.push(this.writeBandwidthLine(e.bandwidth)),e.rtcp&&n.push(e.rtcp),e.iceUfrag&&n.push("a=ice-ufrag:".concat(e.iceUfrag)),e.icePwd&&n.push("a=ice-pwd:".concat(e.icePwd)),e.otherLines.length&&n.push(...e.otherLines),n.push(this.writeMidLine(e.mid)),e.extensionMap.size&&e.extensionMap.forEach(((e,t)=>{n.push(this.writeExtensionMapLine(e))})),n.push(this.writeDirectionLine(e.direction)),e.msid&&n.push(this.writeMsidLine(e.msid)),e.rtcpMux&&n.push(this.writeRtcpMuxLine()),e.rtcpReducedSize&&n.push(this.writeRtcpReducedSizeLine()),e.codecs.forEach((e=>{const{payloadType:t,codecName:i,clockRate:s,channels:a,codecParams:o,fmtpLines:r,rtcpFbParams:c}=e;n.push(this.writeRtpMapLine({payloadType:t,codecName:i,clockRate:s,channels:a})),null==c||c.forEach((e=>{n.push(this.writeRtcpFbLine({payloadType:t,params:e}))})),null!=o&&o.size&&n.push(this.writeFmtpLine({payloadType:t,params:o})),null==r||r.forEach((e=>{n.push(this.writeFmtpLine({payloadType:t,plain:e}))}))})),null===(t=e.ssrcGroups)||void 0===t||t.forEach((e=>{n.push(this.writeSsrcGroupLine(e))})),null===(i=e.ssrcs)||void 0===i||i.forEach((e=>{n.push(this.writeSsrcLine(e))})),null===(s=e.rids)||void 0===s||s.forEach((e=>{n.push(this.writeRidLine(e))})),null===(a=e.candidates)||void 0===a||a.forEach((e=>{n.push(this.writeCandidateLine(e))})),e.simulcast&&n.push(this.writeSimulcastLine(e.simulcast)),n.join("\r\n")+"\r\n"}static parse(e){const t={session:null,media:[]},i=this.splitSections(e);return t.session=this.parseSessionSection(i.shift()),i.forEach((e=>{const i=this.parseMediaSection(e);t.media.push(i)})),t}static write(e){let t=this.writeSessionSection(e.session);return e.media.forEach((e=>{t+=this.writeMediaSection(e)})),t}}var de=i(8935);class he{static parseSdp(e){return ce.parse(e)}static writeSdp(e){return ce.write(e)}static cloneSdp(e){return"function"==typeof structuredClone?structuredClone(e):this.parseSdp(this.writeSdp(e))}static generateSsrc(){return Math.floor(4294967294*Math.random())+1}static generateId(){return Math.random().toString(36).substring(2,12)}static generateSessionId(){return Math.random().toString().substring(2,22)}static generateUuid(){const e=Array.from(Array(256).keys()).map((e=>e.toString(16).padStart(2,"0"))),t=crypto.getRandomValues(new Uint8Array(16));return t[6]=15&t[6]|64,t[8]=63&t[8]|128,Array.from(t.entries()).map((t=>{let[i,s]=t;return[4,6,8,10].includes(i)?"-".concat(e[s]):e[s]})).join("")}static generateIceCredentials(){const e=e=>[...Array(e)].map((()=>Math.random().toString(36).charAt(2))).join("");return{ice_ufrag:e(8),ice_pwd:e(22)}}static getSessionBoilerplate(){return"v=\r\no=- ".concat(this.generateSessionId()," 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n")}static getNtpSeconds(){return Math.floor((Date.now()+(Date.UTC(1970,0,1)-Date.UTC(1900,0,1)))/1e3)}static findHeaderExtensionByUri(e,t){for(const[i,s]of e.extensionMap)if(s.uri===t)return i;return-1}static addHeaderExtension(e,t){const{id:i}=t;return e.extensionMap.set(i,t),!0}static removeHeaderExtensionByUri(e,t){let i=!1;return e.extensionMap.forEach(((e,s,a)=>{e.uri===t&&(a.delete(s),i=!0)})),i}static removeMidRidHeaderExtensions(e){e.extensionMap.forEach(((e,t,i)=>{/^urn:ietf:params:rtp-hdrext:sdes:(?:mid|rtp-stream-id|repaired-rtp-stream-id)$/.test(e.uri)&&i.delete(t)}))}static updateCodecParameters(e,t,i,s,a){e.media.filter((e=>e.type===t&&e.direction===i)).forEach((e=>he.updateMLineCodecParameters(e,s,a)))}static updateMLineCodecParameters(e,t,i){e.codecs.filter((e=>e.codecName===t)).forEach((e=>{i.forEach(((t,i)=>{e.codecParams.set(i,t)}))}))}static updateCodecParametersByMid(e,t,i,s){e.media.filter((e=>e.mid===t)).forEach((e=>he.updateMLineCodecParameters(e,i,s)))}static filterCodecs(e,t){e.media.forEach((e=>{const i=[];e.codecs.forEach((s=>{t&&!t(s,e)||i.push(s.payloadType)})),e.codecs.forEach((e=>{i.includes(e.associatedPayloadType)&&i.push(e.payloadType)})),e.payloadTypes=e.payloadTypes.filter((e=>i.includes(e))),e.codecs=e.codecs.filter((e=>i.includes(e.payloadType)))})),e.media=e.media.filter((e=>e.payloadTypes.length))}static filterH264Profiles(e,t,i){e.media.filter((e=>e.direction===t)).forEach((e=>{const t=[];e.codecs.filter((e=>"H264"===e.codecName)).forEach((e=>{var s;const a=parseInt(null===(s=e.codecParams.get("profile-level-id"))||void 0===s?void 0:s.substring(0,2),16);i.includes(a)&&t.push(e.payloadType)})),e.codecs.forEach((e=>{t.includes(e.associatedPayloadType)&&t.push(e.payloadType)})),e.payloadTypes=e.payloadTypes.filter((e=>t.includes(e))),e.codecs=e.codecs.filter((e=>t.includes(e.payloadType)))}))}static getH264ProfileIds(e,t,i){const s=new Set,a=e.media.find((e=>"video"===e.type&&e.direction===t));return null==a||a.codecs.forEach((e=>{if("H264"===e.codecName&&(void 0===i||parseInt(e.codecParams.get("packetization-mode"))===i)){var t;const i=parseInt(null===(t=e.codecParams.get("profile-level-id"))||void 0===t?void 0:t.substring(0,2),16);i&&s.add(i)}})),Array.from(s.values())}static getMediaStartBandwidth(e){var t;const i=null==e||null===(t=e.codecs[0])||void 0===t?void 0:t.codecParams.get("x-google-start-bitrate");return 1e3*parseInt(i,10)||void 0}static mungeEgressLocalOffer(e,t,i){let s,a,n=!(arguments.length>3&&void 0!==arguments[3])||arguments[3],o=0;if(e.media.forEach((e=>{const{extensionMap:t,type:i,direction:a}=e;t.forEach(((e,t)=>{t>o&&(o=t)})),"video"!==i||"sendonly"!==a||s||(s=e)})),!s)throw new Error("Failed to find a video media section for send");if(s.msid){s.msid.streamId=i;const{trackId:e}=s.msid;a="".concat(i," ").concat(e)}else a="".concat(i," ").concat(he.generateUuid());if(t>1&&n){s.rids=[],s.simulcast=null,s.ssrcs=[],s.ssrcGroups=[];const e=s.codecs.some((e=>"rtx"===e.codecName)),i=[],n=he.generateUuid();for(let o=0;o<t;o++){const t=he.generateSsrc();if(i.push(t),s.ssrcs.push({ssrc:t,attribute:"cname:"+n}),s.ssrcs.push({ssrc:t,attribute:"msid:"+a}),e){const e=he.generateSsrc();s.ssrcs.push({ssrc:e,attribute:"cname:"+n}),s.ssrcs.push({ssrc:e,attribute:"msid:"+a}),s.ssrcGroups.push({semantics:"FID",ssrcs:[t,e]})}}s.ssrcGroups.push({semantics:"SIM",ssrcs:i})}he.removeMidRidHeaderExtensions(s),(0,de.n_)()&&(0,de.nr)()&&15===(0,de.Cd)()&&1===(0,de.w_)()||he.removeHeaderExtensionByUri(s,"urn:3gpp:video-orientation");const r={uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time"};if(-1===he.findHeaderExtensionByUri(s,r.uri)&&(r.id=++o,he.addHeaderExtension(s,r)),t>1){e.session.extMapAllowMixed=!0;const t={uri:"http://www.webrtc.org/experiments/rtp-hdrext/video-layers-allocation00"};-1===he.findHeaderExtensionByUri(s,t.uri)&&(t.id=++o,he.addHeaderExtension(s,t))}}static mungeEgressOfferToRemote(e){e.session.timing={startTime:he.getNtpSeconds(),stopTime:0};const t=e.media.find((e=>"video"===e.type&&"sendonly"===e.direction));if((0,de.gm)()&&null!=t&&t.simulcast){t.rids=null,t.simulcast=null;const e=[];t.ssrcGroups.forEach((t=>{"FID"===t.semantics&&e.push(t.ssrcs[0])})),t.ssrcGroups.push({semantics:"SIM",ssrcs:e})}}static mungeEgressAnswer(e,t,i){if((0,de.gm)()&&t>1){const i=e.media.find((e=>"video"===e.type&&"recvonly"===e.direction));if(i){const e=[];for(let i=0;i<t;i++)e.push({rid:i.toString(),direction:"recv"});const s={direction:"recv",rids:[]};e.forEach((e=>{s.rids.push({id:e.rid})})),i.rids=e,i.simulcast=s}}i&&he.updateCodecParameters(e,"video","recvonly","H264",i)}static mungeIngressLocalOffer(e,t){t&&he.updateCodecParameters(e,"video","recvonly","H264",t)}static updateIceCredential(e,t){const{ice_pwd:i,ice_ufrag:s}=t;e.media.forEach((e=>{e&&(e.icePwd=i,e.iceUfrag=s)}))}static getSSRCByMid(e,t){let i;const s=e.media.find((e=>e.mid==t)),{ssrcs:a}=s;return a.length&&(i=a[0].ssrc),i}static getMlineCodecFromLocalOffer(e,t,i){var s;return null===(s=e.media.find((e=>t===e.mid)))||void 0===s?void 0:s.codecs.find((e=>e.codecName===i))}static updateStreamIdByMid(e,t,i){const s=e.media.find((e=>e.mid===t));if(s.msid){const{trackId:e}=s.msid;s.msid.streamId=i,s.ssrcs&&s.ssrcs.forEach((t=>{0===t.attribute.indexOf("msid")&&(t.attribute="msid:".concat(i," ").concat(e))}))}}}const le=[{layerId:4,width:1920,height:1080,maxFramerate:30,minBitrate:25e5,targetBitrate:5e6,maxBitrate:5e6},{layerId:4,width:1600,height:900,maxFramerate:30,minBitrate:15e5,targetBitrate:3e6,maxBitrate:3e6,special:{ffMaxBitrate:35e5}},{layerId:3,width:1280,height:720,maxFramerate:30,minBitrate:8e5,targetBitrate:2e6,maxBitrate:2e6,special:{ffMinBitrate:12e5,ffMaxBitrate:25e5}},{layerId:3,width:960,height:540,maxFramerate:30,minBitrate:55e4,targetBitrate:12e5,maxBitrate:12e5,special:{ffMaxBitrate:15e5}},{layerId:2,width:640,height:360,maxFramerate:30,minBitrate:25e4,targetBitrate:5e5,maxBitrate:7e5,special:{ffMaxBitrate:8e5}},{layerId:2,width:480,height:270,maxFramerate:30,minBitrate:18e4,targetBitrate:35e4,maxBitrate:45e4,special:{ffMaxBitrate:8e5}},{layerId:1,width:320,height:180,maxFramerate:30,minBitrate:1e5,targetBitrate:15e4,maxBitrate:2e5},{layerId:1,width:256,height:144,maxFramerate:30,minBitrate:6e4,targetBitrate:1e5,maxBitrate:13e4}];function ue(e){const t=e.map(((e,t)=>Object.assign(Object.assign({},e),{formatIndex:t})));x.setLayersSettings(t)}function me(e){x.setEnabledLayerIds(e)}function pe(){return x.layersSettings}function ge(){return x.enabledLayerIds}function Se(){return ge()[0]}function _e(e){return ge().includes(e)}function ve(){const e=ge();return e[e.length-1]}function fe(e){var t;return null===(t=pe())||void 0===t?void 0:t[e]}function ye(e){const t=pe();if(!t)return;const i=t.findIndex((t=>t.layerId===e));return i>=0?fe(i):void 0}function Me(e){const t=pe();if(t)for(let i=t.length-1;i>=0;i--)if(t[i].layerId===e)return fe(i)}function Ce(e){const t=pe();if(!t)return;const i=t.findIndex((t=>t.layerId<=e));return i>=0?fe(i):void 0}function Ie(e){var t;return(null===(t=ye(e))||void 0===t?void 0:t.maxBitrate)||0}function Ee(e){var t;return(null===(t=ye(e))||void 0===t?void 0:t.targetBitrate)||0}function Te(e,t){const i=ye(e);if(i){const{width:e,height:s,maxBitrate:a}=i;return Math.floor(t.width*t.height/(e*s)*a)}}function Re(e){const t=e.width*e.height;return t>921600?4:t>307200?3:t>76800?2:t>19200?1:t>0?0:-1}function Ae(e){var t,i;return!!(null===(i=null===(t=x.videoSettings)||void 0===t?void 0:t.preferSoftwareCodec)||void 0===i?void 0:i[e])}class be{constructor(e){this._array=new Array(e),this._size=e,this._index=0,this._count=0}get size(){return this._size}get count(){return this._count}empty(){return 0===this._count}full(){return this._count===this._size}clear(){this._array=new Array(this._size),this._index=0,this._count=0}fill(e){return this._array.fill(e),this._index=0,this._count=this._size,this}get lastIndex(){return 0===this._index?this._size-1:this._index-1}nextIndex(e){return(e+1)%this._size}push(e){this._array[this._index]=e,this._index=this.nextIndex(this._index),this._count<this._size&&this._count++}pop(){if(this.empty())return;const e=this.lastIndex;return this._index=e,this._count>0&&this._count--,this._array[e]}at(e){if(!(this._count<this._size&&e>=this._count))return this._array[e]}front(){if(!this.empty())return this._array[this._count<this.size?0:this._index]}back(){if(!this.empty())return this._array[this.lastIndex]}unwrap(){return this._count<this._size?this._array.slice(0,this._count):[...this._array.slice(this._index),...this._array.slice(0,this._index)]}findIndex(e){if(this._count<this._size){for(let t=0;t<this._count;t++)if(e(this._array[t]))return t}else{for(let t=this._index;t<this._size;t++)if(e(this._array[t]))return t;for(let t=0;t<this._index;t++)if(e(this._array[t]))return t}return-1}findLastIndex(e){if(this._count<this._size){for(let t=this._count-1;t>=0;t--)if(e(this._array[t]))return t}else{for(let t=this._size-1;t>=this._index;t--)if(e(this._array[t]))return t;for(let t=this._index-1;t>=0;t--)if(e(this._array[t]))return t}return-1}find(e){const t=this.findIndex(e);return-1===t?void 0:this._array[t]}findLast(e){const t=this.findLastIndex(e);return-1===t?void 0:this._array[t]}}function we(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,s)}return i}function De(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?we(Object(i),!0).forEach((function(t){(0,c.A)(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):we(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}te.getTracer("WmscStats");class Le{constructor(){this.sendStatsMonitor=new Oe({cacheSize:Le.sendStatsCacheSize}),this.recvStatsMonitor=new Pe({cacheSize:Le.recvStatsCacheSize}),this.sendUsageStatsEnabled=!1,this.recvUsageStatsEnabled=!1,this.maxEncodingFramerate=30,this.resourceUsageStatsReportTimestamp=0,this.resourceUsageStatsIntervalId=null,this.resourceUsageStatsCallback=null}onStats(e){e.forEach((e=>{this.sendStatsMonitor.onStatsReport(e),this.recvStatsMonitor.onStatsReport(e)}))}getSendStatsMonitor(){return this.sendStatsMonitor}getRecvStatsMonitor(){return this.recvStatsMonitor}setOptions(e){const{sendUsageStatsEnabled:t,recvUsageStatsEnabled:i,maxEncodingFramerate:s}=e||{};void 0!==t&&(this.sendUsageStatsEnabled=t),void 0!==i&&(this.recvUsageStatsEnabled=i),void 0!==s&&(this.maxEncodingFramerate=s)}start(e){e&&this.setOptions(e),this.sendUsageStatsEnabled&&this.sendStatsMonitor.setOptions({outboundRtpStatsEnabled:!0}),this.sendStatsMonitor.start(),this.recvUsageStatsEnabled&&this.recvStatsMonitor.setOptions({inboundRtpStatsEnabled:!0}),this.recvStatsMonitor.start(),(this.sendUsageStatsEnabled||this.recvUsageStatsEnabled)&&(this.resourceUsageStatsIntervalId=setInterval((()=>{this._reportResourceUsageStats()}),Le.resourceUsageCheckInterval))}stop(){this.sendStatsMonitor.stop(),this.recvStatsMonitor.stop(),clearInterval(this.resourceUsageStatsIntervalId),this.resourceUsageStatsIntervalId=null}reset(){this.sendStatsMonitor.reset(),this.recvStatsMonitor.reset(),this.resourceUsageStatsReportTimestamp=0}registerOutgoingBitrateStatsCallback(e){this.sendStatsMonitor.outgoingBitrateStatsCallback=e}registerResourceUsageStatsCallback(e){this.resourceUsageStatsCallback=e}_reportResourceUsageStats(){var e;const t={};let i=0;if(this.sendUsageStatsEnabled){const e=this._getSendResourceUsageStats();(null==e?void 0:e.duration)>0&&(t.send=De({},e),i=Math.max(i,e.timestamp))}if(this.recvUsageStatsEnabled){const e=this._getRecvResourceUsageStats();(null==e?void 0:e.duration)>0&&(t.recv=De({},e),i=Math.max(i,e.timestamp))}this.resourceUsageStatsReportTimestamp=i,null===(e=this.resourceUsageStatsCallback)||void 0===e||e.call(this,t)}_getSendResourceUsageStats(){if(!this.sendStatsMonitor.isStarted())return;const{NONE:e,UNDERUSING:t,NORMAL:i,OVERUSING:s}=C,a=this.sendStatsMonitor.getOutboundRtpStats(),n=1e3/this.maxEncodingFramerate;let o=0,r=0,c=0,d=0,h=0,l=e;for(const[u,m]of a){const a=m.unwrap(),u=a[a.length-1],p=Math.max(this.resourceUsageStatsReportTimestamp-500,u.timestamp-Le.resourceUsageCheckInterval-500);let g=a.find((e=>e.timestamp>p));if(!g)continue;for(let e=1;e<a.length;e++){const t=a[e-1],i=a[e];i.framesEncoded>t.framesEncoded?h=Math.max(h,i.timestamp):i.framesEncoded<t.framesEncoded&&(g=i)}const S=u.framesEncoded-g.framesEncoded,_=u.framesSent-g.framesSent,v=u.timestamp-g.timestamp;if(o+=S,r+=_,c=Math.max(c,v),d=Math.max(d,u.timestamp),0===S||v<Le.resourceUsageMinTimeSlice)continue;const f=S?1e3*(u.totalEncodeTime-g.totalEncodeTime)/S:0;let y,M,C=e,I=e,E=e;if(I=S>_||S>=Le.encodeTimeMinFrameCount&&f>=n*Le.encodeTimeFactorThresholdCritical?s:S<=_&&S>=Le.encodeTimeMinFrameCount&&f<n*Le.encodeTimeFactorThresholdNormal?t:i,u.qualityLimitationDurations)if(y=1e3*(u.qualityLimitationDurations.cpu-g.qualityLimitationDurations.cpu)/v,M=1e3*(u.qualityLimitationDurations.other-g.qualityLimitationDurations.other)/v,y>=Le.qualityLimitationRatioThresholdCritical||M>=Le.qualityLimitationRatioThresholdCritical){E=s;const e="WMSC_Perf_Control: cpuLimitationRatio ".concat(y);te.monitorLog(e),te.globalTrace({logLevel:"log",log:e,tags:["WMSC_Perf_Control"]})}else E=y<Le.qualityLimitationRatioThresholdNormal&&M<Le.qualityLimitationRatioThresholdNormal?t:i;C=I,K(E,C)>0&&(C=E),K(C,l)>0&&(l=C)}return{usageState:l,framesEncoded:o,framesSent:r,duration:c,encodeTimestamp:h,timestamp:d}}_getRecvResourceUsageStats(){if(!this.recvStatsMonitor.isStarted())return;const{NONE:e,UNDERUSING:t,NORMAL:i,OVERUSING:s}=C,a=this.recvStatsMonitor.getInboundRtpStats();let n=0,o=0,r=0,c=0,d=0,h=e,l=-1,u=0;for(const[g,S]of a){var m,p;const a=S.unwrap(),g=a[a.length-1],_=Math.max(this.resourceUsageStatsReportTimestamp-500,g.timestamp-Le.resourceUsageCheckInterval-500);let v=S.find((e=>e.timestamp>_));if(!v)continue;for(let e=1;e<a.length;e++){const t=a[e-1],i=a[e];i.framesDecoded<t.framesDecoded&&(v=i)}const f=g.framesReceived-v.framesReceived,y=(null!==(m=g.framesDropped)&&void 0!==m?m:0)-(null!==(p=v.framesDropped)&&void 0!==p?p:0),M=g.framesDecoded-v.framesDecoded,C=g.timestamp-v.timestamp;if(n+=f,o+=y,r+=M,c=Math.max(c,C),d=Math.max(d,g.timestamp),0===f||C<Le.resourceUsageMinTimeSlice)continue;const I=Re({width:g.frameWidth,height:g.frameHeight}),E=f?y/f:0;(I>l||I===l&&E>u)&&(l=I,u=E);const T=C/f;let R=1e3*(g.totalDecodeTime-v.totalDecodeTime);R>=C&&(R=C);const A=M?R/M:0;let b=e;b=M>=Le.decodeTimeMinFrameCount&&A>=T*Le.decodeTimeFactorThresholdCritical&&f>M?s:M>=Le.decodeTimeMinFrameCount&&A<T*Le.decodeTimeFactorThresholdNormal?t:i,K(b,h)>0&&(h=b)}return{usageState:h,framesReceived:n,framesDropped:o,framesDecoded:r,maxVideoSize:l,maxVideoSizeFrameDropRate:u,duration:c,timestamp:d}}}(0,c.A)(Le,"sendStatsCacheSize",4),(0,c.A)(Le,"recvStatsCacheSize",4),(0,c.A)(Le,"resourceUsageMinTimeSlice",2e3),(0,c.A)(Le,"resourceUsageCheckInterval",3e3),(0,c.A)(Le,"encodeTimeMinFrameCount",10),(0,c.A)(Le,"encodeTimeFactorThresholdNormal",.9),(0,c.A)(Le,"encodeTimeFactorThresholdCritical",1.1),(0,c.A)(Le,"qualityLimitationRatioThresholdNormal",.05),(0,c.A)(Le,"qualityLimitationRatioThresholdCritical",.95),(0,c.A)(Le,"decodeTimeMinFrameCount",10),(0,c.A)(Le,"decodeTimeFactorThresholdNormal",.9),(0,c.A)(Le,"decodeTimeFactorThresholdCritical",1.1);class Oe{constructor(e){this.cacheSize=e.cacheSize||10,this.started=!1,this.selectedCandidatePairId=null,this.roundTripTime=0,this.remoteCandidateId=null,this.networkProtocol=null,this.localCandidateId=null,this.candidateType=null,this.outboundRtpStatsEnabled=!1,this.outboundRtpStatsMap=new Map,this.outgoingBitrateStatsCallback=null}reset(){this.resetCandidateStats(),this.resetOutboundRtpStats()}resetCandidateStats(){this.selectedCandidatePairId=null,this.roundTripTime=0,this.remoteCandidateId=null,this.networkProtocol=null}resetOutboundRtpStats(){this.outboundRtpStatsMap.clear()}setOptions(e){const{outboundRtpStatsEnabled:t}=e||{};void 0!==t&&(this.outboundRtpStatsEnabled=t)}start(e){e&&this.setOptions(e),this.started=!0}stop(){this.started=!1}isStarted(){return this.started}getNetworkProtocol(){return this.networkProtocol}getCurrentRoundTripTime(){return this.roundTripTime}getOutboundRtpStats(){return this.outboundRtpStatsMap}onStatsReport(e){if(this.started)switch(e.type){case"transport":this.onTransportStats(e);break;case"candidate-pair":this.onCandidatePairStats(e);break;case"remote-candidate":this.onRemoteCandidateStats(e);break;case"outbound-rtp":this.onOutboundRtpStats(e);break;case"local-candidate":this.onLocalCandidateStats(e)}}onTransportStats(e){const{selectedCandidatePairId:t,dtlsState:i}=e;"connected"===i&&(this.selectedCandidatePairId=t)}onCandidatePairStats(e){const{id:t,state:i,nominated:s,availableOutgoingBitrate:a,currentRoundTripTime:n,remoteCandidateId:o,timestamp:r,localCandidateId:c}=e;var d;t===this.selectedCandidatePairId&&"succeeded"===i&&s&&(this.roundTripTime=n,this.remoteCandidateId=o,this.localCandidateId=c,null===(d=this.outgoingBitrateStatsCallback)||void 0===d||d.call(this,{availableOutgoingBitrate:a,timestamp:r}))}onRemoteCandidateStats(e){const{id:t,protocol:i,port:s}=e;if(t===this.remoteCandidateId&&!this.networkProtocol){this.networkProtocol=i;const e="WMSC_Network_Change: send|".concat(i,"|").concat(s);te.globalTrace({logLevel:"log",log:e,tags:["WMSC_Network_Change"]}),te.monitorLog(e)}}onLocalCandidateStats(e){const{id:t,candidateType:i}=e;if(t==this.localCandidateId&&this.candidateType!=i){this.candidateType=i;const e="WMSC_LocalCandidatae_Change:send|".concat(i);te.globalTrace({logLevel:"directReport",log:e,tags:["WMSC_LocalCandidatae_Change"]}),te.monitorLog(e)}}onOutboundRtpStats(e){if(!this.outboundRtpStatsEnabled||"video"!==e.kind)return;const{ssrc:t,framesEncoded:i,framesSent:s,totalEncodeTime:a,qualityLimitationDurations:n,pliCount:o,qpSum:r,timestamp:c}=e;let d=this.outboundRtpStatsMap.get(t);d||(d=new be(this.cacheSize),this.outboundRtpStatsMap.set(t,d)),d.push({framesEncoded:i,framesSent:s,totalEncodeTime:a,qualityLimitationDurations:n,pliCount:o,qpSum:r,timestamp:c})}}class Pe{constructor(e){this.cacheSize=e.cacheSize||10,this.started=!1,this.selectedCandidatePairId=null,this.roundTripTime=0,this.remoteCandidateId=null,this.networkProtocol=null,this.localCandidateId=null,this.candidateType=null,this.inboundRtpStatsEnabled=!1,this.inboundRtpStatsMap=new Map}reset(){this.resetCandidateStats(),this.resetInboundRtpStats()}resetCandidateStats(){this.selectedCandidatePairId=null,this.roundTripTime=0,this.remoteCandidateId=null,this.networkProtocol=null}resetInboundRtpStats(){this.inboundRtpStatsMap.clear()}setOptions(e){const{inboundRtpStatsEnabled:t}=e||{};void 0!==t&&(this.inboundRtpStatsEnabled=t)}start(e){e&&this.setOptions(e),this.started=!0}stop(){this.started=!1}isStarted(){return this.started}getNetworkProtocol(){return this.networkProtocol}getCurrentRoundTripTime(){return this.roundTripTime}getInboundRtpStats(){return this.inboundRtpStatsMap}onStatsReport(e){if(this.started)switch(e.type){case"transport":this.onTransportStats(e);break;case"candidate-pair":this.onCandidatePairStats(e);break;case"remote-candidate":this.onRemoteCandidateStats(e);break;case"inbound-rtp":this.onInboundRtpStats(e);break;case"local-candidate":this.onLocalCandidateStats(e)}}onTransportStats(e){const{selectedCandidatePairId:t,dtlsState:i}=e;"connected"===i&&(this.selectedCandidatePairId=t)}onCandidatePairStats(e){const{id:t,state:i,nominated:s,currentRoundTripTime:a,remoteCandidateId:n,localCandidateId:o}=e;t===this.selectedCandidatePairId&&"succeeded"===i&&s&&(this.roundTripTime=a,this.remoteCandidateId=n,this.localCandidateId=o)}onRemoteCandidateStats(e){const{id:t,protocol:i,port:s}=e;if(t===this.remoteCandidateId&&!this.networkProtocol){this.networkProtocol=i;const e="WMSC_Network_Change: recv|".concat(i,"|").concat(s);te.globalTrace({logLevel:"log",log:e,tags:["WMSC_Network_Change"]}),te.monitorLog(e)}}onLocalCandidateStats(e){const{id:t,candidateType:i}=e;if(t==this.localCandidateId&&this.candidateType!=i){this.localCandidateId=t,this.candidateType=i;const e="WMSC_LocalCandidatae_Change:recv|".concat(i);te.globalTrace({logLevel:"directReport",log:e,tags:["WMSC_LocalCandidatae_Change"]}),te.monitorLog(e)}}onInboundRtpStats(e){if(!this.inboundRtpStatsEnabled||"video"!==e.kind||!e.framesReceived)return;const{ssrc:t,framesDecoded:i,framesDropped:s,framesReceived:a,keyFramesDecoded:n,totalDecodeTime:o,pliCount:r,frameWidth:c,frameHeight:d,timestamp:h}=e;let l=this.inboundRtpStatsMap.get(t);l||(l=new be(this.cacheSize),this.inboundRtpStatsMap.set(t,l)),l.push({framesDecoded:i,framesDropped:s,framesReceived:a,keyFramesDecoded:n,totalDecodeTime:o,pliCount:r,frameWidth:c,frameHeight:d,timestamp:h})}}const Ve=new Le;class Be{static mean(e){if(e.length)return e.reduce(((e,t)=>e+t),0)/e.length}static median(e){if(!e.length)return;h()(e).call(e,((e,t)=>e-t));const t=Math.floor(e.length/2);return e.length%2!=0?e[t]:(e[t-1]+e[t])/2}static variance(e){if(!e.length)return;const t=e.reduce(((e,t)=>e+t),0)/e.length,i=e.map((e=>Math.pow(e-t,2)));return i.reduce(((e,t)=>e+t),0)/i.length}static expMovingAverage(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:.5;if(!e.length)return[];const i=[e[0]];for(let s=1;s<e.length;s++)i.push(t*e[s]+(1-t)*i[s-1]);return i}static bestFitSlope(e){if(e.length<2)return;const t=e.length;let i=0,s=0,a=0,n=0;for(let o=0;o<t;o++)i+=o,s+=e[o],a+=o*e[o],n+=o*o;return(t*a-i*s)/(t*n-i*i)}}function Ne(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,s)}return i}function ke(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Ne(Object(i),!0).forEach((function(t){(0,c.A)(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Ne(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}const Ue=te.getTracer("WmscQosMgr"),xe=e=>{Ue.log(e),te.monitorLog("".concat(e))},Fe=e=>{xe("WMSC_Perf_Control: ".concat(e)),te.globalTrace({logLevel:"log",log:e,tags:["WMSC_Perf_Control"]})},We=8e4,ze=Object.freeze({Hold:0,Increase:1,Decrease:2}),je=Object.freeze({None:0,Increase:1,Decrease:2}),Ge=Object.freeze({User:0,OutgoingBandwidth:1,ReceiverBandwidth:2,Other:3}),He=Object.freeze({Low:0,Medium:1,High:2});class Qe{constructor(){this.outgoingBandwidthAdaptationEnabled=!0,this.outgoingBandwidthProbingEnabled=!0,this.outgoingBandwidthFromServer=!1,this.receiverBandwidthAdaptationEnabled=!0,this.additionalSubLayersEnabled=!0,this.lossDetectionEnabled=!1,this.performanceAdaptationEnabled=!0,this.maxEncodingLayers=3,this.sendActive=!1,this.sendActivatedTime=0,this.videoSourceLive=!1,this.videoSourceLiveTime=0,this.pendingLayersUpdate=Promise.resolve(),this.requestedLayerIds=[],this.additionalSubLayerIds=[],this.layersAllocation=[],this.layersAllocationCache=null,this.outgoingBandwidthProbingScheduledTime=0,this.maxSubVideoSize=-1,this.maxFormatIndex=0,this.feasibleFormatIndex=-1,this.failedEncodings=new Map,this.sendUsageStateHistory=new be(Qe.resourceUsageStateHistorySize),this.sendUsageAdjustments=new be(Qe.resourceUsageAdjustmentHistorySize),this.sendUsageIncreaseFailedAttempts=0,this.sendUsageIncreaseFailedTime=0,this.maxFeasibleRecvSize=T,this.recvUsageStateHistory=new be(Qe.resourceUsageStateHistorySize),this.recvUsageAdjustments=new be(Qe.resourceUsageAdjustmentHistorySize),this.recvUsageIncreaseFailedAttempts=0,this.recvUsageIncreaseFailedTime=0,this.outgoingBitrateStats=new be(Qe.outgoingBitrateStatsCacheSize),this.minOutgoingBitrate=We,this.outgoingBandwidth=1/0,this.receiverBandwidthReport=null,this.receiverL3BandwidthEvaluation=null,this.receiverBandwidthUpdatePending=!1,this.receiverBandwidthUpdateTimeoutId=null,this.isDualCall=!0,this.audioBandwidth=0,this.videoStartBandwidth=0,this.receiverStats=new be(Qe.receiverStatsCacheSize),this.framingDelayStats=new be(Qe.maxFramingDelayWindowSize),this.minOutgoingBitrateAdjustments=new be(Qe.minOutgoingBitrateAdjustmentHistorySize),this.receiverReport=null,this.residualLossDetectedTimestamp=0,this.inherentLossDetectedTimestamp=0,this.minOutgoingBitrateUpdatedTime=0,this.decreaseBitrateWindow=5,this.increaseBitrateWindow=5,this.decreaseBitrateRate=.5,this.increaseBitrateRate=.7,this.maxEncodeBitrate=0,this.currentMaxEncodeBitrate=0,this.messageCallback=null,this.maxRecvVideoSizeUpdateCallback=null,this.sendUsageStateUpdateCallback=null,Ve.registerOutgoingBitrateStatsCallback(this.onOutgoingBandwidthStats.bind(this)),Ve.registerResourceUsageStatsCallback(this.onResourceUsageStats.bind(this))}static areLayersAllocationsEqual(e,t){return e.length===t.length&&e.every(((e,i)=>{const s=t[i];return e.layerId===s.layerId&&e.maxBitrate===s.maxBitrate&&(a=e.format,n=s.format,a.width===n.width&&a.height===n.height);var a,n}))}static isBitrateChangeAboveRatio(e,t,i){return!e||Math.abs(t-e)/e>i}static getLayersChangePriority(e){switch(e){case Ge.User:return He.High;case Ge.ReceiverBandwidth:return He.Medium;default:return He.Low}}_resetSendUsageStats(){Ve.getSendStatsMonitor().resetOutboundRtpStats()}_resetRecvUsageStats(){Ve.getRecvStatsMonitor().resetInboundRtpStats()}_resetLayersAllocation(){this.pendingLayersUpdate=Promise.resolve(),this.requestedLayerIds=[],this.additionalSubLayerIds=[],this.layersAllocation=[],this.layersAllocationCache=null}_resetLossDetection(){this.receiverStats.clear(),this.minOutgoingBitrateAdjustments.clear(),this.receiverReport=null,this.residualLossDetectedTimestamp=0,this.inherentLossDetectedTimestamp=0,this.minOutgoingBitrateUpdatedTime=0}_resetBandwidthState(){this._stopReceiverBandwidthUpdateWait(),this._resetReceiverBandwidth(),this.outgoingBitrateStats.clear(),this.minOutgoingBitrate=We,this.outgoingBandwidth=1/0,this.isDualCall=!0}resetSendUsageState(){this.feasibleFormatIndex=-1,this.sendUsageStateHistory.clear(),this.sendUsageAdjustments.clear(),this.sendUsageIncreaseFailedAttempts=0,this.sendUsageIncreaseFailedTime=0,this._resetSendUsageStats()}resetRecvUsageState(){this.maxFeasibleRecvSize=T,this.recvUsageStateHistory.clear(),this.recvUsageAdjustments.clear(),this.recvUsageIncreaseFailedAttempts=0,this.recvUsageIncreaseFailedTime=0,this._resetRecvUsageStats()}resetSend(){this.sendActive=!1,this.sendActivatedTime=0,this.videoSourceLive=!1,this.videoSourceLiveTime=0,this._resetLayersAllocation(),this._resetLossDetection(),this._resetBandwidthState(),this.resetSendUsageState()}resetRecv(){this.maxSubVideoSize=-1,this.resetRecvUsageState()}registerMessageCallback(e){this.messageCallback=e}registerMaxRecvVideoSizeUpdateCallback(e){this.maxRecvVideoSizeUpdateCallback=e}registerSendUsageStateUpdateCallback(e){this.sendUsageStateUpdateCallback=e}setOptions(e){const{outgoingBandwidthAdaptationEnabled:t,outgoingBandwidthProbingEnabled:i,receiverBandwidthAdaptationEnabled:s,lossDetectionEnabled:a,performanceAdaptationEnabled:n}=e||{};void 0!==t&&(this.outgoingBandwidthAdaptationEnabled=t),void 0!==i&&(this.outgoingBandwidthProbingEnabled=i),void 0!==s&&(this.receiverBandwidthAdaptationEnabled=s),void 0!==a&&(this.lossDetectionEnabled=a),void 0!==n&&(this.performanceAdaptationEnabled=n)}setVideoSourceLiveState(e){this.videoSourceLive!==e&&(this.videoSourceLive=e,this.videoSourceLiveTime=e?Date.now():0)}setMaxEncodingLayers(e){this.maxEncodingLayers=e}setMaxEncodingFramerate(e){Ve.setOptions({maxEncodingFramerate:e})}setVideoStartBandwidth(e){if(this.videoStartBandwidth=e,this.outgoingBandwidthAdaptationEnabled){const t=e+this.audioBandwidth;xe("WMSC_Set_Start_Bandwidth: ".concat(t)),this.outgoingBandwidth=t}}getStartBandwidth(){return this.videoStartBandwidth+this.audioBandwidth}setAudioBandwidth(e){this.audioBandwidth!==e&&(xe("WMSC_Set_Audio_Bandwidth: ".concat(e)),this.audioBandwidth=e,this.allocateBitrate(this._getAvailableBitrate(),Ge.OutgoingBandwidth))}start(e){const t=pe();this.maxFormatIndex=t[t.length-1].formatIndex,this.maxEncodeBitrate=ye(ve()).maxBitrate,e&&this.setOptions(e),(0,de.gm)()&&(this.outgoingBandwidthFromServer=!0);const i={};this.performanceAdaptationEnabled&&(i.sendUsageStatsEnabled=!0,i.recvUsageStatsEnabled=!0),Ve.start(i)}stop(){Ve.stop(),this.resetSend(),this.resetRecv()}_queueLayersUpdate(e){return this.pendingLayersUpdate=this.pendingLayersUpdate.then((()=>e())).catch((e=>{te.globalTrace({logLevel:"error",log:e.message,tags:["WMSC_Update_Layers"]})})),this.pendingLayersUpdate}updateLayers(e){Ue.log("updateLayers, ".concat(e)),this.requestedLayerIds=this.isDualCall&&e.length>1?e.slice(-1):[...e],this._setSendState(!!e.length),this.allocateBitrate(this._getAvailableBitrate(),Ge.User)}_setSendState(e){this.sendActive!==e&&(this.sendActive=e,!e&&this.lossDetectionEnabled&&this._resetLossDetection())}updateMaxSubVideoSize(e){this.maxSubVideoSize=e}getMaxFeasibleRecvVideoSize(){return this.maxFeasibleRecvSize}_resetReceiverBandwidth(){this.receiverBandwidthReport=null,this.receiverL3BandwidthEvaluation=null}_waitBeforeReceiverBandwidthUpdate(){this.receiverBandwidthUpdatePending=!0,clearTimeout(this.receiverBandwidthUpdateTimeoutId),this.receiverBandwidthUpdateTimeoutId=setTimeout((()=>{this.receiverBandwidthUpdatePending=!1}),Qe.receiverBandwidthUpdateDelay)}_stopReceiverBandwidthUpdateWait(){clearTimeout(this.receiverBandwidthUpdateTimeoutId),this.receiverBandwidthUpdateTimeoutId=null,this.receiverBandwidthUpdatePending=!1}getMinBandwidth(){return this.minOutgoingBitrate}onOutgoingBandwidthStats(e){if(this.outgoingBandwidthFromServer||!this.outgoingBandwidthAdaptationEnabled||!this.sendActive)return;const{availableOutgoingBitrate:t=1/0,timestamp:i}=e;this.outgoingBitrateStats.push({availableOutgoingBitrate:t,timestamp:i}),this._updateOutgoingBandwidth(t)}onResourceUsageStats(e){e.send&&this.sendActive&&this._handleSendUsageStats(e.send),e.recv&&this._handleRecvUsageStats(e.recv)}_handleSendUsageStats(e){this.performanceAdaptationEnabled&&this._handleSendPerformanceStats(e)}_handleRecvUsageStats(e){this.performanceAdaptationEnabled&&this._handleRecvPerformanceStats(e)}_handleSendPerformanceStats(e){var t,i;const{usageState:s,framesEncoded:a,encodeTimestamp:n,timestamp:o}=e,r=this.sendUsageStateHistory.back(),c=(null===(t=this.sendUsageAdjustments.back())||void 0===t?void 0:t.time)||0,{UNDERUSING:d,OVERUSING:h}=C,l=this.layersAllocation.reduce(((e,t)=>Math.min(e,t.format.formatIndex)),this.maxFormatIndex);let u=je.None;null===(i=this.sendUsageStateUpdateCallback)||void 0===i||i.call(this,s,l);const m=o-Qe.encodingTimeout;if(this.videoSourceLiveTime&&this.videoSourceLiveTime<m&&this.sendActivatedTime&&this.sendActivatedTime<m&&(0===a||o-n>=Qe.encodingTimeout)){const e=(this.failedEncodings.get(l)||0)+1;this.failedEncodings.set(l,e),Fe("Encoding timed out ".concat(e," times for format ").concat(l)),u=je.Decrease}else r&&r.timestamp>c&&r.usageState===s&&(s===h?x.isMacIntel||(u=je.Decrease):s===d&&(u=je.Increase));this.sendUsageStateHistory.push({usageState:s,timestamp:o}),this._maybeAdjustMaxSendSize(l,u)&&(xe("WMSC_VEnc_Cap_Change: ".concat(this.feasibleFormatIndex)),this.allocateBitrate(this._getAvailableBitrate(),Ge.Other))}_handleRecvPerformanceStats(e){var t;const{usageState:i,maxVideoSize:s,maxVideoSizeFrameDropRate:a,timestamp:n}=e,o=this.recvUsageStateHistory.back(),r=(null===(t=this.recvUsageAdjustments.back())||void 0===t?void 0:t.time)||0,{UNDERUSING:c,OVERUSING:d}=C;let h=je.None;var l;a>Qe.decodingFrameDropRateLimit?(Fe("Decoding frames dropped ".concat(a.toFixed(2)," for video size ").concat(s)),h=je.Decrease):o&&o.timestamp>r&&o.usageState===i&&(i===d?h=je.Decrease:i===c&&(h=je.Increase)),this.recvUsageStateHistory.push({usageState:i,timestamp:n}),this._maybeAdjustMaxRecvSize(s,h)&&(xe("WMSC_VDec_Cap_Change: ".concat(this.maxFeasibleRecvSize)),null===(l=this.maxRecvVideoSizeUpdateCallback)||void 0===l||l.call(this,this.maxFeasibleRecvSize))}_maybeAdjustMaxSendSize(e,t){const i=Date.now();let s=-1;if(t===je.Decrease){if(e<this.maxFormatIndex){const t=this.sendUsageAdjustments.back();t&&t.layerChange!==je.Increase||(this.sendUsageIncreaseFailedAttempts++,this.sendUsageIncreaseFailedTime=i,Fe("Attempt to increase layer failed ".concat(this.sendUsageIncreaseFailedAttempts," times"))),s=e+1}}else if(t===je.Increase){const t=Math.min(Qe.resourceUsageIncreaseMaxAttempts-1,this.sendUsageIncreaseFailedAttempts);if(this.feasibleFormatIndex>=0&&e>0&&i-this.sendUsageIncreaseFailedTime>=Qe.resourceUsageIncreaseInitialDelay*Math.pow(2,t-1)){const t=Math.min(this.feasibleFormatIndex,e-1);(this.failedEncodings.get(t)||0)<Qe.encodingFailMaxRetries&&(s=t)}}return s>=0&&this.feasibleFormatIndex!==s&&(this.feasibleFormatIndex=s,this.sendUsageAdjustments.push({layerChange:t,time:i}),!0)}_maybeAdjustMaxRecvSize(e,t){const i=Date.now();let s=-1;if(t===je.Decrease){if(e>T){const t=this.recvUsageAdjustments.back();t&&t.layerChange!==je.Increase||(this.recvUsageIncreaseFailedAttempts++,this.recvUsageIncreaseFailedTime=i,Fe("Attempt to increase receive size failed ".concat(this.recvUsageIncreaseFailedAttempts," times"))),s=e-1}}else if(t===je.Increase){const t=Math.min(Qe.resourceUsageIncreaseMaxAttempts-1,this.recvUsageIncreaseFailedAttempts);e===this.maxFeasibleRecvSize&&i-this.recvUsageIncreaseFailedTime>=Qe.resourceUsageIncreaseInitialDelay*Math.pow(2,t-1)&&(s=e+1)}return s>=0&&this.maxFeasibleRecvSize!==s&&(this.maxFeasibleRecvSize=s,this.recvUsageAdjustments.push({layerChange:t,time:i}),!0)}onSubInfo(e){const{isDualCall:t}=e;this.onDualCallState(t)}onDualCallState(e){this.isDualCall!==e&&(this.isDualCall=e,xe("WMSC_Dual_Call_State_Changed: ".concat(e)),e?(this._resetReceiverBandwidth(),this._waitBeforeReceiverBandwidthUpdate()):this._stopReceiverBandwidthUpdateWait())}isSingleLayerMode(){return 1===this.maxEncodingLayers||this.isDualCall}_evaluateBandwidthDistribution(e,t,i){const s=i.reduce(((e,t)=>e+t),0),a=Qe.receiverBandwidthUseRatio,n=Math.floor(t*a),o=function(e){var t;return(null===(t=Me(e))||void 0===t?void 0:t.minBitrate)||0}(e),r=Ee(e)*Qe.adequateQualityBitrateRatio;let c=0,d=0,h=0;if(n>=r)d=s,h=n;else if(s>0){let e=0,n=0,l=0,u=0,m=0,p=0,g=0;for(let c=i.length-1;c>=0;c--){const d=i[c];d&&(g=g?512*c:t,g>=o&&(e=c,n+=d),g*a>=r&&(l=c,u+=d),p||(m/s<.6?m+=d:p=c))}p<l&&(m-u)/s<.2?(c=l,d=u):p>e?(c=p,d=m):(c=e,d=n),h=d?Math.floor(Math.max(t,512*c)*a):0}else h=r;return{selectedBandwidth:h,selectedAll:h<=n}}onReceiverBandwidthReport(e){if(!this.receiverBandwidthAdaptationEnabled||this.receiverBandwidthUpdatePending)return;const{minBW:t,minL3BW:i}=e;let s=!1;if(this.receiverBandwidthReport&&this.receiverBandwidthReport.minBw===t||(s=!0),this.receiverBandwidthReport={minBw:t,minL3Bw:i},!this.isDualCall&&_e(3)){const{selectedBandwidth:e,selectedAll:t}=this.receiverL3BandwidthEvaluation||{};this.receiverL3BandwidthEvaluation=this._evaluateBandwidthDistribution(3,i,[]),this.receiverL3BandwidthEvaluation.selectedAll===t&&this.receiverL3BandwidthEvaluation.selectedBandwidth===e||(s=!0)}this.sendActive&&s&&this.allocateBitrate(this._getAvailableBitrate(),Ge.ReceiverBandwidth)}onReceiverReport(e){if(!this.outgoingBandwidthAdaptationEnabled||!this.sendActive)return;if(e.frameStats&&(this.framingDelayStats.push(e.frameStats),this._maybeUpdateMaxEncodeBitrate()),!this.receiverReport)return void(this.receiverReport=e);const{recvPkts:t,preMissingPkts:i,postMissingPkts:s,maxJitterMs:a,maxSeqGap:n,timestampMs:o}=e,r=this.receiverReport,c=t-r.recvPkts,d=i-r.preMissingPkts,h=s-r.postMissingPkts,l=d+c,u={loss:l>0?d/l:0,residualLoss:l>0?h/l:0,jitter:a,sequenceGap:n,timestamp:o};this.receiverStats.push(u),this.receiverReport=e,"udp"===Ve.getSendStatsMonitor().getNetworkProtocol()&&this.lossDetectionEnabled&&this._updateOutgoingBandwidth(this._adjustOutgoingBandwidthForLoss(this.outgoingBandwidth))}onQosReport(e){var t;if(this.outgoingBandwidthFromServer&&null!==(t=e.uplink)&&void 0!==t&&t.bw){const t=1e3*e.uplink.bw;this.outgoingBandwidth!==t&&this._updateOutgoingBandwidth(t)}}_getDecreaseBitrateWindow(e){return e<=Qe.maxAllowedFramingDelay?Qe.maxFramingDelayWindowSize:e>=Qe.maxFramingDelay?Qe.minFramingDelayWindowSize:Math.round(Qe.maxFramingDelayWindowSize-(e-Qe.maxAllowedFramingDelay)/(Qe.maxFramingDelay-Qe.maxAllowedFramingDelay)*(Qe.maxFramingDelayWindowSize-Qe.minFramingDelayWindowSize))}_getIncreaseBitrateWindow(e){return e>=Qe.minAllowedFramingDelay?Qe.maxFramingDelayWindowSize:e<=Qe.minFramingDelay?Qe.minFramingDelayWindowSize:Math.round(Qe.minFramingDelayWindowSize+(e-Qe.minFramingDelay)/(Qe.minAllowedFramingDelay-Qe.minFramingDelay)*(Qe.maxFramingDelayWindowSize-Qe.minFramingDelayWindowSize))}_maybeUpdateMaxEncodeBitrate(){const e=this.framingDelayStats.unwrap(),t=this.framingDelayStats.count;let i=0,s=0;const{avgFrameDelay:a,avgPacketsPerFrameTenth:n}=e[t-1];this.increaseBitrateWindow=this._getIncreaseBitrateWindow(a),this.decreaseBitrateWindow=this._getDecreaseBitrateWindow(a);for(let a=t-1;a>=0;a--){const{avgFrameDelay:n}=e[a];t-a<=this.decreaseBitrateWindow&&n>Qe.maxAllowedFramingDelay&&i++,n<Qe.minAllowedFramingDelay&&t-a<=this.increaseBitrateWindow&&s++}const o=this._getMaxEncodeBitrate(i,s,n);return o!==this.maxEncodeBitrate&&(this.maxEncodeBitrate=o,this.allocateBitrate(this._getAvailableBitrate(),Ge.Other),this.framingDelayStats.clear(),xe("WMSC_ENBT-".concat(a,"-").concat(this.increaseBitrateWindow,"-").concat(this.decreaseBitrateWindow,"-").concat(i,"-").concat(s,"-").concat(o,"-").concat(n)),!0)}_getMaxEncodeBitrate(e,t,i){let s=this.maxEncodeBitrate;if(e/this.decreaseBitrateWindow>=this.decreaseBitrateRate&&Math.round(i/10)>1){const e=.3-(this.decreaseBitrateWindow-Qe.minFramingDelayWindowSize)/(Qe.maxFramingDelayWindowSize-Qe.minFramingDelayWindowSize)*.2,{targetBitrate:t}=ye(2);s=Math.max(Math.round((1-e)*(this.currentMaxEncodeBitrate||s)),t)}else if(t/this.increaseBitrateWindow>=this.increaseBitrateRate){const e=.3-(this.increaseBitrateWindow-Qe.minFramingDelayWindowSize)/(Qe.maxFramingDelayWindowSize-Qe.minFramingDelayWindowSize)*.25,{maxBitrate:t}=ye(ve());s=Math.min(Math.round((1+e)*s),t)}return s}_getReceiverMinBandwidth(){return this.receiverBandwidthReport?Math.floor(this.receiverBandwidthReport.minBw*Qe.receiverBandwidthUseRatio):1/0}_getSelectedL3Bandwidth(){return this.receiverL3BandwidthEvaluation?this.receiverL3BandwidthEvaluation.selectedBandwidth:1/0}_getOutgoingBandwidthHistory(e){if(this.outgoingBitrateStats.empty())return[];const t=this.outgoingBitrateStats.unwrap(),i=t[t.length-1].timestamp-e;let s=0;for(let e=t.length-1;e>=0;e--)if(t[e].timestamp<i){s=e+1;break}return t.slice(s).map((e=>e.availableOutgoingBitrate))}_getSubLayersForLayer(e){const t=ge(),i=[];if(3===e){var s;if(null===(s=this.receiverL3BandwidthEvaluation)||void 0===s||!s.selectedAll)for(const s of t)s<e&&i.push(s);return i}if(e<3)for(const s of t)s<e&&i.push(s);return i}_maybeUpdateSubLayers(){if(!this.receiverBandwidthAdaptationEnabled||!this.additionalSubLayersEnabled||this.receiverBandwidthUpdatePending)return!1;const e=[];return this.isSingleLayerMode()||this.requestedLayerIds.forEach((t=>{this._getSubLayersForLayer(t).forEach((t=>{this.requestedLayerIds.includes(t)||e.includes(t)||e.push(t)}))})),!Y(this.additionalSubLayerIds,e)&&(this.additionalSubLayerIds=e,!0)}_getAvailableBitrate(){return this.outgoingBandwidthAdaptationEnabled?Math.max(0,this.outgoingBandwidth-this.audioBandwidth):1/0}_updateOutgoingBandwidth(e){this.outgoingBandwidth=e,this.allocateBitrate(this._getAvailableBitrate(),Ge.OutgoingBandwidth)}_updateLayersMaxBitrate(e){e.forEach(((t,i)=>{const{outgoingBitrate:s,receiverBandwidth:a,skipReceiverBandwidthLimit:n,format:o}=t,r=i===e.length-1?s:Math.min(o.maxBitrate,1e3*Math.ceil(s*(4/3)/1e3));t.maxBitrate=n?r:Math.min(r,a)}))}_detectInherentLoss(e){const t=e.findIndex((e=>e.timestamp>this.inherentLossDetectedTimestamp&&e.loss));if(e.length-t>=Qe.inherentLossDetectionMinDataPoints){const i=e.slice(t).map((e=>e.loss)),s=i.length?Be.mean(i):0;if(s>=Qe.lossThresholdLow&&s<Qe.lossThresholdHigh){const e=Be.variance(i);if(Ue.log("loss ratios: ".concat(i,", mean: ").concat(s,", variance: ").concat(e)),e<Qe.inherentLossVarianceThresholdHigh)return t}}return-1}_detectOutOfOrder(e){const t=e.findIndex((e=>e.timestamp>this.inherentLossDetectedTimestamp&&e.sequenceGap));if(e.length-t>=Qe.outOfOrderDetectionMinDataPoints){const i=e.slice(t).map((e=>e.sequenceGap)),s=Be.mean(i);if(s>=Qe.sequenceGapThresholdLow&&s<Qe.sequenceGapThresholdHigh)return Ue.log("sequence gaps: ".concat(i,", mean: ").concat(s)),t}return-1}_isOutgoingBandwidthNormal(e){return e>=Math.max(Qe.minOutgoingBitrateThresholdLow,this.minOutgoingBitrate*Qe.outgoingBitrateFactorThresholdNormalState)}_adjustOutgoingBandwidthForLoss(e){e<this.minOutgoingBitrate&&(e=this.minOutgoingBitrate),this._isOutgoingBandwidthNormal(e)&&this.minOutgoingBitrateAdjustments.clear();const t=this.receiverStats.unwrap(),{residualLoss:i,timestamp:s}=t[t.length-1],a=t.findIndex((e=>e.loss)),n=t.slice(a).map((e=>e.loss)),o=n.length?Be.mean(n):0;if(i&&Ue.log("residual loss: ".concat(i,", mean loss: ").concat(o)),i>=Qe.residualLossThresholdMedium){this.residualLossDetectedTimestamp=s;const t=i>=Qe.residualLossThresholdHigh?Qe.residualLossBitrateFastDecreaseFactor:Qe.residualLossBitrateDecreaseFactor;return this._decreaseOutgoingBitrate(Math.floor(e*t))}if(i>=o*Qe.residualLossRatioThresholdLow){const i=t.findIndex((e=>e.timestamp>this.residualLossDetectedTimestamp));if(t.reduce(((e,t,a)=>a>=i&&t.residualLoss&&s-t.timestamp<=Qe.residualLossMonitorTimeWindow?e+1:e),0)>=Qe.residualLossCountThreshold)return this.residualLossDetectedTimestamp=s,this._decreaseOutgoingBitrate(Math.floor(e*Qe.residualLossBitrateDecreaseFactor))}if(this.residualLossDetectedTimestamp&&s-this.residualLossDetectedTimestamp<Qe.outgoingBitrateIncreaseSuppressionIntervalResidualLoss)return e;const r=this._getOutgoingBitrateDemand();if(e>=r)return e;let c=-1;if(c=this._detectInherentLoss(t),-1===c&&(c=this._detectOutOfOrder(t)),-1!==c&&s-this.inherentLossDetectedTimestamp>=Qe.inherentLossDetectionMinInterval){const i=this._getOutgoingBandwidthHistory(s-t[c].timestamp+1500);if(i.length>=Qe.inherentLossDetectionMinDataPoints){const t=Be.bestFitSlope(i),a=i[0];if(t<Qe.outgoingBitrateMaxSlopeRestoreBandwidth&&a>=e*Qe.outgoingBitrateMinFactorRestoreBandwidth)return Ue.log("bandwidth: ".concat(a," -> ").concat(e,", slope: ").concat(t)),this._maybeIncreaseMinOutgoingBitrate(Math.min(r,a)),this.inherentLossDetectedTimestamp=s,e}if(e<Qe.minOutgoingBitrateThresholdMedium)return this._maybeIncreaseMinOutgoingBitrate(Math.min(Qe.minOutgoingBitrateThresholdMedium,r,Math.floor(e*Qe.minOutgoingBitrateIncreaseFactor))),this.inherentLossDetectedTimestamp=s,e}return e}_decreaseOutgoingBitrate(e){return e=Math.max(We,e),this._maybeDecreaseMinOutgoingBitrate(e),e}_maybeIncreaseMinOutgoingBitrate(e){return!(this.minOutgoingBitrateAdjustments.unwrap().slice(-3).filter((e=>e===ze.Decrease)).length>=2)&&(this.minOutgoingBitrateAdjustments.push(ze.Increase),this._adjustMinOutgoingBitrate(Math.max(Qe.minOutgoingBitrateThresholdLow,Math.min(Qe.minOutgoingBitrateThresholdHigh,e))))}_maybeDecreaseMinOutgoingBitrate(e){if(e<this.minOutgoingBitrate){this.minOutgoingBitrateAdjustments.push(ze.Decrease);const t=this.minOutgoingBitrate<=Qe.minOutgoingBitrateThresholdLow?We:Math.max(We,Math.min(e,Math.floor(this.minOutgoingBitrate*Qe.minOutgoingBitrateLeastDecreaseFactor)));return this._adjustMinOutgoingBitrate(t)}return!1}async _adjustMinOutgoingBitrate(e){Ue.log("adjust min bitrate: ".concat(this.minOutgoingBitrate," -> ").concat(e));const t=Date.now();if(t-this.minOutgoingBitrateUpdatedTime<Qe.minOutgoingBitrateUpdateMinInterval)return;const i=1e3*Math.floor(e/1e3);if(i!==this.minOutgoingBitrate){Ue.log("update min bitrate: ".concat(this.minOutgoingBitrate," -> ").concat(i)),this.minOutgoingBitrateUpdatedTime=t;try{var s;return await(null===(s=this.messageCallback)||void 0===s?void 0:s.call(this,{type:M.MIN_BITRATE_UPDATE,data:i})),this.minOutgoingBitrate=i,!0}catch(e){return Ue.error("update min bitrate error: ".concat(e.message)),!1}}return!1}async _updateLayersAllocation(e){try{var t;return await(null===(t=this.messageCallback)||void 0===t?void 0:t.call(this,{type:M.LAYERS_UPDATE,data:e})),!0}catch(e){return Ue.error("update layers allocation error: ".concat(e.message)),!1}}async _sendLastLayersAllocation(){if(!this.layersAllocationCache)return;const{outgoingBandwidth:e,receiverBandwidthReport:t,availableBitrate:i,layerIds:s,layersAllocation:a,reason:n,priority:o,timestamp:r}=this.layersAllocationCache;if(o>=He.High||!Qe.areLayersAllocationsEqual(this.layersAllocation,a)){const{minBw:o,minL3Bw:d}=t,h="WMSC_Update_Layers_Allocation, reason: ".concat(n)+", bandwidth: S ".concat(e,",").concat(i,", R ").concat(o,",").concat(d)+", layers: ".concat(s,", ").concat(a.map((e=>{let{layerId:t,maxBitrate:i,format:s}=e;return"{".concat(t,",").concat(s.width,",").concat(i,"}")})).join(","));var c;xe(X(h)),await this._updateLayersAllocation(a)&&(!this.layersAllocation.length&&a.length?this.sendActivatedTime=Date.now():this.layersAllocation.length&&!a.length&&(this.sendActivatedTime=0),(null===(c=this.layersAllocationCache)||void 0===c?void 0:c.timestamp)===r&&(this.layersAllocationCache=null),this.layersAllocation=a)}}_getReceiverBandwidth(e){let t=1/0;return this.isSingleLayerMode()?t=this._getReceiverMinBandwidth():3===e&&(t=this._getSelectedL3Bandwidth()),t}_getAdjustedTargetBitrate(e){const t=Ee(e),i=this._getReceiverBandwidth(e);return Math.min(t,i)}_getAdjustedMaxBitrate(e){const t=Ie(e),i=this._getReceiverBandwidth(e);return Math.min(t,i)}_getSendLayerIds(){var e;return h()(e=[...this.additionalSubLayerIds,...this.requestedLayerIds]).call(e)}_getTotalMaxBitrate(e){let t=0;for(let i=0;i<e.length;i++)i===e.length-1?t+=this._getAdjustedMaxBitrate(e[i]):t+=this._getAdjustedTargetBitrate(e[i]);return t}_getOutgoingBitrateDemand(){const e=this._getSendLayerIds();return this._getTotalMaxBitrate(e)}_allocateBitrateToLayers(e,t){var i;const s=ge(),a=s[0],n=Math.max(0,this.feasibleFormatIndex),o=[];let r=e,c=-1;const d=(e,t)=>{if(o.length>=this.maxEncodingLayers)return!1;const i=this._getReceiverBandwidth(e),s=function(e){var t,i;return null!==(i=null===(t=pe())||void 0===t?void 0:t.filter((t=>t.layerId===e)))&&void 0!==i?i:[]}(e);for(const a of s){const{minBitrate:s,targetBitrate:d,maxBitrate:h,formatIndex:l}=a;if(r<s||!t&&i<s||this.maxEncodeBitrate<s||l<n)continue;const u=Math.min(d,this.maxEncodeBitrate);return!((0,de.gm)()&&(i<h||this.maxEncodeBitrate<h)||(o.push({layerId:e,outgoingBitrate:u,receiverBandwidth:i,skipReceiverBandwidthLimit:t,format:a}),r-=u,c=e,0))}return!1};for(const e of t){const t=this.additionalSubLayerIds.includes(e);if(!d(e,t)){const i=-1===c?a:c+1;for(let a=e-1;a>=i&&s.includes(a)&&!d(a,t);a--);break}}if(o.length){const e=o[o.length-1];e.outgoingBitrate=Math.min(e.format.maxBitrate,this.maxEncodeBitrate)}else if(t.length){const e=Me(a);o.push({layerId:a,outgoingBitrate:e.minBitrate,receiverBandwidth:this._getReceiverBandwidth(a),skipReceiverBandwidthLimit:!0,format:e})}return this._updateLayersMaxBitrate(o),this.currentMaxEncodeBitrate=null===(i=o[o.length-1])||void 0===i?void 0:i.maxBitrate,o}_reallocateBitrateToLayers(e,t,i){let s=0,a=0,n=0,o=!1;const r=[];return t.forEach(((e,i)=>{n+=i===t.length-1?Ie(e):Ee(e)})),i.forEach(((e,t)=>{const{layerId:n,outgoingBitrate:c,receiverBandwidth:d,skipReceiverBandwidthLimit:h,format:l}=e,u=t===i.length-1,m=this._getReceiverBandwidth(n);if(u){if((!h&&m<l.minBitrate||d<=l.maxBitrate&&m>l.maxBitrate)&&(o=!0),(0,de.gm)()){const e=fe(l.formatIndex-1);(e&&m>e.maxBitrate||m<l.maxBitrate)&&(o=!0)}s+=l.minBitrate,a+=c}else!h&&m<l.minBitrate&&(o=!0),s+=c,a+=c;r.push({layerId:n,outgoingBitrate:c,receiverBandwidth:m,skipReceiverBandwidthLimit:h,format:l})})),!o&&(e>=n||e>=s&&e<=a)?(this._updateLayersMaxBitrate(r),r):this._allocateBitrateToLayers(e,t)}allocateBitrate(e,t){var i;const s=Qe.getLayersChangePriority(t),a=this._maybeUpdateSubLayers(),n=this._getSendLayerIds(),o=(null===(i=this.layersAllocationCache)||void 0===i?void 0:i.layersAllocation)||this.layersAllocation;let r;r=a||!o.length||t!==Ge.OutgoingBandwidth&&t!==Ge.ReceiverBandwidth?this._allocateBitrateToLayers(e,n):this._reallocateBitrateToLayers(e,n,o);const c={outgoingBandwidth:this.outgoingBandwidth,receiverBandwidthReport:ke({},this.receiverBandwidthReport),availableBitrate:e,layerIds:n,layersAllocation:r,reason:t,priority:s,timestamp:performance.now()};return this.layersAllocationCache&&(c.priority=Math.max(s,this.layersAllocationCache.priority)),this._updateLayersForBandwidthProbing(c),this.layersAllocationCache=c,this._queueLayersUpdate((async()=>{await this._sendLastLayersAllocation()}))}_updateLayersForBandwidthProbing(e){const{layersAllocation:t,availableBitrate:i}=e,s=Date.now();if(!this.outgoingBandwidthProbingEnabled||i>=Qe.outgoingBitrateThresholdProbing||s-this.outgoingBandwidthProbingScheduledTime<Qe.outgoingBandwidthProbingMinInterval||1!==t.length)return;const{layerId:a,maxBitrate:n}=t[0],o=Math.floor(1.1*this.outgoingBandwidth);a!==Se()||n>this.outgoingBandwidth||o>this._getReceiverBandwidth(a)||(t[0].maxBitrate=o,this.outgoingBandwidthProbingScheduledTime=s)}}(0,c.A)(Qe,"resourceUsageStateHistorySize",6),(0,c.A)(Qe,"resourceUsageAdjustmentHistorySize",6),(0,c.A)(Qe,"resourceUsageIncreaseInitialDelay",6e4),(0,c.A)(Qe,"resourceUsageIncreaseMaxAttempts",6),(0,c.A)(Qe,"encodingTimeout",2e3),(0,c.A)(Qe,"encodingFailMaxRetries",2),(0,c.A)(Qe,"decodingFrameDropRateLimit",.95),(0,c.A)(Qe,"outgoingBitrateStatsCacheSize",8),(0,c.A)(Qe,"receiverBandwidthUseRatio",.9),(0,c.A)(Qe,"receiverBandwidthUpdateDelay",1500),(0,c.A)(Qe,"adequateQualityBitrateRatio",.6),(0,c.A)(Qe,"outgoingBitrateThresholdProbing",2e5),(0,c.A)(Qe,"outgoingBandwidthProbingMinInterval",1e4),(0,c.A)(Qe,"lossThresholdLow",.08),(0,c.A)(Qe,"lossThresholdHigh",.6),(0,c.A)(Qe,"receiverStatsCacheSize",6),(0,c.A)(Qe,"minOutgoingBitrateAdjustmentHistorySize",5),(0,c.A)(Qe,"outgoingBitrateFactorThresholdNormalState",1.5),(0,c.A)(Qe,"outgoingBitrateMaxSlopeRestoreBandwidth",-1e5),(0,c.A)(Qe,"outgoingBitrateMinFactorRestoreBandwidth",1.5),(0,c.A)(Qe,"outgoingBitrateIncreaseSuppressionIntervalResidualLoss",15e3),(0,c.A)(Qe,"minOutgoingBitrateUpdateMinInterval",900),(0,c.A)(Qe,"minOutgoingBitrateThresholdLow",25e4),(0,c.A)(Qe,"minOutgoingBitrateThresholdMedium",1e6),(0,c.A)(Qe,"minOutgoingBitrateThresholdHigh",2e6),(0,c.A)(Qe,"minOutgoingBitrateLeastDecreaseFactor",.8),(0,c.A)(Qe,"minOutgoingBitrateIncreaseFactor",1.15),(0,c.A)(Qe,"residualLossRatioThresholdLow",.05),(0,c.A)(Qe,"residualLossThresholdMedium",.05),(0,c.A)(Qe,"residualLossThresholdHigh",.15),(0,c.A)(Qe,"residualLossMonitorTimeWindow",6e3),(0,c.A)(Qe,"residualLossCountThreshold",2),(0,c.A)(Qe,"residualLossBitrateDecreaseFactor",.8),(0,c.A)(Qe,"residualLossBitrateFastDecreaseFactor",.64),(0,c.A)(Qe,"inherentLossDetectionMinDataPoints",3),(0,c.A)(Qe,"inherentLossDetectionMinInterval",3e3),(0,c.A)(Qe,"inherentLossVarianceThresholdHigh",.02),(0,c.A)(Qe,"outOfOrderDetectionMinDataPoints",3),(0,c.A)(Qe,"sequenceGapThresholdLow",10),(0,c.A)(Qe,"sequenceGapThresholdHigh",80),(0,c.A)(Qe,"maxAllowedFramingDelay",250),(0,c.A)(Qe,"minAllowedFramingDelay",150),(0,c.A)(Qe,"maxFramingDelay",600),(0,c.A)(Qe,"minFramingDelay",50),(0,c.A)(Qe,"maxFramingDelayWindowSize",16),(0,c.A)(Qe,"minFramingDelayWindowSize",5);const qe=new Qe;var Ye=i(5999);function Ke(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,s)}return i}function Je(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Ke(Object(i),!0).forEach((function(t){(0,c.A)(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Ke(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}const Xe=te.getTracer("WmscVideoMgr"),Ze=e=>{Xe.log(e),te.monitorLog("".concat(e))},$e=new class{constructor(){var e,t;this.videoPublished=!1,this.mediaRequested=!1,this.hdVideoEnabled=!1,this.maxEncodingFramerate=30,this.maxSendLayerId=4,this.sourceVideoSize=-1,this.sourceVideoSettings=null,this.pc=null,this.sendTransceiver=null,this.messageCallback=null,this.requestedLayerIds=[],this.sendLayerIds=[],this.encodingMap=new Map,this.recvCodecNum=0,this.sendCodecNum=0,this.senderCodec=null,this.isSupportHi444PP=!1,this.headerExtMap=new Map,this.egressCodecList=null,this.ingressCodecList=null,this.sendCBPPayloadType=0,this.recvHigh444PayloadType=0,this.recvMLineTemp=null,this.recvPreferCodecs=(null===(e=RTCRtpReceiver.getCapabilities("video"))||void 0===e||null===(e=e.codecs)||void 0===e?void 0:e.filter((e=>{let{mimeType:t,sdpFmtpLine:i}=e;if(-1!==t.indexOf("red")||-1!==t.indexOf("fec")||"video/rtx"===t)return!0;const s=i?i.toLowerCase():"";return!("video/H264"!==t||!s||-1===s.indexOf("packetization-mode=1")||(-1!==s.indexOf("profile-level-id=f400")&&(this.isSupportHi444PP=!0),this.recvCodecNum++,0))})))||[],null===(t=RTCRtpSender.getCapabilities("video"))||void 0===t||null===(t=t.codecs)||void 0===t||t.forEach((e=>{const{mimeType:t,sdpFmtpLine:i}=e;"video/H264"===t&&(this.sendCodecNum++,-1!==i.indexOf("profile-level-id=42")&&(!(0,de._J)()&&!(0,de.UP)()||(0,de.D)("124")||(this.senderCodec=e)))})),qe.registerMessageCallback(this.onQosMessage.bind(this))}getSendEncodings(e){switch(e){case 1:return[{rid:"0",active:!1}];case 2:return[{rid:"0",active:!1,scaleResolutionDownBy:2},{rid:"1",active:!1,scaleResolutionDownBy:1}];default:return[{rid:"0",active:!1,scaleResolutionDownBy:4},{rid:"1",active:!1,scaleResolutionDownBy:2},{rid:"2",active:!1,scaleResolutionDownBy:1}]}}getDefaultEncodingIndex(e){return e<=1?0:2===e?1:2}getDefaultEncodingIndexMap(e){return 1===e?new Map([[1,0],[2,0],[3,0],[4,0]]):2===e?new Map([[1,0],[2,1],[3,1],[4,1]]):new Map([[1,0],[2,1],[3,2],[4,2]])}getEncodingIndex(e){return this.layerEncodingIndexMap.get(e)}_configSimulcastLayers(e,t){this.numSimulcastLayers=e,this.layerEncodingIndexMap=t}setDefaultVideoSettings(e){!function(e){const t=e?le.filter((e=>{let{width:t,height:i}=e;return!((s={width:t,height:i}).width*s.height<57600);var s})):le;(0,de.gm)()&&t.forEach((e=>{var t;const{ffMinBitrate:i,ffMaxBitrate:s}=null!==(t=e.special)&&void 0!==t?t:{};i&&(e.minBitrate=i),s&&(e.targetBitrate=s,e.maxBitrate=s)})),ue(t)}((0,de.zQ)()&&x.isMacIntel||(0,de.GN)()),me([1,2,3]),this._configSimulcastLayers(e,this.getDefaultEncodingIndexMap(e)),this.onMediaRequest(this.requestedLayerIds)}setVideoSettings(e){var t;const{hdVideoEnabled:i,maxEncodingLayers:s,layersSettings:a}=e||{};if(this.enableHdVideo(i),s>0&&qe.setMaxEncodingLayers(s),null==a||!a.length)return void this.setDefaultVideoSettings(null!=s?s:3);const n=h()(a).call(a,((e,t)=>Math.min(t.width,t.height)-Math.min(e.width,e.height))),o=n.reduce(((e,t)=>Math.min(t.maxFramerate,e)),30);for(let e=0;e<n.length;e++){const{width:t,height:i,minBitrate:s,maxBitrate:a}=n[e],r=Re({width:t,height:i});n[e].layerId=r,n[e].maxFramerate=o,void 0===a&&(n[e].maxBitrate=Te(r,{width:t,height:i}),n[e].targetBitrate=n[e].maxBitrate),void 0===s&&(n[e].minBitrate=e>0?n[e-1].maxBitrate:6e4)}const r=new Map;n.forEach((e=>{const{layerId:t}=e,i=this.getDefaultEncodingIndex(t);r.get(t)?t.push(t):r.set(i,[t])}));const c=r.size,d=Array.from(r.keys()),l=new Map;for(let e=0;e<c;e++)r.get(d[e]).forEach((t=>{l.set(t,e)}));ue(n),me(h()(t=Array.from(l.keys())).call(t)),this._configSimulcastLayers(c,l),this.onMediaRequest(this.requestedLayerIds)}registerMessageCallback(e){this.messageCallback=e}getPc(){return this.pc}getSender(){var e;return null===(e=this.sendTransceiver)||void 0===e?void 0:e.sender}enableHdVideo(e){Ze("WMSC_Enable_HD_Video: ".concat(e)),this.hdVideoEnabled=e,this.onMediaRequest(this.requestedLayerIds)}setMaxEncodingFramerate(e){this.maxEncodingFramerate=e,Ze("WMSC_Max_Encode_Framerate: ".concat(e)),qe.setMaxEncodingFramerate(e),this._startVideo()}setMaxSendLayerId(e){this.maxSendLayerId=e,this.sendLayerIds=this._reduceRequestLayerIds(this.requestedLayerIds)}async publishVideoTrack(e,t){e&&qe.resetSendUsageState(),await this._replaceVideoTrack(e||null),this.updateVideoSourceSettings(t||null),this._onVideoPublished(!!e)}updateVideoSourceSettings(e){const t=(s=e,!(i=this.sourceVideoSettings)&&!s||!(!i||!s)&&(i.width===s.width&&i.height===s.height||i.width===s.height&&i.height===s.width));var i,s;if(this.sourceVideoSettings=e,!t)if(e){const{width:t,height:i,frameRate:s}=e;Ze("WMSC_Original_Video_Track: ".concat(t,"x").concat(i,"@").concat(s,"fps")),s&&qe.setMaxEncodingFramerate(s),this.sourceVideoSize=Re(e),this.onMediaRequest(this.requestedLayerIds)}else this._stopVideo()}async _replaceVideoTrack(e){const t=this.getSender(),i=e?"{ kind: ".concat(e.kind,", id: ").concat(e.id,", enabled: ").concat(e.enabled,", muted: ").concat(e.muted)+", contentHint: ".concat(e.contentHint," }"):"";if(Ze(X("WMSC_Replace_Video_Track: sender: ".concat(!!t," track: ").concat(i))),t)return t.replaceTrack(e)}_onVideoPublished(e){this.videoPublished=e,this.mediaRequested&&(e?this._startVideo():this._stopVideo())}_startVideo(){Xe.log("_startVideo"),qe.updateLayers(this.sendLayerIds)}_stopVideo(){Xe.log("_stopVideo"),qe.updateLayers([])}handlePcClose(){this.videoPublished=!1,this.sendTransceiver=null,this.pc=null}_reduceRequestLayerIds(e){var t;if(!e.length)return[];let i=[...e];1===this.numSimulcastLayers&&i.length>1&&(i=i.some((e=>e>=2))?[2]:[Math.max(...i)]);const s=new Map,a=Se(),n=ve(),o=Math.min(this.maxSendLayerId,this.sourceVideoSize,this.hdVideoEnabled?n:Math.min(2,n));return i.map((e=>{let t=Math.max(a,Math.min(o,e));for(;!_e(t);)--t;return t})).forEach((e=>{const t=this.getEncodingIndex(e),i=s.get(t);(void 0===i||e<i)&&s.set(t,e)})),h()(t=Array.from(s.values())).call(t)}onMediaRequest(e){const t=!!e.length;this.requestedLayerIds=[...e];const i=this._reduceRequestLayerIds(e);Ze(X("WMSC_New_Media_Request: layer ids: ".concat(JSON.stringify(e)," -> ").concat(JSON.stringify(i)))),this.sendLayerIds=i,this.mediaRequested!==t?(this.mediaRequested=t,this.videoPublished&&(t?this._startVideo():this._stopVideo())):this.videoPublished&&t&&qe.updateLayers(this.sendLayerIds)}async onQosMessage(e){switch(e.type){case M.LAYERS_UPDATE:return this.onLayersAllocationUpdate(e.data);case M.MIN_BITRATE_UPDATE:return this.updateMinOutgoingBitrate(e.data)}}async onLayersAllocationUpdate(e){this.encodingMap.clear(),e.forEach((e=>{const t=this.getEncodingIndex(e.layerId);this.encodingMap.set(t,e)})),await this._updateSendParameters()}async updateMinOutgoingBitrate(e){if(!this.pc)throw new Error("Egress peer connection has not been created");return Ze("WMSC_Update_Min_Bitrate: ".concat(e)),qe.resetSendStats(),new Promise(((t,i)=>{this.messageCallback({type:y.UPDATE_BITRATE,data:{bitrate:e,resolve:t,reject:i}})}))}updateMinOutgoingBitrateInSDP(e){this.pc&&he.updateCodecParameters(this.pc.answer,"video","recvonly","H264",new Map([["x-google-min-bitrate",Math.floor(e/1e3)]]))}async _updateSendParameters(){const e=this.getSender();if(null==e||!e.track||!this.sourceVideoSettings)return void Ze("WMSC_USPTNP: ".concat(!!e,"|").concat(!!this.sourceVideoSettings));const{width:t,height:i}=this.sourceVideoSettings,s=Math.max(t,i);let a="WMSC_Update_Send_Params:";const n=e.getParameters();n.encodings.forEach(((e,t)=>{const i=this.encodingMap.get(t);if(e.active=!!i,e.active){const{layerId:n,maxBitrate:o,format:r}=i,c=Math.max(1,s/Math.max(r.width,r.height));e.maxBitrate=o,e.scaleResolutionDownBy=c,e.maxFramerate=Math.min(this.sourceVideoSettings.frameRate,this.maxEncodingFramerate,function(e){var t;return(null===(t=ye(e))||void 0===t?void 0:t.maxFramerate)||0}(n)),a+=" index ".concat(t,": ").concat(n,",").concat(e.maxBitrate,",").concat(e.maxFramerate)+",".concat(e.scaleResolutionDownBy)}})),n.degradationPreference="maintain-resolution",Ze(X(a));try{await e.setParameters(n)}catch(e){return te.globalTrace({logLevel:"error",log:"WMSC_SETPARAMSE",errorEvent:e}),Ze("WMSC_SETPARAMSE"),Promise.reject(e)}}_getEgressRemoteCodecParams(){const e=qe.getStartBandwidth();return new Map([["x-google-per-layer-pli",1],["x-google-start-bitrate",Math.floor(e/1e3)]])}_getIngressLocalCodecParams(){return new Map([["sps-pps-idr-in-keyframe",1]])}removeRecvCodecByProfile(e){var t;const i=parseInt(e.substring(0,2),16);this.ingressCodecList=null===(t=this.ingressCodecList)||void 0===t?void 0:t.filter((e=>{let{codecName:t,codecParams:s}=e;return!("H264"===t&&parseInt(s.get("profile-level-id").substring(0,2),16)<=i)}))}init(e,t){this.pc=e,qe.resetRecv(),qe.resetSend(),this.addSendTransceiver();for(let e=0;e<t;e++)this.addRecvTransceiver()}addSendTransceiver(){if(!this.pc)throw new Error("Peer connection has not been created");return this.sendTransceiver=this.pc.createSendTransceiver(Ye.zu.MainVideo,{sendEncodings:this.getSendEncodings(this.numSimulcastLayers)}),this.sendTransceiver}addRecvTransceiver(){if(!this.pc)throw new Error("Peer connection has not been created");const e=this.pc.createRecvTransceiver(Ye.zu.MainVideo);try{let t=this.recvPreferCodecs;this.senderCodec&&(t=[...this.recvPreferCodecs,this.senderCodec]),this.recvCodecNum>0&&e.transceiver.setCodecPreferences(t)}catch(e){te.globalTrace({logLevel:"error",log:"WMSC_CODECPREFERENCE_ERROR",errorEvent:e}),Ze("WMSC_CPE")}return e}mungeLocalOffer(e){let t=!1;const i=this.headerExtMap.get("send"),s=this.headerExtMap.get("recv"),a=(0,de.zQ)()&&x.isMacIntel,n=(0,de.gm)();he.filterCodecs(e,((e,o)=>{const{type:r,direction:c}=o;if("video"!==r)return!0;t=!0;const{codecName:d,codecParams:h,payloadType:l}=e;if("flexfec-03"===d)return!0;if("H264"===d&&"1"===h.get("packetization-mode")){if("sendonly"===c){if(ee(h.get("profile-level-id")))this.sendCBPPayloadType=l;else if(a)return!1;this.pc&&!this.pc.currentRemoteDescription?this.headerExtMap.set("send",o.extensionMap):i&&(o.extensionMap=i)}else"recvonly"===c&&(n&&"42001f"===h.get("profile-level-id")&&h.set("profile-level-id","64001f"),$(h.get("profile-level-id"))&&(this.recvHigh444PayloadType=l),this.pc&&!this.pc.currentRemoteDescription?this.headerExtMap.set("recv",o.extensionMap):s&&(o.extensionMap=s));return!0}return!1})),t&&this.pc&&(he.mungeEgressLocalOffer(e,this.numSimulcastLayers,this.pc.mainEgressStreamId,!(0,de.gm)()&&!this.pc.answer),he.mungeIngressLocalOffer(e,this._getIngressLocalCodecParams()))}mungeAnswer(e){he.mungeEgressAnswer(e,this.numSimulcastLayers,this._getEgressRemoteCodecParams())}updateConfigFromSdp(e){const t=e.media.find((e=>"video"===e.type&&"recvonly"===e.direction));if(t){const e=he.getMediaStartBandwidth(t);e&&qe.setVideoStartBandwidth(e)}}saveRecvMLineTemp(){var e;const t=null===(e=this.pc)||void 0===e?void 0:e.answer.media.find((e=>{const{type:t,direction:i}=e||{};return"video"===t&&"sendonly"===i}));t&&(this.recvMLineTemp=Je({},t))}updateRecvMLineTemp(e){const{ice_pwd:t,ice_ufrag:i}=e;this.recvMLineTemp&&(this.recvMLineTemp.icePwd=t,this.recvMLineTemp.iceUfrag=i)}addRecvVideoSDP(e){if(!this.recvMLineTemp)throw new Error("No receive video m-line template");const{transceiver:t,msid:i,mediaType:s,ssrcs:a={},user_id:n}=e,{rtp:o,rtx:r,flexfec:c}=a,{mid:d}=t,h=o||he.generateSsrc(),l=r||he.generateSsrc(),u=c||he.generateSsrc(),m=i||he.generateUuid(),p=he.generateUuid();if(s===Ye.zu.MainVideo){var g;const e=Je({},this.recvMLineTemp);e.mid=d,e.msid={streamId:m,trackId:p},e.ssrcGroups=[{semantics:"FID",ssrcs:[h,l]},{semantics:"FEC-FR",ssrcs:[h,u]}],e.ssrcs=[{ssrc:h,attribute:"cname:".concat(m)},{ssrc:h,attribute:"msid:".concat(m," ").concat(p)},{ssrc:l,attribute:"cname:".concat(m)},{ssrc:l,attribute:"msid:".concat(m," ").concat(p)},{ssrc:u,attribute:"cname:".concat(m)},{ssrc:u,attribute:"msid:".concat(m," ").concat(p)}],null===(g=this.pc)||void 0===g||g.addMLineSDPToAnswer(d,e)}return{mid:d,media_type:s,msid:m,ssrcs:{rtp:h,rtx:l,flexfec:u},user_id:n}}saveCodecList(){var e;let t,i;null===(e=this.pc)||void 0===e||e.answer.media.some((e=>{const{type:s,direction:a}=e||{};return"video"===s&&"recvonly"===a?t=e:"video"===s&&"sendonly"===a&&(i=e),t&&i})),t&&(this.egressCodecList=[...t.codecs]),i&&(this.ingressCodecList=i.codecs.filter((e=>{let{codecName:t}=e;return"H264"===t})))}updateEgressAnswerCodec(e){if(this.egressCodecList&&this.pc){const t=this.pc.answer.media.find((e=>{const{type:t,direction:i}=e||{};return"video"===t&&"recvonly"===i}));let i,s=[];if(this.egressCodecList.forEach((t=>{const{codecName:a,codecParams:n,payloadType:o}=t;if(s.push(o),"H264"===a){const s=n.get("profile-level-id");e?ee(s)&&(i=t):Z(s)&&(i=t)}})),i){t.codecs=[i],t.payloadTypes=[i.payloadType];const e=this.egressCodecList.find((e=>{const{codecName:t,codecParams:s}=e;return"rtx"===t&&s.associatedPayloadType===i.payloadType}));e&&(t.codecs.push(e),t.payloadTypes.push(e.payloadType))}else t.codecs=this.egressCodecList,t.payloadTypes=s}}getRecvCodecPayloads(){const e=[];if(this.ingressCodecList){const t=Ae("recv");this.ingressCodecList.forEach((i=>{const{codecName:s,codecParams:a,payloadType:n}=i;if("H264"===s){const i=a.get("profile-level-id");e.length>0&&(t&&$(i)||!t&&Z(i))?(e.push(e[0]),e[0]=n):e.push(n)}}))}return e}getPreferPayloadTypes(e){const t=Ae(e);return"recv"===e&&t&&this.recvHigh444PayloadType?[this.recvHigh444PayloadType]:"send"===e&&t&&this.sendCBPPayloadType?[this.sendCBPPayloadType]:[]}},et=1,tt=2,it=3,st=4,at=6,nt=7,ot=8,rt=9,ct=10,dt=11,ht=110,lt=206,ut=32769,mt=32770,pt=32771,gt=32776,St=(e,t,i,s,a,n,o,r)=>{const c={type:ot,confID:e,last_stream_request_msg_index:o,stream_status_msg_index:r};return null!=t&&t.length&&(c.created=t),null!=i&&i.length&&(c.deleted=i),null!=s&&s.length&&(c.updated=s),a&&(c.codec_preference=a),n&&(c.ice_restart_req=n),c};var _t=i(6603);const vt=te.getTracer("WmscMidMgr"),ft=e=>{vt.log(e),te.monitorLog("".concat(e))};class yt{constructor(){this.hasPausedVideo=!1,this.hwDecoderLimit=D,this.mIdResource=new Map,this.userId2Media=new Map,this.midTypeMap={[Ye.zu.MainAudio]:Ye.zu.MainVideo,[Ye.zu.MainVideo]:Ye.zu.MainAudio,[Ye.zu.ShareAudio]:Ye.zu.ShareVideo,[Ye.zu.ShareVideo]:Ye.zu.ShareAudio},this.ssrcMidMap=new Map,this.mid2DetectVideo=new Map,this.isActiveSpeakerTimeout=!1}getMainVideoMId(e){const t=this.userId2Media.get(e);return t?t.midMapping.MainVideo:""}getUserId(e){let t;const i=this.mIdResource.get(e);return i&&(t=i.userId),{userId:t,group:null}}getVideoTagsByMId(e){const t=this.mIdResource.get(e);if(t){const{userId:e}=t;if(e){const t=this.userId2Media.get(e);if(null==t?void 0:t.mainVideoDoms)return Array.from(null==t?void 0:t.mainVideoDoms)}}}getVideoTagsByUserId(e){const t=this.userId2Media.get(e);return(null==t?void 0:t.mainVideoDoms)?Array.from(null==t?void 0:t.mainVideoDoms):[]}saveVideoTag(e,t){const i=this._getOrCreateMediaInfo(e);i.mainVideoDoms||(i.mainVideoDoms=new Set),i.mainVideoDoms.add(t),e===I?this.updateActiveSpeakerVideoStream():i.mainVideoStream&&this._setVideoTagStream(t,i.mainVideoStream,e)}removeVideoTag(e,t){var i;const s=this.userId2Media.get(e);s&&(null===(i=s.mainVideoDoms)||void 0===i||i.delete(t))}_setVideoTagStream(e,t,i){((0,de.gm)()||t&&e.srcObject!==t)&&(e.srcObject=t,e.onpause=()=>{ft("WMSC_V_Tag_Pause: ".concat(i,"|").concat(document.hidden,"|").concat(document.visibilityState)),this.hasPausedVideo=!0})}setVideoSize(e,t){this._getOrCreateMediaInfo(e).videoSize=t}getVideoSizeByUserId(e){var t;const i=this.userId2Media.get(e);return i&&null!==(t=i.videoSize)&&void 0!==t?t:-1}getHasPausedVideo(){if(this.hasPausedVideo)return!0;let e=!1;for(const[,t]of this.userId2Media){const{midMapping:i,mainVideoDoms:s,videoSize:a}=t;if(-1!==a&&i.MainVideo&&s)for(const t of s)if(t.paused){e=!0;break}if(e)break}return e}playAllUsedVideoTag(){const e=[];if("visible"===document.visibilityState)for(const[e,t]of this.userId2Media){const{midMapping:i,mainVideoDoms:s,videoSize:a}=t;if(-1!==a&&i.MainVideo&&s)for(const t of s)if(t.paused&&t.srcObject&&"active"in t.srcObject){const i=t.srcObject.active;return i?t.play().then((()=>Promise.resolve())).catch((t=>Promise.reject("".concat(e,"|errorName:").concat(null==t?void 0:t.name,"|errorMessage:").concat(null==t?void 0:t.message)))):(ft("WMSC_V_Tag_C_P: ".concat(e,"|").concat(!!(null==t?void 0:t.srcObject),"|").concat(i)),Promise.reject(e))}}return e.length<=0?Promise.resolve():Promise.all(e).then((()=>(this.hasPausedVideo=!1,Promise.resolve()))).catch((e=>(this.hasPausedVideo=!0,Promise.reject(e))))}changeHWDecodeLimit(e){if(Z(e)&&((0,de.UP)()||(0,de._J)())){if((0,de.U0)()||(0,de.uF)())return void(this.hwDecoderLimit=8);if((0,de.Zs)())return void(this.hwDecoderLimit=16)}this.hwDecoderLimit=D}addMidResource(e,t){const i=this._getOrCreateMIdResource(e),{streamId:s,track:a,transceiver:n}=t;if(s&&(i.streamId=s),a&&(i.track=a),n&&(i.transceiver=n),i.userId&&a)ft("WMSC_WAFT-".concat(i.userId,"-").concat(e,"-").concat(i.streamId)),te.globalTrace({logLevel:"directReport",log:"WMSC_WAFT-".concat(i.userId,"-").concat(e,"-").concat(i.streamId)}),i.mediaType===Ye.zu.MainVideo&&this._assignVideoStream(i.userId,a);else if("video"===(null==a?void 0:a.kind)){const t=_t.A.createVideoElement();this.mid2DetectVideo.set(e,t),t.onloadedmetadata=()=>{this.attachMidByCSRC(e)},t.srcObject=new MediaStream([a])}}removeMidResource(e){this.mIdResource.delete(e),this.detachMid(e),this.removeAssociateDetectVideo(e)}attachMid(e,t,i){let s=!(arguments.length>3&&void 0!==arguments[3])||arguments[3];this.removeAssociateDetectVideo(t);const a=this._getOrCreateMIdResource(t);a.userId?a.userId===e?te.globalTrace({logLevel:"directReport",log:"WMSC_CLIASSO-".concat(e,"-").concat(t)}):(ft("WMSC_REASSO-".concat(e,"-").concat(t)),te.globalTrace({logLevel:"error",log:"WMSC_REASSO-".concat(e,"-").concat(t)})):(ft("WMSC_ASSO-".concat(e,"-").concat(t,"-").concat(a.streamId)),this._getOrCreateMediaInfo(e).midMapping[i]=t,a.userId=e,a.mediaType=i,a.isCurrentSession=s,i===Ye.zu.MainVideo&&a.track&&this._assignVideoStream(e,a.track))}detachMid(e){const t=this.mIdResource.get(e);if(t&&t.userId){const i=this.userId2Media.get(t.userId);i&&i.midMapping[t.mediaType]===e&&delete i.midMapping[t.mediaType]}}getUserIdByMid(e){var t;return null===(t=this.mIdResource.get(e))||void 0===t?void 0:t.userId}getMactchedMSIDByUserId(e,t){var i,s;const a=null===(i=this.userId2Media.get(e))||void 0===i?void 0:i.midMapping[this.midTypeMap[t]];return a?null===(s=this.mIdResource.get(a))||void 0===s?void 0:s.streamId:""}_getOrCreateMediaInfo(e){let t=this.userId2Media.get(e);return t||(t={midMapping:{}},this.userId2Media.set(e,t)),t}setActiveSpeaker(e){this.activeSpeaker=Q(e),this.updateActiveSpeakerVideoStream()}updateActiveSpeakerVideoStream(){return e=this,t=void 0,s=function*(){var e,t;const i=this.userId2Media.get(I);if(i){const s=this.userId2Media.get(this.activeSpeaker);if(s){const a=s.midMapping.MainVideo;if(a&&a!==i.midMapping.MainVideo){const{track:t,userId:s}=this.mIdResource.get(a)||{};i.midMapping.MainVideo=a;try{if(yield this.detectCanplay(t,a,s),s===this.activeSpeaker){const s=i.mainVideoStream||new MediaStream,a=s.getVideoTracks()[0];a!==t&&(s.addTrack(t),a&&s.removeTrack(a)),i.mainVideoStream=s,null===(e=i.mainVideoDoms)||void 0===e||e.forEach((e=>{this._setVideoTagStream(e,s,I),e.load()}))}}catch(e){te.globalTrace({logLevel:"directReport",log:"WMSC_ACSPCPF"})}}else a&&i.mainVideoStream&&(null===(t=i.mainVideoDoms)||void 0===t||t.forEach((e=>{this._setVideoTagStream(e,i.mainVideoStream,I)})))}}},new((i=void 0)||(i=Promise))((function(a,n){function o(e){try{c(s.next(e))}catch(e){n(e)}}function r(e){try{c(s.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?a(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}c((s=s.apply(e,t||[])).next())}));var e,t,i,s}createDetectVideoTag(){this.canplayDetectVideo=document.createElement("video"),this.canplayDetectVideo.autoplay=!0,this.canplayDetectVideo.playsInline=!0,this.canplayDetectVideo.style.position="fixed",this.canplayDetectVideo.style.width="1px",this.canplayDetectVideo.style.height="1px",this.canplayDetectVideo.style.bottom="0px",this.canplayDetectVideo.style.right="0px",this.canplayDetectVideo.style.zIndex="9999",this.canplayDetectVideo.style.pointerEvents="none",this.canplayDetectVideo.muted=!0,this.canplayDetectVideo.id=U,document.body.appendChild(this.canplayDetectVideo)}detectCanplay(e,t,i){return this.canplayDetectVideo||(this.canplayDetectVideo=document.querySelector("#".concat(U)))||this.createDetectVideoTag(),this.isActiveSpeakerTimeout=!1,this.canplayTimer&&clearTimeout(this.canplayTimer),this.canplayDetectVideo.srcObject&&this.canplayReject&&this.canplayReject(),new Promise(((s,a)=>{this.canplayReject=a,this.canplayResolve=s,this.canplayTimer=setTimeout((()=>{ft("WMSC_ACSPCP_TIMEOUT-".concat(t,"-").concat(i)),te.globalTrace({logLevel:"error",log:"WMSC_ACSPCP_TIMEOUT-".concat(t,"-").concat(i)}),this.isActiveSpeakerTimeout=!0}),1500),this.canplayDetectVideo.oncanplay=()=>{ft("WMSC_ACSPCP-".concat(t,"-").concat(i)),clearTimeout(this.canplayTimer),this.canplayDetectVideo.srcObject=null,this.isActiveSpeakerTimeout=!1,s()},this.canplayDetectVideo.srcObject=new MediaStream([e])}))}getUserIdBySsrc(e){var t;const i=this.ssrcMidMap.get(e);if(i)return null===(t=this.mIdResource.get(i))||void 0===t?void 0:t.userId}getMediaTypeBySsrc(e){var t;const i=this.ssrcMidMap.get(e);if(i)return null===(t=this.mIdResource.get(i))||void 0===t?void 0:t.mediaType}getMidBySsrc(e){return this.ssrcMidMap.get(e)}getMediaTypeByMid(e){var t;if(e)return null===(t=this.mIdResource.get(e))||void 0===t?void 0:t.mediaType}isMlineCurrentSessionByMid(e){var t;return null===(t=this.mIdResource.get(e))||void 0===t?void 0:t.isCurrentSession}attachMidByCSRC(e){var t;this.removeAssociateDetectVideo(e);const i=this.mIdResource.get(e);if(i){const{transceiver:s}=i;if(s){const i=null===(t=s.receiver)||void 0===t?void 0:t.getContributingSources();if(i.length>0){const{source:t}=i[0],s=Q(t);this.attachMid(s,e,Ye.zu.MainVideo,!0)}}}}removeAssociateDetectVideo(e){const t=this.mid2DetectVideo.get(e);t&&(t.onloadedmetadata=null,t.srcObject=null,this.mid2DetectVideo.delete(e))}getAudioMidByUserId(e){const t=this.userId2Media.get(e);return(null==t?void 0:t.midMapping.MainAudio)||""}getVideoMidByUserId(e){const t=this.userId2Media.get(e);return(null==t?void 0:t.midMapping.MainVideo)||""}_assignVideoStream(e,t){var i;const s=this._getOrCreateMediaInfo(e);s.mainVideoStream=new MediaStream([t]),null===(i=s.mainVideoDoms)||void 0===i||i.forEach((t=>{this._setVideoTagStream(t,s.mainVideoStream,e)})),e===this.activeSpeaker&&this.updateActiveSpeakerVideoStream()}_getOrCreateMIdResource(e){let t=this.mIdResource.get(e);return t||(t={},this.mIdResource.set(e,t)),t}removeAllMIdResource(){for(const[e]of this.mid2DetectVideo)this.removeAssociateDetectVideo(e);this.mid2DetectVideo.clear(),this.mIdResource.clear(),this.canplayDetectVideo&&(this.canplayDetectVideo.oncanplay=null,this.canplayDetectVideo.srcObject=null)}onStatsReport(e){var t,i;if(!this.isActiveSpeakerTimeout)return;const s=this.userId2Media.get(I),a=this.userId2Media.get(this.activeSpeaker);if(s&&a){const{mainVideoStream:n}=s,{mainVideoStream:o}=a;if((null==n?void 0:n.getVideoTracks()[0])!==(null==o?void 0:o.getVideoTracks()[0])){const{ssrc:s}=e.receiverStatisticData[this.activeSpeaker]||{},{framesDecoded:a}=(null===(t=e["prev-video-inbound-rtp"])||void 0===t?void 0:t[s])||{},{framesDecoded:n}=(null===(i=e["video-inbound-rtp"])||void 0===i?void 0:i[s])||{};n-a>0&&this.canplayResolve&&(te.globalTrace({logLevel:"directReport",log:"WMSC_ACSPCP_BY_STATS-".concat(n-a,"-").concat(s,"-").concat(this.activeSpeaker)}),ft("WMSC_ACSPCP_BY_STATS-".concat(n-a,"-").concat(s,"-").concat(this.activeSpeaker)),this.isActiveSpeakerTimeout=!1,this.canplayResolve())}}}}const Mt=new class{constructor(){this.sendVideoSizeLowerLimit=0,this.sendVideoSizeUpperLimit=4,this.recvVideoSizeLowerLimit=0,this.recvVideoSizeUpperLimit=4,this.recvVideoNumLowerLimit=4,this.recvVideoNumUpperLimit=(0,de.GN)()?L:w,this.sendVideoSizeLowerLimitApp=this.sendVideoSizeLowerLimit,this.sendVideoSizeUpperLimitApp=this.sendVideoSizeUpperLimit,this.recvVideoSizeLowerLimitApp=this.recvVideoSizeLowerLimit,this.recvVideoSizeUpperLimitApp=this.recvVideoSizeUpperLimit,this.recvVideoNumLowerLimitApp=this.recvVideoNumLowerLimit,this.recvVideoNumUpperLimitApp=this.recvVideoNumUpperLimit,this.maxSendVideoSize=0,this.maxRecvVideoSize=0,this.maxRecvVideoNum=0,this._reset()}_reset(){let e=3;!(0,de.Xb)()&&navigator.hardwareConcurrency>=8&&(e=4),this.maxSendVideoSize=Math.max(this.sendVideoSizeLowerLimit,this.sendVideoSizeLowerLimitApp,Math.min(this.sendVideoSizeUpperLimit,this.sendVideoSizeUpperLimitApp,e)),this.maxRecvVideoSize=Math.max(this.recvVideoSizeLowerLimit,this.recvVideoSizeLowerLimitApp,Math.min(this.recvVideoSizeUpperLimit,this.recvVideoSizeUpperLimitApp,4)),this.maxRecvVideoNum=Math.max(this.recvVideoNumLowerLimit,this.recvVideoNumLowerLimitApp,Math.min(this.recvVideoNumUpperLimit,this.recvVideoNumUpperLimitApp))}setLimits(e){const{minSendVideoSize:t,maxSendVideoSize:i,minRecvVideoSize:s,maxRecvVideoSize:a,minRecvVideoNum:n,maxRecvVideoNum:o}=e;void 0!==t&&(this.sendVideoSizeLowerLimitApp=t),void 0!==i&&(this.sendVideoSizeUpperLimitApp=i),void 0!==s&&(this.recvVideoSizeLowerLimitApp=s),void 0!==a&&(this.recvVideoSizeUpperLimitApp=a),void 0!==n&&(this.recvVideoNumLowerLimitApp=n),void 0!==o&&(this.recvVideoNumUpperLimitApp=o),this._reset()}getCapabilities(){return{maxSendVideoSize:this.maxSendVideoSize,maxRecvVideoSize:this.maxRecvVideoSize,maxRecvVideoNum:this.maxRecvVideoNum}}};i(7855);var Ct=i(3472),It=i(2710),Et=i(3323);function Tt(e){return null!=e&&e.length?parseInt(e.reduce(((e,t)=>e+t),0)/e.length):0}function Rt(e){return null!=e&&e.length?Math.max(...e):0}const At=class{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this._userId=e.userId,this._monitorInfo={subscriber:{},publisher:{}},this._bitrateInfo={subscriber:{},publisher:{}},this._reportCount=0,this._MONITOR_RECORD_INTERVAL=12e3,this._BITRATE_RECORD_INTERVAL=1e3,this._INBOUND_AUDIO_LEVEL_INTERVAL=1e3,this._AUDIO_TAG_COUNT_AND_STATUS_CHECK_INTERVAL=5e3,this._enableBitrateReport=!1,this._lastAudioTagCountAndStatusCheckTime=0,this._uplinkMonitorInfoList=[],this._uplinkMonitorPrevTime=Date.now(),this._downlinkAudioLevelInfo={},this._audioMos=[],this._networkStatistics={publisher:{},subscriber:{}},this._wmscAudio=e.wmscAudio,this._onBadNetwork=e.onBadNetwork,this._onHealthCheck=e.onHealthCheck,this._onMonitorLog=e.onMonitorLog,this._isMonitoring=!1,this._onEntireStatsReportBind=this._onEntireStatsReport.bind(this)}destroy(e){this.stopMonitor(e)}setEnableBitrateReport(e){this._enableBitrateReport=e}setUserId(e){this._userId=e}startMonitor(e){this.stopMonitor(e),e.on(Ye.f7.StatsReport,this._onEntireStatsReportBind),this._isMonitoring=!0}stopMonitor(e){e.off(Ye.f7.StatsReport,this._onEntireStatsReportBind),this._resetMonitorCache(),this._isMonitoring=!1}resetWMSCPC(e,t){this.stopMonitor(e),this._isMonitoring&&this.startMonitor(t)}getBitrateInfo(){return this._bitrateInfo}_resetMonitorCache(){var e,t,i,s,a,n;this._monitorInfo={subscriber:{port:null===(e=this._monitorInfo)||void 0===e||null===(e=e.subscriber)||void 0===e?void 0:e.port,protocol:null===(t=this._monitorInfo)||void 0===t||null===(t=t.subscriber)||void 0===t?void 0:t.protocol,candidateType:null===(i=this._monitorInfo)||void 0===i||null===(i=i.subscriber)||void 0===i?void 0:i.candidateType},publisher:{port:null===(s=this._monitorInfo)||void 0===s||null===(s=s.publisher)||void 0===s?void 0:s.port,protocol:null===(a=this._monitorInfo)||void 0===a||null===(a=a.publisher)||void 0===a?void 0:a.protocol,candidateType:null===(n=this._monitorInfo)||void 0===n||null===(n=n.publisher)||void 0===n?void 0:n.candidateType}},this._bitrateInfo={publisher:{},subscriber:{}},this._networkStatistics={publisher:{},subscriber:{}}}_isTimeForMonitorLog(){return this._reportCount&&!(this._reportCount%Math.floor(this._MONITOR_RECORD_INTERVAL/Ye.Mr))}_isTimeForBitrate(){return!(this._reportCount%Math.floor(this._BITRATE_RECORD_INTERVAL/Ye.Mr))}_isTimeForInboundAudioLevel(){return!(this._reportCount%Math.floor(this._INBOUND_AUDIO_LEVEL_INTERVAL/Ye.Mr))}_isTimeForAudioTagCountAndStatus(){const e=performance.now();return!(e-this._lastAudioTagCountAndStatusCheckTime<this._AUDIO_TAG_COUNT_AND_STATUS_CHECK_INTERVAL||(this._lastAudioTagCountAndStatusCheckTime=e,0))}_onEntireStatsReport(e){this._uplinkStatsParse(e),this._downlinkStatsParse(e),this._networkStatsParse(e),this._getRWGNetworkLog(!0),this._getRWGNetworkLog(!1),this.sendAudioMos(),this._reportCount++}_uplinkStatsParse(e){var t,i,s;if(!e)return;const a=this._isTimeForMonitorLog();if(this._isTimeForBitrate()&&Ct.Ay.outboundBitrateQosParse(e,this._bitrateInfo.publisher),!a)return;let n={};const{publisher:o}=this._monitorInfo;if(e.forEach((e=>{0!=Ct.Ay.isAudioStat(e)&&(this._statRemoteInboundRTP(e,n,o),this._statOutBoundRTP(e,n,o),this._statMediaSource(e,n,o))})),this._checkNetworkQuality(0,null===(t=n[Ye.zu.MainAudio])||void 0===t?void 0:t.rtt),this._onHealthCheck&&this._onHealthCheck({uplinkPacketsSent:null===(i=n[Ye.zu.MainAudio])||void 0===i?void 0:i.packetsSent,uplinkTotalAudioEnergy:null===(s=n[Ye.zu.MainAudio])||void 0===s?void 0:s.totalAudioEnergy,isUplink:!0}),n[Ye.zu.MainAudio]){const{resLevelR16Log:e,resLevelR16LogDenoise:t}=this._wmscAudio.getLevelR16Log();n[Ye.zu.MainAudio].audioLevelR16Str=e,n[Ye.zu.MainAudio].audioLevelR16DenoiseStr=t}Ct.Ay.audioSendQualityMonitor(n)}_downlinkStatsParse(e){var t;if(!e)return;const i=this._isTimeForMonitorLog(),s=this._isTimeForBitrate(),a=this._isTimeForInboundAudioLevel(),n=this._isTimeForAudioTagCountAndStatus();let o={ssrcMap:{}};s&&Ct.Ay.inboundBitrateQosParse(e,null===(t=this._bitrateInfo)||void 0===t?void 0:t.subscriber);let r=i;const{subscriber:c}=this._monitorInfo;e.forEach((e=>{i&&this._downLinkCandidatePairParse(e,o),0!=Ct.Ay.isAudioStat(e)&&(r=this._statInboundRTPParseReturnShoudSendMonitor(e,o,c,a&&!i)||r)})),i&&this._checkNetworkQuality(1,o.rtt),this._onHealthCheck&&this._onHealthCheck({downlinkStatInfo:o,isUplink:!1}),r&&this._handleDownlinkMonitorLog(o),n&&this._wmscAudio._healthChecker._audioTagCountAndStatusMonitor(this._wmscAudio._wmscPC,this._wmscAudio._mid2RemoteRTCAudioPlayer,!1,null,null)}async _networkStatsParse(e){e.forEach((t=>{Ct.Ay.networkInfoStatisticsParse(e,t,this._monitorInfo.publisher,"publisher"),Ct.Ay.networkInfoStatisticsParse(e,t,this._monitorInfo.subscriber,"subscriber")}))}_statRemoteInboundRTP(e,t,i){"remote-inbound-rtp"==e.type&&Ct.Ay.remoteInboundRTPStatisticParse(Ye.zu.MainAudio,e,this._wmscAudio.getAudioMode(),t,i)}_statOutBoundRTP(e,t,i){"outbound-rtp"==e.type&&Ct.Ay.outboundRTPStatisticsParse(this._wmscAudio.getUplinkMidOrSSRC2MediaType(e.mid,e.ssrc),e,this._wmscAudio.getAudioMode(),t,i)}_statMediaSource(e,t,i){let s=this._wmscAudio.getAudioStream();"media-source"==e.type&&Ct.Ay.mediaSourceStatisticsParse(s,e,this._wmscAudio.getAudioMode(),t,i)}_downLinkCandidatePairParse(e,t){const{subscriber:i}=this._monitorInfo,{totalRoundTripTime:s,responsesReceived:a,type:n,state:o,nominated:r}=e;if("candidate-pair"===n&&"succeeded"===o&&r){i.prevStatInfo||(i.prevStatInfo={responsesReceived:a,totalRoundTripTime:s},i.ssrcMap={});const{prevStatInfo:e}=i;Object.assign(t,{rtt:Math.floor(1e3*(a===e.responsesReceived?0:(s-e.totalRoundTripTime)/(a-e.responsesReceived)))}),Object.assign(i.prevStatInfo,{totalRoundTripTime:s,responsesReceived:a})}}_statInboundRTPParseReturnShoudSendMonitor(e,t,i,s){if("inbound-rtp"!=e.type)return;let a;const{totalAudioEnergy:n,timestamp:o,jitterBufferDelay:r,jitterBufferEmittedCount:c,jitterBufferMinimumDelay:d,jitterBufferTargetDelay:h,ssrc:l,jitter:u,audioLevel:m,packetsLost:p,packetsDiscarded:g,packetsReceived:S,bytesReceived:_,concealedSamples:v,concealmentEvents:f,insertedSamplesForDeceleration:y,removedSamplesForAcceleration:M,silentConcealedSamples:C,totalProcessingDelay:I,nackCount:E}=e;let T=this._wmscAudio.getRemoteAudioPlayerByMid(e.mid);if((S>0||n>0)&&T.setStreamValid(),this._cacheDownlinkAudioLevel(l,m,T),s)return!1;i.ssrcMap||(i.ssrcMap={});let R=this._wmscAudio.getZoomSSRCByWebRTCSSRC(l);if(!R)return;let A=i.ssrcMap[l];if(A){a=!0;const i=Math.sqrt((n-A.totalAudioEnergy)/(o-A.timestamp)).toFixed(4);let s=-1;"number"==typeof m&&(s=m.toFixed(4));const{aveJitterBufferDelay_ms:r,aveJitterBuffeTargetrDelay_ms:c,totalPacketsReceived_diff:h,packetsDiscarded_diff:p,insertedSamplesForDeceleration_diff:g,packetsLost_diff:S,concealedSamples_diff:_,removedSamplesForAcceleration_diff:y,silentConcealedSamples_diff:I,nackCount_diff:E,totalProcessingDelay_ms:b}=Ct.Ay.getDownlinkStatisticsRate(A,e);t.ssrcMap["".concat(R)]=Object.assign(t.ssrcMap["".concat(R)]||{},{aveAudioLevel:i<1e-4?0:i,audioLevel:s<1e-4?0:s,jitter:u,jitterBufferMinimumDelay:d,concealedSamples:v,concealmentEvents:f,removedSamplesForAcceleration:M,silentConcealedSamples:C,audioPausedStatus:T?T.isPaused()?0:1:-1,audioMutedStatus:T?T.isMuted()?0:1:-1,totalAudioEnergy:n,aveJitterBufferDelay_ms:r,aveJitterBuffeTargetrDelay_ms:c,ssrc:l,audioVolume:T?T.getVolume():-1,isInterpreter:T?T.isInterpreter()?1:0:-1,totalPacketsReceived_diff:h,packetsDiscarded_diff:p,insertedSamplesForDeceleration_diff:g,packetsLost_diff:S,concealedSamples_diff:_,removedSamplesForAcceleration_diff:y,silentConcealedSamples_diff:I,nackCount_diff:E,totalProcessingDelay_ms:b})}else A=i.ssrcMap[l]={},a=!1;return this._wmscAudio.isUserMuted(R,l)||!R?i.ssrcMap[l]=null:Object.assign(A,{totalAudioEnergy:n,timestamp:o,jitterBufferDelay:r,jitterBufferEmittedCount:c,packetsLost:p,packetsReceived:S,bytesReceived:_,jitterBufferTargetDelay:h,totalProcessingDelay:I,insertedSamplesForDeceleration:y,packetsDiscarded:g,concealedSamples:v,removedSamplesForAcceleration:M,silentConcealedSamples:C,nackCount:E}),a}_checkNetworkQuality(e,t){t&&this._onBadNetwork&&(t>5e3?this._onBadNetwork({isUplink:0===e,networkLevel:It.tT.NET_QUALITY_VERY_BAD,bwLevel:It.LA.NET_BW_LEVEL_VERY_LOW}):t>2e3&&this._onBadNetwork({isUplink:0===e,networkLevel:It.tT.NET_QUALITY_BAD,bwLevel:It.LA.NET_BW_LEVEL_LOW}))}_cacheDownlinkAudioLevel(e,t,i){const s=this._wmscAudio.getZoomSSRCByWebRTCSSRC(e);if(!s)return;let a="".concat(s);this._downlinkAudioLevelInfo[a]||(this._downlinkAudioLevelInfo[a]=[]),null!=i&&i.isPaused()?this._downlinkAudioLevelInfo[a].push("x"):this._downlinkAudioLevelInfo[a].push(Et.ey(t))}_handleDownlinkMonitorLog(e){Object.keys(this._downlinkAudioLevelInfo).forEach((t=>{e.ssrcMap[t]&&(e.ssrcMap[t].zoomAudioLevel=this._downlinkAudioLevelInfo[t])})),this._downlinkAudioLevelInfo={},Ct.Ay.audioRecvQualityMonitor(e),this._downlinkAudioLevelInfo={}}setAudioStatisticsFromRWG(e){const t=e.encoding?this._networkStatistics.publisher:this._networkStatistics.subscriber;Object.keys(e).forEach((i=>{"avg_mos"===i?this._audioMos.push(e[i]):(t[i]||(t[i]=[]),void 0!==e[i]&&t[i].push(e[i]))}))}sendAudioMos(){var e,t;if(!(arguments.length>0&&void 0!==arguments[0]&&arguments[0]||this._reportCount&&this._reportCount%10==0))return;const i=null===(e=this._audioMos)||void 0===e?void 0:e.length;if(!i)return;const s=this._audioMos[i-1].toFixed(2),a=(this._audioMos.reduce(((e,t)=>e+t),0)/i).toFixed(2);this._audioMos.length=0;const n="WCL_MCM_AUDIO,".concat(this._userId,",,,{[SPEECH_R16]},,,,,,{[PROCESS]},,,{[NETWORK]},,,,{[AUDIOSCORE]},,,,,,,,,,,,,,{[QUALITY]},").concat(s,",").concat(a,",{[SEND]},,,{[DENOISE]},,,,{[END]}");null===(t=this._onMonitorLog)||void 0===t||t.call(this,n)}_toIntSafe(e){const t=Number(e);return Number.isFinite(t)?Math.round(t):-1}_getRWGNetworkLog(e){var t,i;if(0===this._reportCount||this._reportCount%30!=0)return;const s=e?this._monitorInfo.publisher:this._monitorInfo.subscriber,a=e?this._networkStatistics.publisher:this._networkStatistics.subscriber,n=e?"RWG_UPLINK_NETWORK":"RWG_DOWNLINK_NETWORK",o="udp"===s.protocol?0:1,r=Math.floor(Date.now()/1e3),c=e?(null===(t=this._bitrateInfo)||void 0===t||null===(t=t.publisher)||void 0===t?void 0:t.bitrate)||0:(null===(i=this._bitrateInfo)||void 0===i||null===(i=i.subscriber)||void 0===i?void 0:i.bitrate)||0,d=c,h=this._toIntSafe(Tt(a.avg_loss)),l=this._toIntSafe(Rt(a.max_loss)),u=this._toIntSafe(Tt(a.rtt)),m=this._toIntSafe(Rt(a.rtt)),p=this._toIntSafe(u/2),g=this._toIntSafe(m/2),S=this._toIntSafe(Tt(a.jitter)),_=this._toIntSafe(Rt(a.jitter)),v=this._toIntSafe(d),f=this._toIntSafe(c);e?this._networkStatistics.publisher={}:this._networkStatistics.subscriber={};const y="".concat(n,",").concat(this._userId,",").concat(1,",").concat(o,",").concat(r,",,").concat(v,",").concat(f,",").concat(h,",").concat(l,",,").concat(p,",").concat(g,",").concat(u,",").concat(m,",,,,,,,,,,,").concat(S,",").concat(_);this._onMonitorLog(y)}static getEstimatePlayoutTimestampFromStatsByMid(e,t){var i;let s;for(const[,i]of e)if("inbound-rtp"===i.type&&"audio"===i.kind&&i.mid===t){s=i;break}return null===(i=s)||void 0===i?void 0:i.estimatedPlayoutTimestamp}};var bt=i(9559);function wt(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,s)}return i}function Dt(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?wt(Object(i),!0).forEach((function(t){(0,c.A)(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):wt(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}const Lt=te.getTracer("WmscMonitor"),Ot=e=>{Lt.log(e),te.monitorLog("".concat(e))},Pt=e=>e===Number.MIN_SAFE_INTEGER?"":e,Vt=e=>e===Number.MAX_SAFE_INTEGER?"":e,{tT:Bt,LA:Nt,ue:kt}=s,Ut=new class{constructor(){this.bToPrint=!0,this.mIdMgr=null,this.reportTimer=null,this.userId="",this.isMonitoring=!1,this.subInfo={},this.activeSpeaker="",this.isPreActiveSpeaker=!1,this.recordUserId="",this.reportTimer=null,this.lastSendPCsStatRecord=new Map,this.captureCount=0,this.rtpHeaderExt={"http://www.webrtc.org/experiments/rtp-hdrext/playout-delay":0,"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01":1,"urn:ietf:params:rtp-hdrext:sdes:mid":2,"http://www.webrtc.org/experiments/rtp-hdrext/video-layers-allocation00":3},this.sdpDirection={recvonly:0,sendonly:1,sendrecv:2,inactive:3},this.recvStatisticData={},this.reportCount=0,this.maxSubscribedSize=-1,this._telemetry=null,this.uiQosData={},this.isUISubQos=!1,this.UIQosInterval=1,this.candidateLog="",this.candidatePairLog="",this.iceCandidatePairState={frozen:0,waiting:1,"in-progress":2,failed:3,succeeded:4},this.ingressReport={},this.camStream=null,this.recvCodecProfile="",this.shouldReportNullDecoderError=!0,this.shouldReportEncodeFailedError=!0,this.recvRawStats={},this.sendRawStats={},this.ssrcLayerMap={},this.rawLog=[],this.prevUplinkState={},this.prevDownlinkState={},this.networkReportDelay=0,this.isDualCall=!1,this.layerStatus={numOfActive:0,numOfStopSending:0},this.isWebRTCVideoEnabled=!1,this.pcStats={senderStatisticData:{},receiverStatisticData:{},statisticData:{}},this.videoObserverEnabled=!1,this.videoObserverFramerateEnabled=!1,this.recvVideoQuality={},this.avSyncMgr=null,this.rawRTPInboundStats={},this.qosReport=null}setTelemetry(e){this._telemetry="function"==typeof e?e:null}updateQosSubscription(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1e3;this.isUISubQos=e,this.UIQosInterval=Math.round(t/1e3)}enableVideoObserver(e,t){this.videoObserverEnabled=e,this.videoObserverFramerateEnabled=e&&t}setUserId(e){this.userId=parseInt(e,10)}setQoSDataCb(e){this.sendQoSData=e}onQosReport(e){this.qosReport=e}updateSubInfo(e,t){Ot("WMSC_USBI: ".concat(e,"|").concat(t)),t>=0?this.subInfo[e]=t:(delete this.subInfo[e],delete this.recvVideoQuality[e],this.resetRecvStats(e)),Lt.log("updateSubInfo:",this.subInfo)}setActiveSpeaker(e,t){this.activeSpeaker=Q(parseInt(e,10)),this.isPreActiveSpeaker=t}updateSubscribedSize(e,t,i){let s=-1;Array.from(new Set([...e,...t,...i])).forEach((e=>{s=Math.max(s,e)})),this.maxSubscribedSize=s}start(){Ot("WMSC_MSTART: ".concat(this.isMonitoring)),this.isMonitoring||(this._startReport(),this.isMonitoring=!0,this.shouldReportNullDecoderError=!0,this.shouldReportEncodeFailedError=!0,this.networkReportDelay=0)}resetRecvStats(e){var t;let i;null!==(t=this.pcStats.receiverStatisticData)&&void 0!==t&&t[e]&&(i=this.pcStats.receiverStatisticData[e].ssrc,delete this.pcStats.receiverStatisticData[e]),i&&(this.pcStats["begin-video-inbound-rtp"]&&delete this.pcStats["begin-video-inbound-rtp"][i],this.pcStats["video-inbound-rtp"]&&delete this.pcStats["video-inbound-rtp"][i],this.pcStats["video-remote-outbound-rtp"]&&delete this.pcStats["video-remote-outbound-rtp"][i])}stop(){Ot("WMSC_MSTOP: ".concat(this.isMonitoring)),clearInterval(this.reportTimer),this._getStats(),this._uploadRawRTPInboundStats(),this.pcStats={senderStatisticData:{},receiverStatisticData:{},statisticData:{}},this.rawRTPInboundStats={},this.isMonitoring=!1}_sendQosData(){this.isUISubQos&&this.captureCount%this.UIQosInterval==0&&(this.uiQosData.receiving&&(this._telemetry&&this._telemetry({type:W.VIDEO_QOS_DATA,data:Dt({encoding:!1},this.uiQosData.receiving)}),this.uiQosData.receiving=null),this.uiQosData.sending&&(this._telemetry&&this._telemetry({type:W.VIDEO_QOS_DATA,data:Dt({encoding:!0},this.uiQosData.sending)}),this.uiQosData.sending=null))}_sendNetworkState(e){const{isUplink:t}=e;let i=!1;i=t?e.networkLevel!==this.prevUplinkState.networkLevel||e.bwLevel!==this.prevUplinkState.bwLevel:e.networkLevel!==this.prevDownlinkState.networkLevel||e.bwLevel!==this.prevDownlinkState.bwLevel,i&&(this._telemetry&&this._telemetry({type:W.NETWORK_QUALITY_CHANGE,data:e}),t?this.prevUplinkState=e:this.prevDownlinkState=e)}_getNetworkState(e,t,i){let s=Bt.NET_QUALITY_UNKNOWN,a=Nt.NET_BW_LEVEL_UNKNOWN;if(e>.5||t/2>5)s=Bt.NET_QUALITY_VERY_BAD;else if(e>.3||t/2>2)s=Bt.NET_QUALITY_BAD;else if(void 0!==i){const n=i/1024;n<320||e>.08&&t>.5?s=Bt.NET_QUALITY_NOT_GOOD:n>450?(s=Bt.NET_QUALITY_GOOD,a=Nt.NET_BW_LEVEL_NORMAL):n>850&&e<.05&&t<.3&&(s=Bt.NET_QUALITY_EXCELLENT,a=Nt.NET_BW_LEVEL_NORMAL)}return{networkLevel:s,bwLevel:a}}onStatsReport(e){this.captureCount++;try{this.handleStatsReport(e),this._sendQosData()}catch(e){Lt.error("_startCapture, capture error: ".concat(e)),Ot("WMSC_LOGCE"),te.globalTrace({logLevel:"error",log:"WMSC_LOGCE",errorEvent:e})}}_startReport(){this.reportTimer=setInterval(this._reportStats.bind(this),f)}_reportStats(){try{this.reportCount++,this._getStats(),this._resetStats(),this.ingressReport.begin=null}catch(e){Ot("WMSC_LOGRE"),te.globalTrace({logLevel:"error",log:"WMSC_LOGRE",errorEvent:e})}}_resetSenderStats(){const{senderStatisticData:e}=this.pcStats;e.maxCamCaptureFps=e.maxCaptureFps=0,e.minCamCaptureFps=e.minCaptureFps=Math.MAX_SAFE_INTEGER,e.totalCamCaptureCount=e.totalCaptureCount=0,e.totalCamCaptureFps=e.totalCaptureFps=0;for(const t in this.pcStats["video-outbound-rtp"])e[t]={maxEncodeTime:0,minEncodeTime:Number.MAX_SAFE_INTEGER,avgEncodeTime:0,minSendFrameRate:Number.MAX_SAFE_INTEGER,maxSendFrameRate:0,avgSendFrameRate:0,minSendBitRate:Number.MAX_SAFE_INTEGER,maxSendBitRate:0,avgSendBitRate:0,minPacketSentDelay:Number.MAX_SAFE_INTEGER,maxPacketSentDelay:0,avgPacketSentDelay:0,maxLossRate:"",avgLossRate:"",encodePauseCount:0,count:0,maxQP:0,minQP:Number.MAX_SAFE_INTEGER,avgQP:0};this.pcStats["video-outbound-rtp"]&&(this.pcStats["begin-video-outbound-rtp"]=Dt({},this.pcStats["video-outbound-rtp"])),this.pcStats["video-remote-inbound-rtp"]&&(this.pcStats["begin-video-remote-inbound-rtp"]=Dt({},this.pcStats["video-remote-inbound-rtp"])),this.pcStats["video-media-source"]&&(this.pcStats["begin-video-media-source"]=this.pcStats["video-media-source"])}_resetReceiverStats(){const{receiverStatisticData:e}=this.pcStats;for(const t in e)e[t]={maxFps:0,minFps:Number.MAX_SAFE_INTEGER,avgFps:0,maxDecodeTime:0,minDecodeTime:Number.MAX_SAFE_INTEGER,avgDecodeTime:0,maxLossRate:0,avgLossRate:0,maxBt:0,minBt:Number.MAX_SAFE_INTEGER,avgBt:0,maxJitter:0,minLastRecvGap:Number.MAX_SAFE_INTEGER,maxLastRecvGap:0,avgLastRecvGap:0,noDataCount:0,count:0,decodePausedCount:0,maxAVSyncDelay:Number.MIN_SAFE_INTEGER,minAVSyncDelay:Number.MAX_SAFE_INTEGER,avgAVSyncDelay:"",avSyncDelayArray:[],audioEstimatedPlayoutTimestamp:"",maxJitterBufferDelay:0,minJitterBufferDelay:Number.MAX_SAFE_INTEGER,avgJitterBufferDelay:0,maxAppAVSyncDelay:Number.MIN_SAFE_INTEGER,minAppAVSyncDelay:Number.MAX_SAFE_INTEGER,avgAppAVSyncDelay:"",appAVSyncDelayArray:[]};this.pcStats["video-inbound-rtp"]&&(this.pcStats["begin-video-inbound-rtp"]=Dt({},this.pcStats["video-inbound-rtp"])),this.pcStats["video-remote-outbound-rtp"]&&(this.pcStats["begin-video-remote-outbound-rtp"]=Dt({},this.pcStats["video-remote-outbound-rtp"]))}_resetStats(){this._resetSenderStats(),this._resetReceiverStats(),this.pcStats["candidate-pair"]&&(this.pcStats["begin-candidate-pair"]=this.pcStats["candidate-pair"]),delete this.pcStats.statisticData.maxRtt,delete this.pcStats.codec}_generateSenderStatisticData(){const e=this.pcStats.senderStatisticData,t=this.pcStats["video-media-source"]||{},i=this.pcStats["prev-video-media-source"]||{},s=this.pcStats["video-outbound-rtp"]||{},a=this.pcStats["prev-video-outbound-rtp"]||{},n=this.pcStats["begin-video-outbound-rtp"]||{},o=this.pcStats["begin-video-media-source"]||{},r=this.pcStats["video-remote-inbound-rtp"]||{};let c=0,d=0;this.layerStatus.numOfActive=0,this.layerStatus.numOfStopSending=0;const{minCaptureFps:h,maxCaptureFps:l,minCamCaptureFps:u,maxCamCaptureFps:m,totalCaptureFps:p=0,totalCaptureCount:g=0,totalCamCaptureFps:S=0,totalCamCaptureCount:_=0}=e;let v=!1;const f=$e.getSender(),{frames:y}=t,{frames:M}=i;if(f&&f.track){const{frameRate:i=0,width:s,height:a}=f.track.getSettings(),{framesPerSecond:n=i,height:o=s,width:r=a}=t;v=!0,e.minCaptureFps=Math.round(Math.min(n,h||Number.MAX_SAFE_INTEGER)),e.maxCaptureFps=Math.round(Math.max(n,l||0)),e.totalCaptureFps=p+n,e.totalCaptureCount=g+1,e.avgCaptureFps=Math.round(e.totalCaptureFps/e.totalCaptureCount),e.captureWidth=null!=o?o:"",e.captureHeight=null!=r?r:""}if(this.camStream){var C;const{frameRate:t=0}=null===(C=this.camStream.getVideoTracks()[0])||void 0===C?void 0:C.getSettings();e.minCamCaptureFps=Math.round(Math.min(t,u||Number.MAX_SAFE_INTEGER)),e.maxCamCaptureFps=Math.round(Math.max(t,m||0)),e.totalCamCaptureFps=S+t,e.totalCamCaptureCount=_+1,e.avgCamCaptureFps=Math.round(e.totalCamCaptureFps/e.totalCamCaptureCount)}for(const t in s){const{framesPerSecond:i="",bytesSent:h,framesSent:l,timestamp:u,framesEncoded:m,totalEncodeTime:p,packetsSent:g,totalPacketSendDelay:S,frameHeight:_,frameWidth:f,retransmittedPacketsSent:C,active:T,qualityLimitationDurations:R,qpSum:A}=s[t];let b=0;!1!==T&&(this._captureRawSendData(s[t]),this.layerStatus.numOfActive++);const{jitter:w}=r[t]||{};e[t]||(e[t]={});const D=e[t],{minEncodeFrameRate:L,maxEncodeFrameRate:O,minSendFrameRate:P,maxSendFrameRate:V,minSendBitRate:B,maxSendBitRate:N,maxEncodeTime:k,minEncodeTime:U,maxPacketSentDelay:x,minPacketSentDelay:F,maxJitter:W,maxLossRate:z,sendWidth:j,sendHeight:G,maxQP:H,minQP:Q}=D;if(D.minEncodeFrameRate=Math.min(i,L||Number.MAX_SAFE_INTEGER),D.maxEncodeFrameRate=Math.max(i,O||0),D.maxJitter=Math.max(w,W||0),a&&a[t]){var I;if(!1===T||!v)continue;D.count++;const{timestamp:i,bytesSent:s,framesSent:r,framesEncoded:c,totalEncodeTime:w,packetsSent:L,totalPacketSendDelay:O,retransmittedPacketsSent:W,qpSum:q}=a[t],{framesSent:Y,bytesSent:K,timestamp:J,framesEncoded:X,totalEncodeTime:Z,packetsSent:$,totalPacketSendDelay:ee,retransmittedPacketsSent:ie,qualityLimitationDurations:se,qpSum:ae}=n[t];let ne,oe,re="",ce="";b=l-r;const de=Math.round(b/((u-i)/1e3)),he=(8*(h-s)/((u-i)/1e3)).toFixed(2),le=Math.round((l-Y)/((u-J)/1e3)),ue=parseFloat((8*(h-K)/((u-J)/1e3)).toFixed(2)),me=Math.ceil((p-w)/(m-c)*1e3)||0,pe=Math.ceil((p-Z)/(m-X)*1e3)||0,ge=Math.round((m-X)/((u-J)/1e3)),{current:Se,begin:_e,prev:ve}=this.ingressReport;if(Se&&ve&&_e){const{lostPkts:e,recvPkts:t}=Se,{lostPkts:i,recvPkts:s}=ve,{lostPkts:a,recvPkts:n}=_e,o=e-i,r=e-a;ce=o/(t-s+o)||0,re=r/(t-n+r)||0}else re=(C-ie)/(g-$)||0,ce=(C-W)/(g-L)||0;if(void 0!==S&&(ne=(1e3*(S-O)/(g-L)).toFixed(3),oe=(1e3*(S-ee)/(g-$)).toFixed(3)),T&&m===c&&y&&y>M&&(D.encodePauseCount++,D.encodePauseCount>10&&this.layerStatus.numOfStopSending++,D.encodePauseCount>10&&this.shouldReportEncodeFailedError)){var E;const{frames:e=""}=o;let i="".concat(t,"|").concat(m,"|").concat(X,"|").concat(y,"|").concat(e,"|"),s=!1;if(R&&se){const{bandwidth:e,cpu:t,other:a}=R,{bandwidth:n,cpu:o,other:r}=se;s=e>n,i+="".concat(e,"|").concat(n,"|").concat(t,"|").concat(o,"|").concat(a,"|").concat(r)}const a=null===(E=this.camStream)||void 0===E?void 0:E.getVideoTracks()[0];i+=",videoTrack:".concat(!!a,"|").concat(a&&(null==a?void 0:a.muted)),te.globalTrace({logLevel:s?"warn":"error",log:"WMSC_ENCODE_STOP: ".concat(i)}),Ot("WMSC_ENCODE_STOP: ".concat(i)),this.shouldReportEncodeFailedError=!1}let fe="",ye="";void 0!==A&&m&&(void 0!==q&&m>c&&(ye=Math.round((A-q)/(m-c))),void 0!==ae&&m>X&&(fe=Math.round((A-ae)/(m-X)))),e[t]=Dt(Dt({},D),{},{maxEncodeTime:Math.max(k,me),minEncodeTime:Math.min(me,U),avgEncodeTime:pe,minSendFrameRate:Math.min(de,P),maxSendFrameRate:Math.max(V,de),avgSendFrameRate:le,minSendBitRate:Math.min(he,B),maxSendBitRate:Math.max(N,he),avgSendBitRate:ue,minPacketSentDelay:Math.min(ne,F),maxPacketSentDelay:Math.max(ne,x),avgPacketSentDelay:null!==(I=oe)&&void 0!==I?I:"",avgEncodeFrameRate:ge,avgLossRate:isNaN(re)?"":re,maxLossRate:isNaN(ce)?z:Math.max(ce,z),sendWidth:f||j,sendHeight:_||G,maxQP:Math.max(H,ye),minQP:Math.min(Q,ye),avgQP:fe}),d=Math.max(d,e[t].avgLossRate)}else e[t]=Dt(Dt({},D),{},{maxEncodeTime:0,minEncodeTime:Number.MAX_SAFE_INTEGER,avgEncodeTime:0,minSendFrameRate:Number.MAX_SAFE_INTEGER,maxSendFrameRate:0,avgSendFrameRate:0,minSendBitRate:Number.MAX_SAFE_INTEGER,maxSendBitRate:0,avgSendBitRate:0,minPacketSentDelay:Number.MAX_SAFE_INTEGER,maxPacketSentDelay:0,avgPacketSentDelay:0,maxLossRate:"",avgLossRate:"",encodePauseCount:0,maxQP:0,minQP:Number.MAX_SAFE_INTEGER,avgQP:0,count:0});if(_&&f){const s=_*f;if(s>c&&b>0){const{currentRoundTripTime:a=0,availableOutgoingBitrate:n}=this.pcStats["candidate-pair"]||{};c=s,this.uiQosData.sending={width:f,height:_,fps:i,rtt:Math.round(1e3*a),max_loss:1e3*e[t].maxLossRate,avg_loss:1e3*e[t].avgLossRate,jitter:Math.round(1e3*(w||0)),rate:e[t].avgSendBitRate,bandwidth:n}}}}const{numOfActive:T,numOfStopSending:R}=this.layerStatus;if(T&&T===R&&(te.globalTrace({logLevel:"error",log:"WMSC_ENCODE_FAILED: ".concat(T)}),Ot("WMSC_ENCODE_FAILED"),this._telemetry({type:W.ERROR_MESSAGE,data:{type:"WEBRTC_VIDEO_HEALTH_CHECK_FAILED"}})),v)if(this.networkReportDelay>5){const{currentRoundTripTime:e=0,availableOutgoingBitrate:t}=this.pcStats["candidate-pair"]||{},i=this._getNetworkState(d,e,t);this._sendNetworkState(Dt({isUplink:!0},i))}else this.networkReportDelay++;0===c&&(this.uiQosData.sending=Dt(Dt({},this.uiQosData.sending),{},{fps:0,width:0,height:0}))}_generateReceiverStatisticData(e){const t=this.mIdMgr.mIdResource;let i=0,s=0;for(const h in this.pcStats["video-inbound-rtp"]){const l=this.pcStats["video-inbound-rtp"][h];let{mid:u}=l;u||(u=this.mIdMgr.ssrcMidMap.get(l.ssrc));const{userId:m}=t.get(u)||{};let p=-1;if(m&&(p=this.mIdMgr.getVideoSizeByUserId(m),-1===p&&m===this.activeSpeaker&&(p=this.mIdMgr.getVideoSizeByUserId(I))),u&&p>-1){let t;this._captureRawRecvData(l);let p=0,g=!1,S=!1;const{framesPerSecond:_="",timestamp:v="",framesDecoded:f="",frameWidth:y="",frameHeight:M="",bytesReceived:C="",framesReceived:I="",totalDecodeTime:E="",packetsReceived:T="",packetsLost:R="",jitter:A="",lastPacketReceivedTimestamp:b=0,fecPacketsReceived:w=0,retransmittedPacketsReceived:D=0,jitterBufferEmittedCount:L,decoderImplementation:O,estimatedPlayoutTimestamp:P,jitterBufferDelay:V}=l,B=this.mIdMgr.getAudioMidByUserId(m),N=At.getEstimatePlayoutTimestampFromStatsByMid(e,B);if(this.pcStats.receiverStatisticData[m]){var a;this.pcStats.receiverStatisticData[m].count++;const{maxFps:e,minFps:s,maxDecodeTime:n,minDecodeTime:o,maxLossRate:r,maxBt:c,minBt:d,maxJitter:l,minLastRecvGap:I,maxLastRecvGap:B,avgLastRecvGap:k,count:U,maxAVSyncDelay:x,minAVSyncDelay:F,avSyncDelayArray:W,minJitterBufferDelay:z,maxJitterBufferDelay:j,maxAppAVSyncDelay:G,minAppAVSyncDelay:H,appAVSyncDelayArray:Q}=this.pcStats.receiverStatisticData[m],q=this.pcStats["prev-video-inbound-rtp"][h],Y=this.pcStats["begin-video-inbound-rtp"][h],{timestamp:K,framesDecoded:J,totalDecodeTime:X,packetsLost:Z,packetsReceived:$,bytesReceived:ee,fecPacketsReceived:ie=0,retransmittedPacketsReceived:se=0,jitterBufferEmittedCount:ae=0,pliCount:ne=0,jitterBufferDelay:oe=0}=Y||{},{packetsLost:re,packetsReceived:ce,totalDecodeTime:de,framesDecoded:he,bytesReceived:le,timestamp:ue,lastPacketReceivedTimestamp:me,fecPacketsReceived:pe=0,retransmittedPacketsReceived:ge=0,jitterBufferEmittedCount:Se=0,jitterBufferDelay:_e=0}=q||{};p=f-he,0===p&&L>Se&&this.pcStats.receiverStatisticData[m].decodePausedCount++,"NullVideoDecoder"===O&&this.shouldReportNullDecoderError&&(te.globalTrace({logLevel:"error",log:"WMSC_NULLDECODER: ".concat(u)}),Ot("WMSC_NULLDECODER,".concat(u)),this.shouldReportNullDecoderError=!1);const ve=T-$-(w-ie)-(D-se),fe=(R-re)/(T-ce-(w-pe)-(D-ge)+(R-re))||0,ye=Math.ceil((E-de)/(f-he)*1e3)||0;t=8*(C-le)/((v-ue)/1e3);const Me=8*(C-ee)/((v-K)/1e3);if(me){const e=parseInt(b-me,10);this.pcStats.receiverStatisticData[m].minLastRecvGap=Math.min(I,e),this.pcStats.receiverStatisticData[m].maxLastRecvGap=Math.max(B,e),this.pcStats.receiverStatisticData[m].avgLastRecvGap=parseInt((k*(U-1)+e)/U,10),0===e&&this.pcStats.receiverStatisticData[m].noDataCount++}else this.pcStats.receiverStatisticData[m].minLastRecvGap=0,this.pcStats.receiverStatisticData[m].noDataCount++;if(this.pcStats.receiverStatisticData[m].maxFps=Math.max(e,_),this.pcStats.receiverStatisticData[m].minFps=Math.min(s,_),this.pcStats.receiverStatisticData[m].avgFps=Math.round((f-J)/((v-K)/1e3)),this.pcStats.receiverStatisticData[m].maxDecodeTime=Math.max(n,ye),this.pcStats.receiverStatisticData[m].minDecodeTime=Math.min(ye,o),this.pcStats.receiverStatisticData[m].avgDecodeTime=Math.ceil((E-X)/(f-J)*1e3)||0,this.pcStats.receiverStatisticData[m].prevTotalDecodeTime=E,this.pcStats.receiverStatisticData[m].prevFramesDecoded=f,this.pcStats.receiverStatisticData[m].maxLossRate=Math.max(r,fe),this.pcStats.receiverStatisticData[m].avgLossRate=(R-Z)/(ve+(R-Z))||0,this.pcStats.receiverStatisticData[m].maxJitter=Math.max(l,A),this.pcStats.receiverStatisticData[m].maxBt=Math.max(t,c),this.pcStats.receiverStatisticData[m].minBt=Math.min(t,d),this.pcStats.receiverStatisticData[m].avgBt=Me,i=Math.max(this.pcStats.receiverStatisticData[m].avgLossRate,i),P&&N){let e=N-P;this.pcStats.receiverStatisticData[m].audioEstimatedPlayoutTimestamp=N,W.push(e),this.pcStats.receiverStatisticData[m].maxAVSyncDelay=Math.max(x,e),this.pcStats.receiverStatisticData[m].minAVSyncDelay=Math.min(F,e),this.pcStats.receiverStatisticData[m].avgAVSyncDelay=Math.round(W.reduce(((e,t)=>e+t),0)/W.length)}let Ce=null===(a=this.avSyncMgr)||void 0===a?void 0:a.getAVSyncDiff(m);if(Ce){const{diff:e,audioNtpTimestamp:t,videoNtpTimestamp:i}=Ce;N||(this.pcStats.receiverStatisticData[m].audioEstimatedPlayoutTimestamp=t),this.pcStats.receiverStatisticData[m].videoEstimatedPlayoutTimestamp=i,Q.push(e),this.pcStats.receiverStatisticData[m].maxAppAVSyncDelay=Math.max(G,e),this.pcStats.receiverStatisticData[m].minAppAVSyncDelay=Math.min(H,e),this.pcStats.receiverStatisticData[m].avgAppAVSyncDelay=Math.round(Q.reduce(((e,t)=>e+t),0)/Q.length)}if(L>0&&void 0!==V){let e=(V-_e)/(L-Se),t=(V-oe)/(L-ae);e=Math.round(1e3*e),t=Math.round(1e3*t),e&&(this.pcStats.receiverStatisticData[m].maxJitterBufferDelay=Math.max(j,e),this.pcStats.receiverStatisticData[m].minJitterBufferDelay=Math.min(z,e)),t&&(this.pcStats.receiverStatisticData[m].avgJitterBufferDelay=t)}this.pcStats.receiverStatisticData[m].ssrc=parseInt(h,10),this.recvVideoQuality[m]?(this.recvVideoQuality[m].width===y&&this.recvVideoQuality[m].height===M||(this.recvVideoQuality[m].width=y,this.recvVideoQuality[m].height=M,g=!0),this.recvVideoQuality[m].fps!==_&&(this.recvVideoQuality[m].fps=_,S=!0)):(this.recvVideoQuality[m]={width:y,height:M,fps:_},g=!0,S=!0)}else t=8*C/I*_||"",this.pcStats.receiverStatisticData[m]={maxFps:_,minFps:_,avgFps:_,maxDecodeTime:0,minDecodeTime:Number.MAX_SAFE_INTEGER,avgDecodeTime:0,maxLossRate:0,avgLossRate:0,maxBt:t,minBt:t,avgBt:t,maxJitter:A,minLastRecvGap:Number.MAX_SAFE_INTEGER,maxLastRecvGap:0,avgLastRecvGap:0,noDataCount:0,count:0,decodePausedCount:0,maxAVSyncDelay:Number.MIN_SAFE_INTEGER,minAVSyncDelay:Number.MAX_SAFE_INTEGER,avgAVSyncDelay:"",avSyncDelayArray:[],maxAppAVSyncDelay:Number.MIN_SAFE_INTEGER,minAppAVSyncDelay:Number.MAX_SAFE_INTEGER,avgAppAVSyncDelay:"",appAVSyncDelayArray:[],maxJitterBufferDelay:0,minJitterBufferDelay:Number.MAX_SAFE_INTEGER,avgJitterBufferDelay:0,ssrc:parseInt(h,10)};if(y&&M){const e=y*M;if(e>s&&p>0){var n,o,r;const t=null===(n=this.mIdMgr)||void 0===n?void 0:n.getVideoTagsByUserId(m),{currentRoundTripTime:i=0,availableIncomingBitrate:a}=this.pcStats["candidate-pair"]||{};this.uiQosData.receiving={avg_loss:Math.max(1e3*this.pcStats.receiverStatisticData[m].avgLossRate,0),max_loss:Math.max(1e3*this.pcStats.receiverStatisticData[m].maxLossRate,0),fps:_||0,height:(null===(o=t[0])||void 0===o?void 0:o.videoHeight)||M,width:(null===(r=t[0])||void 0===r?void 0:r.videoWidth)||y,jitter:Math.round(1e3*(A||0)),rate:this.pcStats.receiverStatisticData[m].avgBt,rtt:Math.round(1e3*i),bandwidth:a},s=e}}if(g&&this.videoObserverEnabled){var c;const{width:e,height:t}=this.recvVideoQuality[m];null===(c=this._telemetry)||void 0===c||c.call(this,{type:W.CURRENT_DECODE_VIDEO_QUALITY,data:{ssrc:m,width:e,height:t,quality:(0,bt.jK)(e,t)}})}var d;S&&this.videoObserverFramerateEnabled&&(null===(d=this._telemetry)||void 0===d||d.call(this,{type:W.CURRENT_DECODE_VIDEO_FPS,data:{ssrc:m,fps:this.recvVideoQuality[m].fps}})),this.bToPrint&&this._renderStatsData(u,y,M,_,t);const k=this.detectDecodeFailed(m);if(k){const{codecId:e}=l,t=this.getRecvH264Profile(e);t||te.globalTrace({logLevel:"error",log:"WMSC_DECODE_FAILED_NP"});const i=Object.keys(this.subInfo).length,s="".concat(this.userId,"|").concat(u,"|").concat(i,"|").concat(k,"|").concat(t);return te.globalTrace({logLevel:"error",log:"WMSC_DECODE_FAILED: ".concat(s)}),Ot("WMSC_DECODE_FAILED:".concat(s)),void(t&&this.onDecodeError&&this.onDecodeError(t))}}}const{currentRoundTripTime:h=0}=this.pcStats["candidate-pair"]||{},l=this._getNetworkState(i,h);this._sendNetworkState(Dt({isUplink:!1},l)),0===s&&(this.uiQosData.receiving=Dt(Dt({},this.uiQosData.receiving),{},{fps:0,width:0,height:0}))}_getVideoSenderLog(){var e;let t="",i="",s={};if(!$e.getPc())return;const a=$e.getSender();a&&null!==(e=a.track)&&void 0!==e&&e.getStats&&(s=a.track.getStats());const{fps:n="",receivingFps:o="",generatedFrames:r="",receivedFrames:c=""}=s,d=this.pcStats,{frames:h=""}=d["video-media-source"]||{};let l=0,u=0;for(const e in d["video-outbound-rtp"]){var m;const s="{[SEND".concat(this.ssrcLayerMap[e],"]}"),a="{[ENCO".concat(this.ssrcLayerMap[e],"]}"),{minEncodeFrameRate:p,maxEncodeFrameRate:g,avgEncodeFrameRate:S,minSendFrameRate:_,maxSendFrameRate:v,avgSendFrameRate:f,minSendBitRate:y,maxSendBitRate:M,avgSendBitRate:C,maxEncodeTime:I,minEncodeTime:E,avgEncodeTime:T,maxPacketSentDelay:R,minPacketSentDelay:A,avgPacketSentDelay:b,sendWidth:w="",sendHeight:D="",encodePauseCount:L,count:O=0,maxQP:P,minQP:V,avgQP:B}=d.senderStatisticData[e]||{};if(0===O)continue;let{minCaptureFps:N,maxCaptureFps:k,avgCaptureFps:U,captureHeight:x,captureWidth:F,minCamCaptureFps:W,maxCamCaptureFps:z,avgCamCaptureFps:j}=d.senderStatisticData;this.camStream||(W=N,z=k,j=U);const{keyFramesEncoded:G="",qualityLimitationReason:H="",pliCount:Q="",nackCount:q="",firCount:Y="",framesSent:K="",retransmittedPacketsSent:J="",powerEfficientEncoder:X,hugeFramesSent:Z="",packetsSent:$="",bytesSent:ee="",qualityLimitationDurations:te={},encoderImplementation:ie="",targetBitrate:se="",codecId:ae,active:ne,qpSum:oe="",framesEncoded:re=""}=d["video-outbound-rtp"][e],{framesSent:ce}=d["begin-video-outbound-rtp"][e],{bandwidth:de="",cpu:he="",none:le="",other:ue=""}=te,{mimeType:me="h264",sdpFmtpLine:pe=""}=(null===(m=d.codec)||void 0===m?void 0:m[ae])||{};let ge="";const Se=pe.match(/profile-level-id=([A-Za-z0-9]+);/);Se&&(ge=Se[1]);let _e=-1!==me.toLowerCase().indexOf("h264")?0:2;X&&(_e|=1);const ve=w*D;K-ce>0&&ve>l&&(l=ve,u=this.ssrcLayerMap[e]),t+="".concat(s,",").concat(this.maxSubscribedSize,",").concat(F,",").concat(x,",").concat(k,",").concat(N,",").concat(U,",,,,,,,").concat(g,",").concat(p,",").concat(S,",").concat(M,",").concat(y,",").concat(C,",").concat(v,",").concat(_,",").concat(f,",").concat(w,",").concat(D,",").concat(K,",,,,").concat(z,",").concat(W,",").concat(j,",").concat(isNaN(R)?"":R,",").concat(isNaN(A)?"":A,",").concat(isNaN(b)?"":b,",").concat($,",").concat(ee,",").concat(G,",").concat(Z,",").concat(q,",").concat(Y,",").concat(Q,",").concat(J,",").concat(H,",").concat(de,",").concat(he,",").concat(ue,",").concat(le,",").concat(se,",").concat(h,",").concat(L,",").concat(void 0===ne?"":ne,",").concat(O,",").concat(n,",").concat(o,",").concat(r,",").concat(c,",").concat(this.ssrcLayerMap[e],",").concat(oe,",").concat(B,",").concat(P,",").concat(V,",").concat(re,",").concat(e,","),i+="".concat(a,",").concat(I,",").concat(Vt(E),",").concat(T,",,").concat(_e,",").concat(ie,",").concat(ge,",")}return t=t.replace("{[SEND".concat(u,"]}"),"{[SEND]}"),i=i.replace("{[ENCO".concat(u,"]}"),"{[ENCO]}"),"".concat(t).concat(i)}_getVideoReceiveLog(){var e;const t=new Array(8).fill(0),i=new Array(8).fill(0);let s,a=-1;const n={};for(const e in this.pcStats.receiverStatisticData){var o,r,c,d,h;const{maxFps:t,minFps:M,avgFps:C,maxBt:E,minBt:T,avgBt:R,minLastRecvGap:A,maxLastRecvGap:b,avgLastRecvGap:w,noDataCount:D,count:L,decodePausedCount:O,maxAVSyncDelay:P,minAVSyncDelay:V,avgAVSyncDelay:B,audioEstimatedPlayoutTimestamp:N="",videoEstimatedPlayoutTimestamp:k="",maxJitterBufferDelay:U,minJitterBufferDelay:x,avgJitterBufferDelay:F,maxAppAVSyncDelay:W,minAppAVSyncDelay:z,avgAppAVSyncDelay:j,appAVSyncDelayArray:G,ssrc:H=""}=(null===(o=this.pcStats.receiverStatisticData)||void 0===o?void 0:o[e])||{},Q=this.pcStats["video-inbound-rtp"][H]||{},q=this.pcStats["begin-video-inbound-rtp"][H]||{};let Y="";null!=G&&G.length&&(Y=Math.round(G.reduce(((e,t)=>e+Math.abs(t)),0)/G.length));const{framesReceived:K="",framesDropped:J="",framesDecoded:X="",totalProcessingDelay:Z=""}=q,{frameHeight:$=0,frameWidth:ee=0,freezeCount:te="",framesReceived:ie="",framesDropped:se="",keyFramesDecoded:ae="",pauseCount:ne="",nackCount:oe="",firCount:re="",pliCount:ce="",totalProcessingDelay:de="",fecPacketsReceived:he="",retransmittedPacketsReceived:le="",framesDecoded:ue="",bytesReceived:me="",packetsReceived:pe="",packetsLost:ge="",jitterBufferEmittedCount:Se="",estimatedPlayoutTimestamp:_e="",jitterBufferTargetDelay:ve,framesAssembledFromMultiplePackets:fe="",totalAssemblyTime:ye,timestamp:Me,mid:Ce,framesPerSecond:Ie="",qpSum:Ee="",totalDecodeTime:Te,jitter:Re="",totalInterFrameDelay:Ae="",totalSquaredInterFrameDelay:be="",totalPausesDuration:we="",totalFreezesDuration:De="",lastPacketReceivedTimestamp:Le="",headerBytesReceived:Oe="",packetsDiscarded:Pe="",fecBytesReceived:Ve="",fecPacketsDiscarded:Be="",jitterBufferDelay:Ne="",jitterBufferMinimumDelay:ke="",powerEfficientDecoder:Ue="",retransmittedBytesReceived:xe="",codecId:Fe}=Q,{payloadType:We=""}=(null===(r=this.pcStats.codec)||void 0===r?void 0:r[Fe])||{},ze=ie-K,je=se-J,Ge=(je/ze||0).toFixed(2),He=((de-Z)/(ue-X)*1e3||0).toFixed(2),Qe=ue-X;if(void 0!==this.subInfo[e]||void 0!==this.subInfo[I]&&parseInt(e,10)===this.activeSpeaker){const t=ee*$;t>a&&(a=t,s=parseInt(e,10)),t>0&&Qe>0&&i[(0,bt.jK)(ee,$)]++}let qe;parseInt(e,10)===this.activeSpeaker&&(qe=this.mIdMgr.getVideoTagsByUserId(I)),0===(null===(c=qe)||void 0===c?void 0:c.length)&&(qe=this.mIdMgr.getVideoTagsByUserId(parseInt(e,10)));let Ye="",Ke="",Je="";if(null!==(d=qe)&&void 0!==d&&d.length){const e=qe[0];Ye=e.currentTime>0&&!e.paused&&!e.ended&&e.readyState>2?1:0;const t=e.getVideoPlaybackQuality();Je=t.droppedVideoFrames,Ke=t.totalVideoFrames-Je}const Xe=void 0===ye?"":Math.round(1e3*ye);var l,u,m,p,g,S,_,v,f,y;n[e]="".concat(t,",").concat(M,",").concat(C,",").concat(ee,",").concat($,",").concat(e,",").concat(L,",").concat(D,",,,,,,,,").concat(_e||k,",").concat(N,",,,,").concat(ze,",").concat(je,",").concat(Ge,",").concat(null!==(h=this.subInfo[e])&&void 0!==h?h:"",",,,,").concat(Qe,",").concat(Ye,",").concat(Ke,",").concat(Je,",").concat((E||0).toFixed(2),",").concat((T||0).toFixed(2),",").concat((R||0).toFixed(2),",").concat(pe,",").concat(ge,",").concat(me,",").concat(ae,",").concat(ne,",").concat(te,",").concat(oe,",").concat(re,",").concat(ce,",").concat(he,",").concat(le,",").concat(He,",").concat(Math.round(1e3*ve),",").concat(Se,",").concat(b,",").concat(A,",").concat(w,",").concat(O,",").concat(Pt(P),",").concat(Vt(V),",").concat(B,",").concat(U,",").concat(x,",").concat(F,",").concat(H,",").concat(this.mIdMgr.ssrcMidMap.get(H),",").concat(Xe,",").concat(fe,",").concat(Pt(W),",").concat(Vt(z),",").concat(j,",").concat(Y),this.reportCount%2==0&&H&&Me&&(this.rawRTPInboundStats[H]="".concat(Me,",").concat(H,",").concat(pe,",").concat(ge,",").concat(Re,",").concat(Ce||this.mIdMgr.ssrcMidMap.get(H),",").concat(ue,",").concat(ae,",").concat(Ke,",").concat(se,",").concat(ee,",").concat($,",").concat(Ie,",").concat(Ee,",").concat(null==Te||null===(l=Te.toFixed)||void 0===l?void 0:l.call(Te,3),",").concat(null==Ae||null===(u=Ae.toFixed)||void 0===u?void 0:u.call(Ae,3),",").concat(null==be||null===(m=be.toFixed)||void 0===m?void 0:m.call(be,3),",").concat(ne,",").concat(null==we||null===(p=we.toFixed)||void 0===p?void 0:p.call(we,3),",").concat(te,",").concat(null==De||null===(g=De.toFixed)||void 0===g?void 0:g.call(De,3),",").concat(Le,",").concat(Oe,",").concat(Pe,",").concat(Ve,",").concat(he,",").concat(Be,",").concat(me,",").concat(oe,",").concat(re,",").concat(ce,",").concat(null==de||null===(S=de.toFixed)||void 0===S?void 0:S.call(de,3),",").concat(_e,",").concat(null==Ne||null===(_=Ne.toFixed)||void 0===_?void 0:_.call(Ne,3),",").concat(null==ve||null===(v=ve.toFixed)||void 0===v?void 0:v.call(ve,3),",").concat(Se,",").concat(null==ke||null===(f=ke.toFixed)||void 0===f?void 0:f.call(ke,3),",").concat(ie,",").concat(Ue,",").concat(fe,",").concat(null==ye||null===(y=ye.toFixed)||void 0===y?void 0:y.call(ye,3),",").concat(le,",").concat(xe,",").concat(We))}this.activeSpeaker&&null!==(e=this.pcStats.receiverStatisticData)&&void 0!==e&&e[this.activeSpeaker]&&void 0!==this.subInfo[I]?this.recordUserId=this.activeSpeaker:this.recordUserId=s;for(const e in this.subInfo)t[this.subInfo[e]]++;const M="{[RECV]},".concat(t.join(","),",").concat(i.join(","),",");if(this.recvStatisticData[(new Date).toUTCString()]=n,this.reportCount%4==0)try{const e=JSON.stringify(this.recvStatisticData);q(e,E.GZIP_BASE64).then((e=>{te.globalTrace({logLevel:"log",log:"WCL_WB_VIDEO,".concat(e)}),this.recvStatisticData={}})).catch((t=>{te.globalTrace({logLevel:"error",log:"WMSC compress video log failed",errorEvent:t}),te.globalTrace({logLevel:"log",log:"WCL_WB_VIDEO,".concat(e)}),this.recvStatisticData={}}))}catch(e){te.globalTrace({logLevel:"error",log:"WMSC_Video_Log_Parse_Failed",errorEvent:e}),this.recvStatisticData={}}return n[this.recordUserId]?"".concat(M).concat(n[this.recordUserId],","):M}_getVideoDecodeLog(){var e,t;if(null===(e=this.pcStats.receiverStatisticData)||void 0===e||!e[this.recordUserId])return"";const{maxDecodeTime:i,minDecodeTime:s,avgDecodeTime:a,ssrc:n}=this.pcStats.receiverStatisticData[this.recordUserId],{powerEfficientDecoder:o,codecId:r,decoderImplementation:c=""}=this.pcStats["video-inbound-rtp"][n]||{},d=(null===(t=this.pcStats.codec)||void 0===t?void 0:t[r])||{},h=this.getRecvH264Profile(r),{mimeType:l="h264"}=d,u=(-1!==l.toLowerCase().indexOf("h264")?0:2)|(o?1:0);return"{[DECO]},".concat(i,",").concat(Vt(s),",").concat(a,",,").concat(u,",").concat(c,",").concat(h,",")}_getDownLinkLog(){var e,t;const{maxLossRate:i="",avgLossRate:s="",maxJitter:a="",ssrc:n}=(null===(e=this.pcStats.receiverStatisticData)||void 0===e?void 0:e[this.recordUserId])||{},o=(null===(t=this.pcStats["video-inbound-rtp"])||void 0===t?void 0:t[n])||{},{packetsLost:r="",jitter:c=""}=o,d=this.pcStats["remote-candidate"]||{},h=this.pcStats["candidate-pair"]||{},l=this.pcStats["begin-candidate-pair"]||{},{maxRtt:u}=this.pcStats.statisticData||{},{protocol:m}=d,{availableIncomingBitrate:p="",bytesReceived:g="",timestamp:S="",totalRoundTripTime:_="",responsesReceived:v="",packetsReceived:f=""}=h,{bytesReceived:y,timestamp:M}=l,C=(8*(g-y)/((S-M)/1e3)).toFixed(2),I=Math.round(_/v*1e3)||"";return"RWG_WB_DOWNLINK_NETWORK,".concat(this.userId,",3,").concat("udp"===m?0:1,",").concat(Math.round(S/1e3),",,").concat(p,",").concat(C,",").concat(Math.round(1e3*s),",").concat(Math.round(1e3*i),",,,,").concat(I,",").concat(1e3*u,",").concat(f,",").concat(r,",,,,,,,,,").concat(Math.round(1e3*c),",").concat(Math.round(1e3*a))}_getUpLinkLog(){let e="";const t=this.pcStats["candidate-pair"]||{},i=this.pcStats["remote-candidate"]||{},s=this.pcStats["video-remote-inbound-rtp"]||{},{timestamp:a,availableOutgoingBitrate:n="",totalRoundTripTime:o,responsesReceived:r}=t,{protocol:c}=i;let{maxRtt:d=""}=this.pcStats.statisticData;d=d?1e3*d:"";let h="",l="",u="",m="",p="",g="",S="";for(const e in this.pcStats["video-outbound-rtp"]){const{maxJitter:t,avgLossRate:i,maxLossRate:a}=this.pcStats.senderStatisticData[e]||{},{packetsLost:n,jitter:o}=s[e]||{},{packetsSent:r,timestamp:c,bytesSent:d}=this.pcStats["video-outbound-rtp"][e]||{},{bytesSent:_,timestamp:v}=this.pcStats["begin-video-outbound-rtp"][e]||{};t&&!u&&(u=Math.round(1e3*t)),!i&&0!==i||h||(h=Math.round(1e3*i)),!a&&0!==a||l||(l=Math.round(1e3*a)),o&&!p&&(p=Math.round(1e3*o)),void 0!==d&&void 0!==_&&(g=parseInt(g+8e3*(d-_)/(c-v),10)),(r||0===r)&&(S=parseInt(S+r,10)),(n||0===n)&&(m=parseInt(m+n,10))}const _=Math.round(o/r*1e3)||"";return e+=",3,".concat("udp"===c?0:1,",").concat(Math.round(a/1e3),",,").concat(n,",").concat(g,",").concat(h,",").concat(l,",,,,").concat(_,",").concat(d,",").concat(S,",").concat(m,",,,,,,,,,").concat(p,",").concat(u),e?"RWG_WB_UPLINK_NETWORK,".concat(this.userId).concat(e):""}_getStats(){if(this.isWebRTCVideoEnabled){var e;let t=0;null!==(e=x.videoSettings)&&void 0!==e&&e.hdVideoEnabled&&(t|=kt.HD_VIDEO),this.isDualCall&&(t|=kt.DUAL_CALL);let i,s,a="WCL_WB_MCM_VIDEO,".concat(this.userId,",,").concat(document.hidden?0:1,",").concat(t,",");const n=this._getVideoSenderLog(),o=this._getVideoReceiveLog(),r=this._getVideoDecodeLog();this.reportCount%2==0&&(i=this._getDownLinkLog(),s=this._getUpLinkLog()),a+=n+o+r+"{[END]}",a&&te.directSendMonitorLog(a),i&&te.directSendMonitorLog(i),s&&te.directSendMonitorLog(s),this.bToPrint&&(a&&Lt.log("_getStats, video log: ".concat(a)),i&&Lt.log("_getStats, downlink log: ".concat(i)),s&&Lt.log("_getStats, uplink log: ".concat(s)))}this.candidatePairLog&&(te.directSendMonitorLog("WMSC_CANDIDATE-PAIR: ".concat(this.candidatePairLog)),this.candidatePairLog="")}_renderStatsData(e){}sendSdpLog(e,t){try{const a=he.parseSdp(t),{media:n=[]}=a;let o,r;var i,s;n.forEach((t=>{const{ssrcGroups:i,mid:s,type:a,direction:n,ssrcs:c,codecs:d=[]}=t;if("sendonly"===n&&"ANSWER"===e&&"video"===a&&!this.recvCodecProfile){const{codecParams:e}=d[0]||{};e&&(this.recvCodecProfile=e.get("profile-level-id"))}i.forEach((e=>{let{semantics:t,ssrcs:i}=e;"SIM"===t&&i.forEach(((e,t)=>{this.ssrcLayerMap[e]=t}))})),c.forEach((e=>{let{ssrc:t}=e;this.mIdMgr.ssrcMidMap.set(t,s)})),"video"===a&&("sendonly"!==n||o||(o=t),"recvonly"!==n||r||(r=t))})),o&&te.directSendMonitorLog(this.generateSdpLog(e,o,null===(i=a.session)||void 0===i?void 0:i.groups)),r&&te.directSendMonitorLog(this.generateSdpLog(e,r,null===(s=a.session)||void 0===s?void 0:s.groups)),q(t,E.GZIP_BASE64).then((t=>{te.globalTrace({logLevel:"log",log:"WCL_WB_SDP-".concat(e,"-").concat(t)})}))}catch(i){te.globalTrace({logLevel:"error",log:"WCL_WB_SDP-".concat(e,"-").concat(t),errorEvent:i}),Ot("WMSC_SDPLE: ".concat(e))}}_getCandidatePairLog(e){const{localCandidateId:t,remoteCandidateId:i,nominated:s,state:a,packetsReceived:n,packetsSent:o,bytesReceived:r,bytesSent:c,currentRoundTripTime:d,requestsSent:h,responsesReceived:l,packetsDiscardedOnSend:u,bytesDiscardedOnSend:m,availableOutgoingBitrate:p="",priority:g=""}=e;return"".concat(g,",").concat(t,",").concat(i,",").concat(this.iceCandidatePairState[a],",").concat(s?1:0,",").concat(n,",").concat(o,",").concat(r,",").concat(c,",").concat(d,",").concat(h,",").concat(l,",").concat(u,",").concat(m,",").concat(p,",")}_getCandidateLog(e){const{id:t,candidateType:i,port:s,priority:a,protocol:n,type:o,usernameFragment:r,url:c="",relayProtocol:d="",networkType:h=""}=e;return"".concat(t,",").concat(a,",").concat(n,",").concat(i,",").concat(s,",").concat(h,",").concat("remote-candidate"===o?1:0,",").concat(r,",").concat(c,",").concat(d,",")}onReceiverReport(e){const{begin:t,current:i}=this.ingressReport;this.ingressReport.prev=i,this.ingressReport.current=e,t||(this.ingressReport.begin=i)}_captureRawRecvData(e){if(!e)return;const{timestamp:t,framesDecoded:i="",totalDecodeTime:s="",jitterBufferEmittedCount:a="",framesReceived:n="",ssrc:o}=e;if(!o)return;const r=this.mIdMgr.ssrcMidMap.get(o),c="mid-".concat(r,"-ssrc-").concat(o);if(this.recvRawStats[c]){const{startTime:e}=this.recvRawStats[c],o=this.recvRawStats[c].framesDecoded.length,r=Math.floor((t-e)/1e3)-o;if(o+r>O)this._generateRecvRawLog(c),this.recvRawStats[c]={startTime:t,framesDecoded:[i],totalDecodeTime:[Math.round(1e3*s)],jitterBufferEmittedCount:[a],framesReceived:[n]};else for(let e=0;e<r;e++){const t=e===r-1;this.recvRawStats[c].framesDecoded.push(t?i:""),this.recvRawStats[c].totalDecodeTime.push(t?Math.round(1e3*s):""),this.recvRawStats[c].jitterBufferEmittedCount.push(t?a:""),this.recvRawStats[c].framesReceived.push(t?n:"")}}else this.recvRawStats[c]={startTime:t,framesDecoded:[i],totalDecodeTime:[Math.round(1e3*s)],jitterBufferEmittedCount:[a],framesReceived:[n]}}_captureRawSendData(e){if(!e)return;const{type:t}=e;if("outbound-rtp"===t){const{timestamp:t,framesSent:i,framesEncoded:s,totalEncodeTime:a,ssrc:n}=e,o="sim-".concat(this.ssrcLayerMap[n],"-ssrc-").concat(n);if(this.sendRawStats[o]){const{startTime:e}=this.sendRawStats[o],n=this.sendRawStats[o].framesSent.length,r=Math.floor((t-e)/1e3)-n;if(n+r>O)this._generateSendRawLog(o),this.sendRawStats[o]={startTime:t,framesSent:[i],framesEncoded:[s],totalEncodeTime:[Math.round(1e3*a)]};else for(let e=0;e<r;e++){const t=e===r-1;this.sendRawStats[o].framesSent.push(t?i:""),this.sendRawStats[o].framesEncoded.push(t?s:""),this.sendRawStats[o].totalEncodeTime.push(t?Math.round(1e3*a):"")}}else this.sendRawStats[o]={startTime:t,framesSent:[i],framesEncoded:[s],totalEncodeTime:[Math.round(1e3*a)]}}else if("media-source"===t){const{frames:t,timestamp:i}=e;if(!t&&0!==t)return;if(this.sendRawStats.capturedFrames){const{startTime:e}=this.sendRawStats.capturedFrames,s=this.sendRawStats.capturedFrames.frames.length,a=Math.floor((i-e)/1e3)-s;if(s+a>O)this._generateSendRawLog("capturedFrames"),this.sendRawStats.capturedFrames={startTime:i,frames:[t]};else for(let e=0;e<a;e++){const i=e===a-1;this.sendRawStats.capturedFrames.frames.push(i?t:"")}}else this.sendRawStats.capturedFrames={startTime:i,frames:[t]}}}reportRawStats(){for(const e in this.sendRawStats)this._generateSendRawLog(e,!1);for(const e in this.recvRawStats)this._generateRecvRawLog(e,!1);this._uploadRawStats()}_generateRecvRawLog(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];const{startTime:i,framesDecoded:s,framesReceived:a,jitterBufferEmittedCount:n,totalDecodeTime:o}=this.recvRawStats[e],r="".concat(this.userId,",0,").concat(e,",").concat(Math.round(i/1e3),",framesDecoded=").concat(JSON.stringify(s),",framesReceived=").concat(JSON.stringify(a),",jitterBufferEmittedCount=").concat(JSON.stringify(n),",totalDecodeTime=").concat(JSON.stringify(o));this._sendRawLog(r,t),delete this.recvRawStats[e]}_generateSendRawLog(e){let t,i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if("capturedFrames"===e){const{frames:i,startTime:s}=this.sendRawStats[e];t="".concat(this.userId,",1,").concat(e,",").concat(Math.round(s/1e3),",capturedFrames=").concat(JSON.stringify(i))}else{const{startTime:i,framesEncoded:s,framesSent:a,totalEncodeTime:n}=this.sendRawStats[e];t="".concat(this.userId,",1,").concat(e,",").concat(Math.round(i/1e3),",framesEncoded=").concat(JSON.stringify(s),",framesSent=").concat(JSON.stringify(a),",totalEncodeTime=").concat(JSON.stringify(n))}this._sendRawLog(t,i),delete this.sendRawStats[e]}_sendRawLog(e,t){this.rawLog.push(e),t&&this.rawLog.length>P&&this._uploadRawStats()}_uploadRawStats(){if(this.rawLog.length>0){const e=this.rawLog.join("|");this.rawLog=[],q(e,E.GZIP_BASE64).then((e=>{te.globalTrace({logLevel:"directReport",log:e,tags:["WCL_WB_RAW_STATS"]})})).catch((()=>{te.globalTrace({logLevel:"directReport",log:rawLog,tags:["WCL_WB_RAW_STATS"]})}))}}detectDecodeFailed(e){const{decodePausedCount:t,ssrc:i}=this.pcStats.receiverStatisticData[e],{framesDecoded:s,jitterBufferEmittedCount:a="",pliCount:n,packetsLost:o,framesReceived:r=""}=this.pcStats["begin-video-inbound-rtp"][i],{framesDecoded:c,jitterBufferEmittedCount:d="",pliCount:h,packetsLost:l,decoderImplementation:u,framesReceived:m="",codecId:p}=this.pcStats["video-inbound-rtp"][i],g="".concat(c,"|").concat(s,"|").concat(d,"|").concat(a,"|").concat(l,"|").concat(o,"|").concat(h,"|").concat(n,"|").concat(u,"|").concat(t,"|").concat(m,"|").concat(r);if(c>s)return!1;if("NullVideoDecoder"===u)return g;if(d-a<=5)return!d&&m-r>150&&g;if(0===c&&h>n&&l===o)return g;const S=this.getRecvH264Profile(p),_=$e.ingressCodecList.some((e=>{let{codecParams:t}=e;const i=t.get("profile-level-id");return!!i&&$(i)}));return(Z(S)&&_&&d-a>=15&&c===s&&c>0||t>10)&&g}getRecvH264Profile(e){if(this.pcStats.codec){var t;const i=null===(t=this.pcStats.codec)||void 0===t?void 0:t[e];if(i){const{sdpFmtpLine:e=""}=i,t=e.match(/profile-level-id=([A-Za-z0-9]+);/);if(t)return t[1]}}return this.recvCodecProfile}onDualCallState(e){let{isDualCall:t}=e;this.isDualCall=t}generateSdpLog(e,t){var i;let s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[];const{direction:a="",codecs:n=[],extensionMap:o,bandwidth:r,candidates:c,ssrcGroups:d=[]}=t,h=new Array(4).fill(-1),l=[],u={};let m="WCL_WB_SDP_".concat(e,",").concat(this.userId,",").concat((null===(i=s[0])||void 0===i?void 0:i.ids.length)||0,",").concat(this.sdpDirection[a],",");if(o)for(const[e,t]of o){const{uri:i}=t,s=this.rtpHeaderExt[i];void 0!==s&&(h[s]=e)}m+=h.join(",")+",",n.forEach((e=>{const{codecName:t,codecParams:i,payloadType:s,associatedPayloadType:a=""}=e;"H264"===t&&i?"1"===i.get("packetization-mode")&&(l.push(s),l.push(i.get("profile-level-id")),l.push(i.get("max-mbps")||""),l.push(i.get("max-fs")||""),l.push(i.get("x-google-start-bitrate")||""),l.push(i.get("x-google-max-bitrate")||""),l.push(i.get("x-google-min-bitrate")||""),l.push(i.get("x-google-per-layer-pli")||"")):"rtx"===t&&(u[a]=s)}));for(let e=0,t=l.length;e<t;e+=8){const t=l[e];m+="".concat(t,",").concat(l[e+1],",").concat(l[e+2],",").concat(l[e+3],",").concat(l[e+4],",").concat(l[e+5],",").concat(l[e+6],",").concat(l[e+7],",").concat(u[t],",")}return d.forEach((e=>{let{semantics:t,ssrcs:i}=e;"FID"===t&&(m+="".concat(i.join(","),","))})),m+="".concat(r||"",","),c&&c.length>0&&c.forEach((e=>{let{transport:t,address:i,port:s,priority:a}=e;m+="".concat(a,",").concat("udp"===t?0:1,",").concat(i,",").concat(s,",")})),m}handleStatsReport(e){var t;const i={},s={};let a,n="",o="";var r,c;if(e.forEach((e=>{const{kind:t,type:a}=e,r="".concat(t?t+"-":"").concat(a),c="begin-".concat(r),d="prev-".concat(r);if("candidate-pair"===a){const{id:t}=e;i[t]=e,o+=this._getCandidatePairLog(e)}else if("remote-candidate"===a||"local-candidate"===a){const{id:t}=e;s[t]=e,n+=this._getCandidateLog(e)}else if("codec"===a){const{id:t,mimeType:i}=e;"video/H264"===i&&(this.pcStats[r]||(this.pcStats[r]={}),this.pcStats[r][t]=e)}else if("video"!==t||"inbound-rtp"!==a&&"remote-outbound-rtp"!==a&&"outbound-rtp"!==a&&"remote-inbound-rtp"!==a)"video"===t&&"media-source"===a?(this.pcStats[d]=this.pcStats[r],this.pcStats[r]=e,this.pcStats[c]||(this.pcStats[c]=e)):this.pcStats[r]=e;else{const{ssrc:t}=e;this.pcStats[r]||(this.pcStats[r]={}),this.pcStats[d]||(this.pcStats[d]={}),this.pcStats[d][t]=this.pcStats[r][t],this.pcStats[r][t]=e,this.pcStats[c]&&this.pcStats[c][t]||(this.pcStats[c]=Dt(Dt({},this.pcStats[c]),{},{[t]:e}))}})),"connected"===(null===(t=this.pcStats.transport)||void 0===t?void 0:t.dtlsState)?a=i[this.pcStats.transport.selectedCandidatePairId]:(a=Object.values(i).find((e=>e.selected&&"succeeded"===e.state)),a&&(a.currentRoundTripTime=(null!==(r=null===(c=this.qosReport)||void 0===c||null===(c=c.uplink)||void 0===c?void 0:c.rtt)&&void 0!==r?r:0)/1e3)),a){var d,h,l,u,m,p,g,S;null!==(h=(d=a).availableOutgoingBitrate)&&void 0!==h||(d.availableOutgoingBitrate=1e3*(null!==(l=null===(u=this.qosReport)||void 0===u||null===(u=u.uplink)||void 0===u?void 0:u.bw)&&void 0!==l?l:0)),null!==(p=(m=a).availableIncomingBitrate)&&void 0!==p||(m.availableIncomingBitrate=1e3*(null!==(g=null===(S=this.qosReport)||void 0===S||null===(S=S.downlink)||void 0===S?void 0:S.bw)&&void 0!==g?g:0));const{localCandidateId:e,remoteCandidateId:t}=a;this.pcStats["remote-candidate"]=s[t],this.pcStats["local-candidate"]=s[e],this.pcStats["prev-candidate-pair"]=this.pcStats["candidate-pair"],this.pcStats["candidate-pair"]=a,this.pcStats["begin-candidate-pair"]||(this.pcStats["begin-candidate-pair"]=a)}this.candidateLog!==n&&(te.directSendMonitorLog("WMSC_CANDIDATE: ".concat(n)),this.candidateLog=n),this.candidatePairLog=o;const{currentRoundTripTime:_}=this.pcStats["candidate-pair"]||{},{maxRtt:v=0}=this.pcStats.statisticData;_&&(this.pcStats.statisticData.maxRtt=Math.max(_,v)),this._generateSenderStatisticData(),this._generateReceiverStatisticData(e),this._uploadRawRTPInboundStats(3),this.mIdMgr.onStatsReport(this.pcStats)}_uploadRawRTPInboundStats(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:30,t=1,i="";for(const s in this.rawRTPInboundStats){if(t>e)break;this.rawRTPInboundStats[s]&&(i+=(i?"|":"")+this.rawRTPInboundStats[s]),delete this.rawRTPInboundStats[s],t++,i.length>1500&&(te.directSendMonitorLog("WMSC_RTP_INBOUND,"+i),i="")}i&&te.directSendMonitorLog("WMSC_RTP_INBOUND,"+i)}};var xt=i(7007);class Ft extends xt.EventEmitter{constructor(e,t){super(),this.codecs=[],this.type=e,this.rtpTransceiver=t}stop(){this.rtpTransceiver.direction="inactive",this.emit(Ye.f7.NegotiationNeeded)}get transceiver(){return this.rtpTransceiver}get sender(){return this.rtpTransceiver.sender}getCodecs(){return this.codecs}setCodecs(e){this._setCodecs(e),this.emit(Ye.f7.CodecsChange,e)}_setCodecs(e){this.codecs=e}publishTrack(e){return t=this,i=void 0,a=function*(){return this.sender.replaceTrack(e||null)},new((s=void 0)||(s=Promise))((function(e,n){function o(e){try{c(a.next(e))}catch(e){n(e)}}function r(e){try{c(a.throw(e))}catch(e){n(e)}}function c(t){var i;t.done?e(t.value):(i=t.value,i instanceof s?i:new s((function(e){e(i)}))).then(o,r)}c((a=a.apply(t,i||[])).next())}));var t,i,s,a}}class Wt extends xt.EventEmitter{constructor(e,t){super(),this.codecs=[],this.type=e,this.rtpTransceiver=t}stop(){this.rtpTransceiver.stop(),this.emit(Ye.f7.NegotiationNeeded)}get transceiver(){return this.rtpTransceiver}get receiver(){return this.rtpTransceiver.receiver}getCodecs(){return this.codecs}setCodecs(e){this._setCodecs(e),this.emit(Ye.f7.CodecsChange,e)}_setCodecs(e){this.codecs=e}}var zt=function(e,t,i,s){return new(i||(i=Promise))((function(a,n){function o(e){try{c(s.next(e))}catch(e){n(e)}}function r(e){try{c(s.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?a(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}c((s=s.apply(e,t||[])).next())}))};class jt extends xt.EventEmitter{constructor(e){super(),this.sendTransceivers=new Map,this.recvTransceivers=new Map,this.nextMid=0,this.mids=new Map,this.mediaSourceId2Mid=new Map,this.localId2Mid=new Map,this.pendingTransceivers=[],this.mainEgressStreamId=he.generateUuid(),this.shareEgressStreamId=he.generateUuid(),this.config=Object.assign(Object.assign({},e),{bundlePolicy:"max-bundle"}),this.pc=_t.A.createPeerConnection(this.config),this.setupEventListeners(),this.startPollingStats()}createSendTransceiver(e,t){const i=(0,Ye.xv)(e),s=this.pc.addTransceiver(i,Object.assign({direction:"sendonly"},t)),a=new Ft(e,s);return a.on(Ye.f7.CodecsChange,(e=>this.onCodecsChange(a.mid,e))),a.on(Ye.f7.NegotiationNeeded,(()=>this.onNegotiationNeeded())),this.pendingTransceivers.push(a),a}createRecvTransceiver(e){const t=(0,Ye.xv)(e),i=this.pc.addTransceiver(t,{direction:"recvonly"}),s=new Wt(e,i);return s.on(Ye.f7.CodecsChange,(e=>this.onCodecsChange(s.mid,e))),s.on(Ye.f7.NegotiationNeeded,(()=>this.onNegotiationNeeded())),this.pendingTransceivers.push(s),s}getSendTransceiverByMid(e){return this.sendTransceivers.get(e)}getRecvTransceiverByMid(e){return this.recvTransceivers.get(e)}createOffer(e){return zt(this,void 0,void 0,(function*(){this.mids.clear();const t=yield this.pc.createOffer(e),i=he.parseSdp(t.sdp);return i.media.forEach(((e,t)=>{const{mid:i}=e;this.mids.set(i,t)})),this.offer=i,this.offer}))}setOffer(e){return zt(this,void 0,void 0,(function*(){if(!this.offer)throw new Error("Call createOffer() first.");let t;e?(this.offer=he.parseSdp(e),t=e):t=he.writeSdp(this.offer),yield this.pc.setLocalDescription({type:"offer",sdp:t}),this.pendingTransceivers=this.pendingTransceivers.filter((e=>{const{mid:t,direction:i}=e.transceiver;return!t||(e.mid=t,"sendonly"===i?this.sendTransceivers.set(t,e):"recvonly"===i&&this.recvTransceivers.set(t,e),!1)}))}))}setAnswer(e){return zt(this,void 0,void 0,(function*(){if(!e&&!this.answer)throw new Error("Answer is required for the first time negotiation");let t;return e?(this.answer=he.parseSdp(e),t=e):t=he.writeSdp(this.answer),this.pc.setRemoteDescription({type:"answer",sdp:t})}))}close(){var e;clearTimeout(this.statsTimeoutId),null===(e=this.pc)||void 0===e||e.close(),this.removeAllListeners()}getStats(e){return this.pc.getStats(e)}setupEventListeners(){this.pc.ontrack=e=>{this.emit(Ye.f7.Track,e);const t=this.recvTransceivers.get(e.transceiver.mid);t&&t.emit(Ye.f7.Track,e.track)},this.pc.onsignalingstatechange=()=>{this.emit(Ye.f7.SignalingStateChange,this.pc.signalingState)},this.pc.oniceconnectionstatechange=()=>{this.emit(Ye.f7.IceConnectionStateChange,this.pc.iceConnectionState)},this.pc.onconnectionstatechange=()=>{const e=this.pc.connectionState;this.emit(Ye.f7.ConnectionStateChange,e)},this.pc.onicegatheringstatechange=()=>{this.emit(Ye.f7.IceGatheringStateChange,this.pc.iceGatheringState)},this.pc.onicecandidateerror=e=>{this.emit(Ye.f7.IceCandidateError,e)}}addMidNum(){return this.nextMid++}startPollingStats(){return zt(this,void 0,void 0,(function*(){try{const e=yield this.pc.getStats();this.dispatchStats(e)}catch(e){console.error("Dispatch stats error",e)}this.statsTimeoutId=window.setTimeout((()=>{this.startPollingStats()}),Ye.Mr)}))}dispatchStats(e){this.emit(Ye.f7.StatsReport,e),e.forEach((e=>{var t,i,s,a;switch(e.type){case"local-candidate":this.emit(Ye.f7.LocalCandidateStats,e);break;case"remote-candidate":this.emit(Ye.f7.RemoteCandidateStats,e);break;case"candidate-pair":this.emit(Ye.f7.CandidatePairStats,e);break;case"transport":this.emit(Ye.f7.TransportStats,e);break;case"outbound-rtp":{const{id:i,mid:s,mediaSourceId:a}=e;this.localId2Mid.set(i,s),this.mediaSourceId2Mid.set(a,s),null===(t=this.sendTransceivers.get(s))||void 0===t||t.emit(Ye.f7.OutboundRtpStats,e)}break;case"remote-inbound-rtp":{const t=this.localId2Mid.get(e.localId);null===(i=this.sendTransceivers.get(t))||void 0===i||i.emit(Ye.f7.RemoteInboundRtpStats,e)}break;case"inbound-rtp":null===(s=this.recvTransceivers.get(e.mid))||void 0===s||s.emit(Ye.f7.InboundRtpStats,e);break;case"remote-outbound-rtp":default:break;case"media-source":{const t=this.mediaSourceId2Mid.get(e.id);null===(a=this.sendTransceivers.get(t))||void 0===a||a.emit(Ye.f7.MediaSourceStats,e)}}}))}onCodecsChange(e,t){return zt(this,void 0,void 0,(function*(){this.offer.media.forEach((i=>{i.mid===e&&(i.codecs=t)})),yield this.setLocalOfferAnswer()}))}setLocalOfferAnswer(){return zt(this,void 0,void 0,(function*(){if(this.offer){const e=he.writeSdp(this.offer);yield this.pc.setLocalDescription({type:"offer",sdp:e})}if(this.answer){const e=he.writeSdp(this.answer);yield this.pc.setLocalDescription({type:"answer",sdp:e})}}))}onNegotiationNeeded(){}removeUnusedTransceiver(){if(this.answer){const e=new Array(this.mids.size);this.answer.media.forEach((t=>{const{mid:i}=t,s=this.mids.get(i);void 0!==s&&(e[s]=t)})),this.answer.media=e,this.answer.session.groups[0].ids=[...this.offer.session.groups[0].ids]}}addMLineSDPToAnswer(e,t){const i=this.mids.get(e);void 0!==i&&(this.answer.media[i]=t)}removeMLineSDPFromAnswer(e){const t=this.mids.get(e);if(void 0!==t){const i=this.answer.media[t],{type:s,connection:a,protocol:n}=i;this.answer.media[t]={type:s,connection:a,protocol:n,mid:e,direction:"inactive",port:0,payloadTypes:[0],otherLines:[],extensionMap:new Map,codecs:[]},this.recvTransceivers.get(e)?this.recvTransceivers.delete(e):this.sendTransceivers.get(e)&&this.sendTransceivers.delete(e)}}get connectionState(){return this.pc.connectionState}getOffer(){return this.offer}getAnswer(){return this.answer}updateOfferIceCredential(e){this.offer&&he.updateIceCredential(this.offer,e)}updateAnswerIceCredential(e){this.answer&&he.updateIceCredential(this.answer,e)}get currentRemoteDescription(){return this.pc.currentRemoteDescription}setConfiguration(e){this.config=Object.assign(Object.assign({},this.config),e),this.pc.setConfiguration(this.config)}get signalingState(){return this.pc.signalingState}}var Gt=i(2689),Ht=i(559),Qt=i(5738),qt=i(9338),Yt=i(242),Kt=i(9482),Jt=i(9373),Xt=i(3656),Zt=i(5803);function $t(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,s)}return i}function ei(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?$t(Object(i),!0).forEach((function(t){(0,c.A)(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):$t(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class ti{constructor(e){let{mIdMgr:t,signalSendSink:i,messageCallback:s,userId:a}=e;this._mIdMgr=t,this._WMSCsignalSendSink=i,this._messageCallback=s,this._wmscPC=null,this._wmscMainAudioTransceiver=null,this._wmscShareAudioTransceiver=null,this._initialized=!1,this._isDestroyed=!1,this._webRTCWorkletManager=null,this._useWebRTCOnDesktop=!1,this._isRecvOnly=!1,this._audioStream=null,this._audioStreamCloning=null,this._shareAudioStream=null,this._recvMLineTemp=null,this._isMutedBySystem=!1,this._audioSpeakerSetErrorCnt=0,this._cleanUserEventFn=null,this._mid2RemoteRTCAudioPlayer=new Map,this._nodeId2VolumeMap=new Map,this._mainSessionNodeId2VolumeMap=new Map,this._codecDoAVSync=!1,this._AVsyncTimer=null,this._nodeId2NTPDescriptionMap=new Map,this._shareNodeId2NTPDescriptionMap=new Map,this._audioProfile=It.yu,this._isMuted=!1,this._audioMode=It.DY,this._isAudioPlayerError=!1,this._audioPlayerErrorCounter=new Map,this._recoverPlay1STimeout=null,this._showUplinkQosOnDashboard=!1,this._showDownlinkQosOnDashboard=!1,this._stopIncomingAudioFlag=!1,this._healthChecker=new Zt.A({webrtcAudio:this,onAudioEnergySentCheckResult:this._onAudioEnergySentCheckResult.bind(this),onPacketSentCheckResult:this._onPacketSentCheckResult.bind(this),onAudioEnergyReceivedCheckResult:this._onAudioEnergyReceivedCheckResult.bind(this)}),this._wmscAudioMonitor=new At({wmscAudio:this,userId:a,onBadNetwork:this._onBadNetworkDetected.bind(this),onHealthCheck:this._healthChecker.onCheck,onMonitorLog:this._onRequestReportMonitorLog.bind(this)}),document.addEventListener("visibilitychange",(()=>{"visible"===document.visibilityState&&this.triggerPlayerHealthCheck(It.vr.VISIBILITY_CHANGE)})),this.clearAllRemoteAudioPlayer(),this._interpretationEnable=!1,this._interpretationList=[],this._userLangMap=new Map,this._interpretationMuted=!1,this._interpretationCurrentLang=It.jw,this._interpreterSpeakingStatus=It.g3,this._inboundSourceVADBind=this.inboundSourceVAD.bind(this),this.playFailedTimeout=null,this.hasReportedPlayFailed=!1,this.normal_ssrc=null,this.share_ssrc=null,this.nodeId=this._convertUserId2NodeId(a)}get isMutedBySystem(){return this._isMutedBySystem}set isMutedBySystem(e){this._webRTCWorkletManager&&(this._webRTCWorkletManager.isMutedBySystem=e),this._isMutedBySystem=e}get isMuted(){return this._isMuted}get isAudioPlayerError(){return this._isAudioPlayerError}get audioSpeakerSetErrorCnt(){return this._audioSpeakerSetErrorCnt}set audioSpeakerSetErrorCnt(e){this._audioSpeakerSetErrorCnt=e}get doingDenoise(){var e;return null===(e=this._webRTCWorkletManager)||void 0===e?void 0:e.doingDenoise}initconfig(e){let{workletPath:t,recvOnly:i,codecDoAVSync:s,useWebRTCOnDesktop:a}=e;this._initialized||(this._initialized=!0,t&&(this._webRTCWorkletManager=new qt.v(this.setNormalAudioStream.bind(this),t)),this._isRecvOnly=!!i,this._codecDoAVSync=!!s,this._useWebRTCOnDesktop=a)}getUplinkMidOrSSRC2MediaType(e,t){var i;return!e&&t&&(e=null===(i=this._mIdMgr)||void 0===i?void 0:i.getMidBySsrc(t)),e==this._wmscMainAudioTransceiver.mid?Ye.zu.MainAudio:e==this._wmscShareAudioTransceiver.mid?Ye.zu.ShareAudio:null}triggerPlayerHealthCheckSuccessCallback(e){this.playFailedTimeout&&(clearTimeout(this.playFailedTimeout),this.playFailedTimeout=null),this.hasReportedPlayFailed&&((0,Ct._$)("triggerPlayerHealthCheck success-".concat(e)),this.notifyUIMessage(Ht.raw,It.Fu),this.hasReportedPlayFailed=!1)}triggerPlayerHealthCheckFailedCallback(e,t){(0,Ct.lo)("REA:".concat(e)),this.playFailedTimeout||(this.playFailedTimeout=setTimeout((()=>{(0,Ct.py)("Error when triggerPlayerHealthCheck-".concat(e," : "),t),this._audioMode&It.qR&&(this.notifyUIMessage(Ht.raw,It.K_),this.hasReportedPlayFailed=!0,this.playFailedTimeout=null)}),1e3))}triggerPlayerHealthCheck(e){this._isMutedBySystem||this._audioMode&&this._healthChecker._audioTagCountAndStatusMonitor(this._wmscPC,this._mid2RemoteRTCAudioPlayer,!1,this.triggerPlayerHealthCheckSuccessCallback.bind(this,e),this.triggerPlayerHealthCheckFailedCallback.bind(this,e))}_handleAudioPlayerError(e){if(!this._audioMode||!e)return;const t=(this._audioPlayerErrorCounter.get(e)||0)+1;if(this._audioPlayerErrorCounter.set(e,t),this._isAudioPlayerError=!0,(0,Ct.py)("MEDIA_ELEMENT_ERROR: ".concat(e,"-").concat(t)),e==It.Rs.MEDIA_ERR_DECODE&&t<=3){const e=Array.from(this._mid2RemoteRTCAudioPlayer.values());e.forEach((e=>{e.pause(),e.setSrcObject(null)})),e.forEach((e=>{e.setSrcObject(e.mediaStream)})),this.triggerPlayerHealthCheck(It.vr.AUDIO_ERROR)}else(0,Xt.iK)(Ht.BJf)}_checkNeedPlayAllPlayerLater(e){this.triggerPlayerHealthCheck(e)}async join(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:It.DY;if(i===It.qR)try{var s,a,n;this._cleanUserEventFn||(this._cleanUserEventFn=(0,bt.zV)((()=>{this.triggerPlayerHealthCheck(It.vr.USER_CLICK)}))),null===(s=this._webRTCWorkletManager)||void 0===s||s.createWebRTCWorklet(),null===(a=this._webRTCWorkletManager)||void 0===a||a.changeAudioStatus(!1,!1),null===(n=this._webRTCWorkletManager)||void 0===n||n.startCheckProcess()}catch(e){(0,Ct.py)("Error when creating webRTCWorklet",e)}this._audioMode=this._audioMode|i,i!=It.DY&&(this.notifyRWGSSRC(this.normal_ssrc,this.share_ssrc),this._startAVSyncTimer(),this._wmscAudioMonitor.startMonitor(this._wmscPC)),i===It.qR&&this.unmuteAllRemoteAudio()}async onPCCreated(e){(0,Ct.U1)("onPCCreated oldWMSCPC=",this._wmscPC,"wmscPc=",e),this._audioMode&&this._startAVSyncTimer(),this._wmscPC&&(this._wmscAudioMonitor.resetWMSCPC(this._wmscPC,e),this._wmscPC=null,(0,Ct.U1)("onPCCreated cleared old one")),this._wmscPC=e,this._preserveMlineOnPCCreated(e),this._updateQosAudioBandwidth()}setUserId(e){this.nodeId=this._convertUserId2NodeId(e),this._wmscAudioMonitor.setUserId(e)}addRecvTransceiver(e,t,i,s,a){return(0,Ct.U1)("addRecvTransceiver , ".concat(e,", nodeId=").concat(t,", webrtcSSRC=").concat(i,", msid=").concat(s,", isCurrentSession=").concat(a)),this._wmscPC.createRecvTransceiver(e)}saveRecvMLineTemp(){var e;const t=null===(e=this._wmscPC)||void 0===e?void 0:e.answer.media.find((e=>{if(!e)return!1;const{type:t,direction:i}=e;return"audio"===t&&"sendonly"===i}));this._recvMLineTemp=ei({},t)}updateRecvMLineTemp(e){const{ice_pwd:t,ice_ufrag:i}=e;this._recvMLineTemp&&(this._recvMLineTemp.icePwd=t,this._recvMLineTemp.iceUfrag=i)}addRecvAudioSDP(e){const{transceiver:t,msid:i,mediaType:s,ssrcs:a={},user_id:n}=e,{rtp:o}=a,{mid:r}=t,c=o||he.generateSsrc(),d=i||he.generateUuid(),h=he.generateUuid(),l=ei({},this._recvMLineTemp);return l.mid=r,l.msid={streamId:d,trackId:h},l.ssrcs=[{ssrc:c,attribute:"cname:".concat(d)},{ssrc:c,attribute:"msid:".concat(d," ").concat(h)}],this._wmscPC.addMLineSDPToAnswer(r,l),(0,Ct.U1)("addRecvAudioSDP mid=",r,"mLine=",l),{mid:r,media_type:s,msid:d,ssrcs:{rtp:c},user_id:n}}onRemoteStream(e,t,i,s){const a=this._convertUserId2NodeId(s);(0,Ct.U1)("onRemoteStream, mid=".concat(i,", mediaStream.id=").concat(e.id,", nodeId=").concat(null!=a?a:"",", _mid2RemoteRTCAudioPlayer="),this._mid2RemoteRTCAudioPlayer),t.onunmute=t=>this._onDownlinkTrackUnmute(e,i,a)}handleLocalOffer(e){(0,Ct.U1)("handleLocalOffer , parsedOffer=".concat(e)),this.normal_ssrc=he.getSSRCByMid(e,this._wmscMainAudioTransceiver.mid),this.share_ssrc=he.getSSRCByMid(e,this._wmscShareAudioTransceiver.mid),(0,Ct.U1)("handleLocalOffer , normal_ssrc=".concat(this.normal_ssrc,", share_ssrc=").concat(this.share_ssrc)),this.notifyRWGSSRC(this.normal_ssrc,this.share_ssrc)}notifyRWGSSRC(e,t){e&&t&&Gt.A.sendMessageToRwg(Ht.yJV,{evt:gt,body:{normal_ssrc:e,share_ssrc:t}})}getUpdatedMlineFtmpFromLocalOffer(){var e;const t=he.getMlineCodecFromLocalOffer(this._wmscPC.getOffer(),this._wmscMainAudioTransceiver.mid,"opus");let i="";t.codecParams.forEach(((e,t)=>{null!=e&&(i+="".concat(t,"=").concat(e,";"))}));const s=null===(e=this._wmscPC.getOffer())||void 0===e||null===(e=e.media)||void 0===e||null===(e=e.find((e=>e.mid===this._wmscMainAudioTransceiver.mid)))||void 0===e||null===(e=e.msid)||void 0===e?void 0:e.streamId;return{media_type:Ye.zu.MainAudio,mid:this._wmscMainAudioTransceiver.mid,msid:s||"-",codec:[{rtp_payload_type:t.payloadType,fmtp:i}]}}mungeLocalOffer(e){this._updateCodec(e)}mungeAnswer(e){this._updateCodec(e,!1)}onRWGCMDQos(e){var t,i;const s=this._wmscAudioMonitor.getBitrateInfo(),a=ei(ei({},e.uplink),{},{sample_rate:48,rate:null===(t=s.publisher)||void 0===t?void 0:t.bitrate,encoding:!0}),n=ei(ei({},e.downlink),{},{sample_rate:48,rate:null===(i=s.subscriber)||void 0===i?void 0:i.bitrate,encoding:!1});this._audioMode!=It.DY&&(this._wmscAudioMonitor.setAudioStatisticsFromRWG(a),this._wmscAudioMonitor.setAudioStatisticsFromRWG(n)),this._showUplinkQosOnDashboard&&this.notifyUIMessage(Ht.iQY,a),this._showDownlinkQosOnDashboard&&this.notifyUIMessage(Ht.iQY,n)}onRWGCMDRtcpSR(e){let{ntptime:t,rtptime:i,ssrc:s,abssrc:a}=e;512&s?this._shareNodeId2NTPDescriptionMap.set(this._convertUserId2NodeId(s),{ntptime:t,rtptime:i,abssrc:a,ssrc:s}):this._nodeId2NTPDescriptionMap.set(this._convertUserId2NodeId(s),{ntptime:t,rtptime:i,abssrc:a,ssrc:s})}onMlineAssignedNodeId(e,t,i,s,a){var n,o,r;if(!i)return(0,Ct.py)("onMlineAssignedNodeId nodeId error, ".concat(e,", mid=").concat(t,", nodeId=").concat(i,", webrtcSSRC=").concat(s,", isCurrentSession=").concat(a));let c;e==Ye.zu.MainAudio&&(c=null===(n=this._nodeId2VolumeMap.get(i))||void 0===n?void 0:n.speechVolume);let d="onMlineAssignedNodeId , ".concat(e,", mid=").concat(t,", nodeId=").concat(i,", webrtcSSRC=").concat(s,", isCurrentSession=").concat(a,", volume=").concat(null!==(o=c)&&void 0!==o?o:100);if((0,Ct.U1)(d),(0,Ct.PV)(d),(0,Ct.lo)("REVT:".concat(t,"-").concat(i,"-").concat(s,"-").concat(a?1:0,"-").concat(null!==(r=c)&&void 0!==r?r:100)),this._mid2RemoteRTCAudioPlayer.has(t)){let n=this._mid2RemoteRTCAudioPlayer.get(t);n.onAssignedNodeId(e,i,a,s),this._healthChecker.addRemoteAudio(s),void 0!==c&&n.setVolume(c),this._stopIncomingAudioFlag&&n.mute(),this._checkNeedPlayAllPlayerLater(It.vr.ASSIGNED_NODE_ID)}else d+=" cannot find RTCAudioPlayer at present",(0,Ct.PV)(d);e==Ye.zu.ShareAudio&&(this._nodeId2VolumeMap.forEach(((e,t)=>{void 0!==e.shareVolume&&this.setShareVolumeLevel(t>>10,e.shareVolume,!1,!1)})),this._mainSessionNodeId2VolumeMap.forEach(((e,t)=>{void 0!==e.shareVolume&&this.setShareVolumeLevel(t>>10,e.shareVolume,!0,!1)}))),this.updateUserLang(i,this._userLangMap[i>>10]),this.interpretation_set_list(this._interpretationList),this.interpretation_set_lang(this._interpretationCurrentLang)}onMlineRemoved(e){if((0,Ct.U1)("onMlineRemoved mid=".concat(e)),!this._mid2RemoteRTCAudioPlayer.has(e))return;(0,Ct.lo)("REVTM:".concat(e));const t=this._mid2RemoteRTCAudioPlayer.get(e);this._healthChecker.removeRemoteAudio(null==t?void 0:t.getWebrtcSSRC()),t&&t.destroy(),this._mid2RemoteRTCAudioPlayer.delete(e),(0,Ct.U1)("onMlineRemoved mid=".concat(e," done"))}_onBadNetworkDetected(e){let{isUplink:t,networkLevel:i,bwLevel:s}=e;this._audioMode==It.qR&&this._audioStream&&Gt.A.Notify_APPUI_SAFE(Ht.Joy,{isUplink:t,networkLevel:i,bwLevel:s})}_onRequestReportMonitorLog(e){Gt.A.sendMessageToRwg(Ht.yGo,{evt:Ht.UFw,seq:1,body:{data:e}})}_onDownlinkTrackUnmute(e,t,i){var s;let a;if(i||(i=this._convertUserId2NodeId(this._mIdMgr.getUserIdByMid(t))),this._mid2RemoteRTCAudioPlayer.has(t))a=this._mid2RemoteRTCAudioPlayer.get(t);else{var n;let s,o;i&&(s=this._mIdMgr.isMlineCurrentSessionByMid(t),o=this._mIdMgr.getMediaTypeByMid(t),(0,Ct.U1)("_onDownlinkTrackUnmute, nodeId known, ".concat(o," mid=").concat(t,", nodeId=").concat(i,", isCurrentSession=").concat(s))),a=new Jt.A({mediaStream:e,speakerId:Yt.A.pendingSpeakerId||Yt.A.speakerId,mediaType:null!==(n=o)&&void 0!==n?n:Ye.zu.MainAudio,nodeId:i,mid:t,isCurrentSession:s,streamValid:!1,isReceivingPacketFunc:this.isReceivingPacketByMid.bind(this),errorCallback:e=>{this._handleAudioPlayerError(e)},pauseCallback:()=>{(0,Ct.PV)("RTCAudioPlayer on paused, document visibility=".concat(document.visibilityState)),this._healthChecker._audioTagCountAndStatusMonitor(this._wmscPC,this._mid2RemoteRTCAudioPlayer,!0,this.triggerPlayerHealthCheckSuccessCallback.bind(this,It.vr.PLAYER_ON_PAUSE),this.triggerPlayerHealthCheckFailedCallback.bind(this,It.vr.PLAYER_ON_PAUSE))},streamValidCallback:()=>{this._healthChecker._audioTagCountAndStatusMonitor(this._wmscPC,this._mid2RemoteRTCAudioPlayer,!1,this.triggerPlayerHealthCheckSuccessCallback.bind(this,It.vr.STREAM_VALID),this.triggerPlayerHealthCheckFailedCallback.bind(this,It.vr.STREAM_VALID))}}),this._mid2RemoteRTCAudioPlayer.set(t,a),(0,Ct.U1)("_onDownlinkTrackUnmute, mid=",t,",this._mid2RemoteRTCAudioPlayer=",this._mid2RemoteRTCAudioPlayer)}this._healthChecker._audioTagCountAndStatusMonitor(this._wmscPC,this._mid2RemoteRTCAudioPlayer,!0,this.triggerPlayerHealthCheckSuccessCallback.bind(this,It.vr.NEW_STREAM),this.triggerPlayerHealthCheckFailedCallback.bind(this,It.vr.NEW_STREAM),!0),this._isDestroyed&&a.mute(),(0,Ct.lo)("REVTP:".concat(t,"-").concat(null!==(s=i)&&void 0!==s?s:""))}_wmscSignalSend(e){return!!this._WMSCsignalSendSink&&this._WMSCsignalSendSink(e)}notifyUIMessage(e,t){var i;null===(i=Gt.A.Notify_APPUI)||void 0===i||i.call(Gt.A,e,t)}async enableShareToBO(e){return this.notifyUIMessage(Ht.CcD,{enable:e})}async enableBroadCastToBO(e){return this.notifyUIMessage(Ht.g9q,{enable:e})}leaveAudioWithoutDisconnect(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:It.DY;var t,i;this._audioMode=this._audioMode&~e,e===It.qR?(this.playFailedTimeout&&(clearTimeout(this.playFailedTimeout),this.playFailedTimeout=null),this.hasReportedPlayFailed=!1,this.setNormalAudioStream(null),this._stopIncomingAudioFlag=!1,this.muteAllRemoteAudio(),this._cleanUserEventFn&&(this._cleanUserEventFn(),this._cleanUserEventFn=null),this._isMuted=!1,null===(t=this._webRTCWorkletManager)||void 0===t||t.changeAudioStatus(!1,!0),null===(i=this._webRTCWorkletManager)||void 0===i||i.stopCheckProcess(),this._wmscAudioMonitor.sendAudioMos(!0)):e===It.$t&&this.setShareAudioStream(null),this._audioMode===It.DY&&(this._wmscAudioMonitor.stopMonitor(this._wmscPC),this._stopAVSyncTimer())}_preserveMlineOnPCCreated(e){this._wmscMainAudioTransceiver=e.createSendTransceiver(Ye.zu.MainAudio),this._wmscShareAudioTransceiver=e.createSendTransceiver(Ye.zu.ShareAudio),e.createRecvTransceiver(Ye.zu.MainAudio),e.createRecvTransceiver(Ye.zu.MainAudio),e.createRecvTransceiver(Ye.zu.MainAudio)}_getAudioCodecParams(e){return It.gC[e]}_updateCodec(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],i=this._wmscMainAudioTransceiver.mid,s=this._wmscShareAudioTransceiver.mid;const a=t?"sendonly":"recvonly",n=e.media.filter((e=>"audio"===e.type&&e.direction===a));if(!i){const e=n.reduce(((e,t)=>parseInt(t.mid)<parseInt(e.mid)?t:e));i=e.mid}s||(s=n.filter((e=>e.mid!==i)).reduce(((e,t)=>parseInt(t.mid)<parseInt(e.mid)?t:e)).mid),he.updateCodecParametersByMid(e,i,"opus",this._getAudioCodecParams(this._audioProfile)),he.updateCodecParametersByMid(e,s,"opus",this._getAudioCodecParams(It.x_)),(0,de.GN)()||he.updateCodecParameters(e,"audio",t?"recvonly":"sendonly","opus",this._getAudioCodecParams(It.fo)),t&&(he.updateStreamIdByMid(e,i,this._wmscPC.mainEgressStreamId),he.updateStreamIdByMid(e,s,this._wmscPC.shareEgressStreamId))}setRecvOnly(e,t){this._isRecvOnly=!!e,this._isRecvOnly?this.setNormalAudioStream(null):t&&this.setNormalAudioStream(t)}setCodecDoAVSync(e){this._codecDoAVSync=e}getFinalSentAudioStream(){return this._webRTCWorkletManager&&this._webRTCWorkletManager.doingDenoise&&this._webRTCWorkletManager.getAudioStream()||this._audioStream}async setNormalAudioStream(e){arguments.length>1&&void 0!==arguments[1]&&arguments[1]||(this._isRecvOnly?this._audioStream=null:this._audioStream=e),this.resetAudioTrackState(this._audioStream),this.setAudioStreamCloning(this._audioStream),this._webRTCWorkletManager&&(this._webRTCWorkletManager.doingDenoise?this._webRTCWorkletManager.setAudioStream(this._audioStream):this._webRTCWorkletManager.setAudioStream(this._audioStreamCloning||this._audioStream));let t=e;t=this.getFinalSentAudioStream(),t&&(this._isMuted?this.mute():this.unmute()),await this.publishAudioStream(t,this._wmscMainAudioTransceiver,"PAT")}async setShareAudioStream(e){this._shareAudioStream=e,await this.publishAudioStream(this._shareAudioStream,this._wmscShareAudioTransceiver,"PAST")}async publishAudioStream(e,t,i){if(!this._isDestroyed){if(t)if(e){let s=[];e.getAudioTracks().forEach((e=>{(0,Ct.PV)("publish track label: "+e.label),(0,Ct.lo)("".concat(i,"-").concat(e.id)),s.push(t.publishTrack(e).catch((t=>{(0,Ct.lo)("".concat(i,"-Failed-").concat(e.id)),(0,Ct.py)("error publishing audio stream",t)})))})),await Promise.all(s)}else await t.publishTrack(null),(0,Ct.lo)("".concat(i,"-null"));else(0,Ct.lo)(i+"SE ");this._updateQosAudioBandwidth()}}mute(){this._isMuted=!0;let e=this.getFinalSentAudioStream();var t;e&&((0,Ct.lo)("SEVTP"),e.getAudioTracks().forEach((e=>{e.enabled=!1})),null===(t=this._webRTCWorkletManager)||void 0===t||t.changeAudioStatus(!0,!1))}unmute(){this._isMuted=!1;let e=this.getFinalSentAudioStream();var t;e&&((0,Ct.lo)("SEVTM"),e.getAudioTracks().forEach((e=>{e.enabled=!0})),null===(t=this._webRTCWorkletManager)||void 0===t||t.changeAudioStatus(!1,!1))}stopIncomingAudio(e){this._stopIncomingAudioFlag=!!e,e?this.muteAllRemoteAudio():this.unmuteAllRemoteAudio()}muteAllRemoteAudio(){for(const[e,t]of this._mid2RemoteRTCAudioPlayer)t.mute()}unmuteAllRemoteAudio(){for(const[e,t]of this._mid2RemoteRTCAudioPlayer)t.unmute();this.triggerPlayerHealthCheck(It.vr.UNMUTE_ALL)}setAudioStreamCloning(e){this.destroyAudioStream(this._audioStreamCloning),this._audioStreamCloning=null;try{if(!e)return;if(this._webRTCWorkletManager&&!this._webRTCWorkletManager.doingDenoise&&Gt.A.enableCloneAudioStream){this._audioStreamCloning=e.clone();let t=this._audioStreamCloning.getAudioTracks()[0];t&&((0,Ct.lo)("CATRS:"+t.readyState+":"+t.id),(0,Ct.lo)("CATMS:"+t.muted+":"+t.id),(0,Ct.lo)("CATES:"+t.enabled+":"+t.id))}}catch(e){(0,Ct.py)("Error when cloning audio stream, ",e)}}destroyAudioStream(e){e&&e.getTracks().forEach((e=>{e.stop()}))}setSpeechVolumeLevel(e,t){const i=this._convertUserId2NodeId(e);(0,Ct.U1)("setSpeechVolumeLevel nodeId=".concat(i,", volume=").concat(t));let s=this._nodeId2VolumeMap.get(i)||{};s.speechVolume=t,this._nodeId2VolumeMap.set(i,s);for(const[e,s]of this._mid2RemoteRTCAudioPlayer)if(this._mIdMgr.isMlineCurrentSessionByMid(e)&&s.getMediaType()==Ye.zu.MainAudio&&s.getNodeId()==i){s.setVolume(t),(0,Ct.PV)("set speech volume level, nodeId=".concat(i,", volume=").concat(t));break}}async changeSpeaker(e){let t,i=!0,s="",a=Xt.Lg.BROWSER_ERROR,n=Date.now(),o=[];Yt.A.setPendingSpeakerId(e);for(const[t,n]of this._mid2RemoteRTCAudioPlayer){if(!1===n.isSupportSetSpeakerDevice()){i=!1,a=Xt.Lg.UNSUPPORTED_BROWSER,s="audioplayer.setSinkId is not supported on your device.",Yt.A.clearPendingSpeakerId();break}let t=n.setSpeakerDevicePromise(e);o.push(t)}try{await Promise.all(o)}catch(e){i=!1,t=e,s="Error when setting sink of audio player: "+e.message}if(i)this._audioSpeakerSetErrorCnt=0,this.notifyUIMessage(Ht.a6z,e||"default");else{this._audioSpeakerSetErrorCnt++;let e=Yt.A.getSpeakerId();(0,Ct.py)("setSinkId failed ".concat(this._audioSpeakerSetErrorCnt," times, current speaker ").concat(e,", errorMessgae = ").concat(s)),this._audioSpeakerSetErrorCnt<=3&&this.notifyUIMessage(Ht.dsK,{errorMessgae:s,currentSink:e,error:t,errorCode:a})}await Yt.A.updateSelectedSpeakerDevices(e,Date.now()-n,i),Yt.A.clearPendingSpeakerId()}setShareVolumeLevel(e,t,i){let s=!(arguments.length>3&&void 0!==arguments[3])||arguments[3],a=e<<10,n=this._convertUserId2NodeId(a);if((0,Ct.U1)("setShareVolumeLevel, nodeId=".concat(n,", volume=").concat(t,", isFromMainSession=").concat(i)),n){if(s)if(i){let e=this._mainSessionNodeId2VolumeMap.get(n)||{};e.shareVolume=t,this._mainSessionNodeId2VolumeMap.set(n,e)}else{let e=this._nodeId2VolumeMap.get(n)||{};e.shareVolume=t,this._nodeId2VolumeMap.set(n,e)}for(const[e,s]of this._mid2RemoteRTCAudioPlayer)s.getNodeId()==n&&this._mIdMgr.isMlineCurrentSessionByMid(e)!=i&&s.getMediaType()==Ye.zu.ShareAudio&&(t?s.unmute():s.mute(),(0,Ct.PV)("setShareVolumeLevel, nodeId=".concat(n,", volume=").concat(t?1:0,", isFromMainSession=").concat(i)))}}set_CC_lang(e){this.nodeId?((0,Ct.PV)("set_CC_lang, lang=".concat(e)),Gt.A.sendMessageToRwg(Ht.yJV,{evt:Ht.pWm,body:{type:Ht.hEQ.SELECT_TRANSLATION_LANGUAGE,lang:e,nodeid:this.nodeId}}),this.notifyUIMessage(Ht.V5N,e)):(0,Ct.py)("Invalid parameters for setting CC lang: nodeId=".concat(this.nodeId))}updateUserMuteUnmuteStatus(e){const{update:t,remove:i}=e;t&&t.length>0&&t.forEach((e=>{const{userId:t,muted:i}=e;if(t){let e=this._nodeId2VolumeMap.get(this._convertUserId2NodeId(t))||{};e.muted=!!i,this._nodeId2VolumeMap.set(this._convertUserId2NodeId(t),e)}})),i&&i.length>0&&i.forEach((e=>{const{userId:t}=e;if(t){let e=this._nodeId2VolumeMap.get(this._convertUserId2NodeId(t))||{};e.muted=!0,this._nodeId2VolumeMap.set(this._convertUserId2NodeId(t),e)}}))}isUserMuted(e,t){var i;if(this._mIdMgr.getMediaTypeBySsrc(t)!==Ye.zu.MainAudio)return!1;const s=null===(i=this._nodeId2VolumeMap.get(this._convertUserId2NodeId(e)))||void 0===i?void 0:i.muted;return void 0!==s&&!!s}async setAudioProfile(e){if(this._audioMode!==It.qR&&this._audioMode!=It.$2)return;let t=this._audioProfile;"backgroundNoiseSuppression"===e.currentSelect?(e.highBitrate?this._audioProfile=It.$A:this._audioProfile=It.yu,Yt.A.changeDenoiseSwitch("Zoom"===e.backgroundNoiseSuppression)):(Yt.A.changeDenoiseSwitch(!1),e.originalSound.highfidelity&&e.originalSound.stereo?this._audioProfile=It.IA:e.originalSound.highfidelity?this._audioProfile=It.hc:e.originalSound.stereo?this._audioProfile=It.Hc:this._audioProfile=It.ej),t!==this._audioProfile&&(this._messageCallback("requestSelfRenegotiation",Ye.zu.MainAudio),Gt.A.sendMessageToRwg(Ht.yJV,{evt:pt,body:{audioProfile:this._audioProfile}}))}resetAudioTrackState(e){e&&e.getAudioTracks().forEach((e=>{e.enabled=!0}))}getAudioBandwidth(){let e=0;return this._wmscMainAudioTransceiver&&(e+=It.gC[this._audioProfile].get("maxaveragebitrate")+28800),this._wmscShareAudioTransceiver&&(e+=It.gC[It.x_].get("maxaveragebitrate")+28800),e}_updateQosAudioBandwidth(){qe.setAudioBandwidth(this.getAudioBandwidth())}clearAllRemoteAudioPlayer(){this.muteAllRemoteAudio();for(const[e,t]of this._mid2RemoteRTCAudioPlayer)t.destroy();this._mid2RemoteRTCAudioPlayer.clear()}getRemoteAudioPlayerByMid(e){return this._mid2RemoteRTCAudioPlayer.get(e)}destroy(){(0,Ct.lo)("DS"),this._isDestroyed=!0,this._cleanUserEventFn&&(this._cleanUserEventFn(),this._cleanUserEventFn=null),this._wmscAudioMonitor.destroy(this._wmscPC),this._stopAVSyncTimer(),this._webRTCWorkletManager&&(this._webRTCWorkletManager.destroy(),this._webRTCWorkletManager=null),this.setNormalAudioStream(null),this.setShareAudioStream(null),this.clearAllRemoteAudioPlayer(),this._isRecvOnly=!1}async setStreamAsync(e){arguments.length>1&&void 0!==arguments[1]&&arguments[1]?await this.setShareAudioStream(e):await this.setNormalAudioStream(e)}_stopAVSyncTimer(){this._AVsyncTimer&&(clearInterval(this._AVsyncTimer),this._AVsyncTimer=null)}syncMultiView(e,t){let i=new ArrayBuffer(16),s=t.toString(2),a=parseInt(s.substring(0,s.length-32),2),n=parseInt(s.substring(s.length-32,s.length),2),o=new DataView(i);o.setUint32(0,e,!0),o.setUint32(4,n,!0),o.setUint32(8,a,!0),o.setUint32(12,Date.now(),!0);let r=new Uint8Array(i);(0,Qt.Notify_Video_Decode_Thread)({command:"audioDecodeTime",status:1,data:r})}syncSingleView(e,t){let i=0;if(t){let e=parseInt(t).toString(2),s=e.substring(0,e.length-32),a=e.substring(e.length-32,e.length);s=parseInt(s,2),a=parseInt(a,2),i=1e3*s+232.8*a/1e9}0==Gt.A.mediaSDKHandle.RenderInMain?e?(0,Qt.Notify_Sharing_Decode_Thread)({command:"audioTimestamp",data:i}):(0,Qt.Notify_Video_Decode_Thread)({command:"audioDecodeTime",status:0,data:i}):e?Gt.A.mediaSDKHandle.SharingRenderObj&&Gt.A.mediaSDKHandle.SharingRenderObj.SetcATimeStamp(i):Gt.A.CurrentSSRCTime!=i&&(Gt.A.CurrentSSRCTime=i,Gt.A.audioPlayTime=Date.now())}_startAVSyncTimer(){this._stopAVSyncTimer(),this._AVsyncTimer=setInterval((()=>{if(!this._wmscPC)return;let e=0;Array.from(this._mid2RemoteRTCAudioPlayer.keys()).forEach((t=>{this._wmscPC.getRecvTransceiverByMid(t).receiver.getSynchronizationSources().forEach((t=>{if(e++,this.isUserMuted(this.getZoomSSRCByWebRTCSSRC(t.source),t.source))return;let i=this.getNodeIdByWebRTCSSRC(t.source);if(!i)return;let s=null;const a=this._mIdMgr.getMediaTypeBySsrc(t.source);if(a==Ye.zu.MainAudio?s=this._nodeId2NTPDescriptionMap.get(i):a==Ye.zu.ShareAudio&&(s=this._shareNodeId2NTPDescriptionMap.get(i)),s){let e=s.ntptime,n=s.rtptime,o=Gt.A.timeOrigin+performance.now(),r=(o-t.timestamp)/1e3;Math.abs(r)>60&&(this._getSynchronizationSourcesTimestampInvalidDetected||(0,Ct.py)("[WMSC Audio] data.timestamp diff too large: ".concat(r,", now:").concat(o,", data.ts:").concat(t.timestamp)),r=0,this._getSynchronizationSourcesTimestampInvalidDetected=!0);let c=t.rtpTimestamp-n&4294967295,d=e+r*Math.pow(2,32)+c*Math.pow(2,32)/48e3;this._codecDoAVSync?this.syncMultiView(s.ssrc,d):i>>10!=Gt.A.CurrentSSRC>>10&&a!=Ye.zu.ShareAudio||t.source===s.abssrc&&this.syncSingleView(a==Ye.zu.ShareAudio,d)}}))})),0===e&&(this.syncSingleView(!1,0),this.syncSingleView(!0,0))}),500)}getLevelR16Log(){return this._webRTCWorkletManager&&this._webRTCWorkletManager.getLevelR16Log()}getHealthCheckFailedAndReset(){return!!this._healthChecker.isPacketSentBytesZero&&(this._healthChecker.resetPacketSentCheck(),!0)}_onAudioEnergySentCheckResult(e,t,i,s){let a="HEALTH_CHECK_FAILED:".concat(Ye.zu.MainAudio,"-energy-").concat(t,"-").concat(i,"-").concat(s);e?(a="HEALTH_CHECK_RECOVERED:".concat(Ye.zu.MainAudio,"-energy-").concat(t,"-").concat(i,"-").concat(s),(0,Ct.lo)(a),(0,Ct.py)(a)):s<=3?(bt.Ay.isAndroidBrowser()||bt.Ay.isIphoneOrIpadBrowser()||0==t)&&((0,Ct.lo)("RE-CAPTURE:AUDIO_HEALTH_CHECK_FAILED"),(0,Ct.py)("RE-CAPTURE:AUDIO_HEALTH_CHECK_FAILED"),this._doRecapture()):4==s?(0,Ct.PV)(a):s%6==0&&((0,Ct.lo)(a),(0,Ct.py)(a))}_doRecapture(){this._messageCallback("recapture",Ye.zu.MainAudio),this._healthChecker.resetPacketSentCheck()}isReceivingPacketByMid(e){let t=!1;return this._wmscPC.getRecvTransceiverByMid(e).receiver.getSynchronizationSources().forEach((e=>{e.rtpTimestamp&&(t=!0)})),t}_onPacketSentCheckResult(e){e?((0,Ct.lo)("HEALTH_CHECK_RESTORED:PACKETS_SENT_ZERO"),Gt.A.Notify_APPUI_SAFE(Ht.FjO)):((0,Ct.lo)("HEALTH_CHECK_FAILED:PACKETS_SENT_ZERO"),(0,Xt.iK)(Ht.$qV,It.Mm))}_onAudioEnergyReceivedCheckResult(e){e?(this._isAudioPlayerError=!1,(0,Ct._$)("HEALTH_CHECK_RESTORED:RECEIVE_AUDIO_ENERGY_ZERO"),(0,Ct.lo)("HEALTH_CHECK_RESTORED:RECEIVE_AUDIO_ENERGY_ZERO")):(this._isAudioPlayerError=!1,(0,Ct._$)("HEALTH_CHECK_FAILED:RECEIVE_AUDIO_ENERGY_ZERO"),(0,Ct.lo)("HEALTH_CHECK_FAILED:RECEIVE_AUDIO_ENERGY_ZERO"))}_convertUserId2NodeId(e){return e?parseInt(e)>>10<<10:null}changeDenoiseSwitch(e,t,i){var s;null===(s=this._webRTCWorkletManager)||void 0===s||s.changeDenoiseSwitch(e,t,i)}updateQos(e){this._wmscAudioMonitor.setEnableBitrateReport(e.enable),e.workerType===Kt._c.AUDIO_ENCODE&&(this._showUplinkQosOnDashboard=!!e.enable),e.workerType===Kt._c.AUDIO_DECODE&&(this._showDownlinkQosOnDashboard=!!e.enable)}getNodeIdByWebRTCSSRC(e){return this._convertUserId2NodeId(this._mIdMgr.getUserIdBySsrc(e))}getZoomSSRCByWebRTCSSRC(e){const t=this._mIdMgr.getMediaTypeBySsrc(e);let i=this._mIdMgr.getUserIdBySsrc(e);return t===Ye.zu.ShareAudio&&(i|=512),i}getAudioStream(){return this.getFinalSentAudioStream()}getAudioMode(){return this._audioMode}interpretation_set_mute(e){this._interpretationMuted=!!e,this._interpretationChangeSpeakerVolume()}interpretation_set_enable(e){this._interpretationEnable=!!e,this._mid2RemoteRTCAudioPlayer.forEach((e=>{e.initInterpretationParams()})),this._wmscPC.off(Ye.f7.StatsReport,this._inboundSourceVADBind),this._interpretationEnable&&this._wmscPC.on(Ye.f7.StatsReport,this._inboundSourceVADBind)}interpretation_set_lang(e){this._interpretationCurrentLang=e,this._mid2RemoteRTCAudioPlayer.forEach((e=>{e.clearInterpreterSpeakingCount(),this._interpreterSpeakingStatus=It.g3})),this._interpretationChangeSpeakerVolume()}interpretation_set_list(e){this._interpretationList=e,this._mid2RemoteRTCAudioPlayer.forEach((t=>{e.includes(t.getNodeId()>>10)?t.setInterpreter(!0):t.setInterpreter(!1)})),this._interpretationChangeSpeakerVolume()}updateUserLang(e,t){this._userLangMap[e>>10]=t,this._mid2RemoteRTCAudioPlayer.forEach((i=>{i.getNodeId()>>10==e>>10&&i.setLang(t)})),this._interpretationChangeSpeakerVolume()}inboundSourceVAD(e){if(!this._interpretationEnable)return!1;e.forEach((e=>{if("inbound-rtp"===e.type&&"audio"===e.kind){const{totalAudioEnergy:t,totalSamplesDuration:i,audioLevel:s,mid:a}=e,n=this._mid2RemoteRTCAudioPlayer.get(a);if(!n||!n.isInterpreter())return;if(void 0===t||void 0===i)return;const{totalAudioEnergy:o,totalSamplesDuration:r}=n.getVADStatistics(),c=t-o,d=i-r;if(n.setVADStatistics({totalAudioEnergy:t,totalSamplesDuration:i}),d<=0||!o||!r)return;const h=c/d>.001&&(void 0===s?1:s)>.01;this._changeCurrentLangInterpreterSpeakingStatus(a,h)}}));const t=[...this._mid2RemoteRTCAudioPlayer.values()].reduce(((e,t)=>t.isInterpreter()?Math.max(e,t.isInterpreterSpeaking()):e),It.g3);t!=this._interpreterSpeakingStatus&&((0,Ct.lo)("interpreterSpeakingStatus: ".concat(t)),this._interpreterSpeakingStatus=t,this._interpretationChangeSpeakerVolume())}_interpretationChangeSpeakerVolume(){this._mid2RemoteRTCAudioPlayer.forEach((e=>{e.isInterpreter()?e.getLang()===this._interpretationCurrentLang?e.changeVolumeByInterpreter(100):e.changeVolumeByInterpreter(0):e.getLang()===this._interpretationCurrentLang?this._interpreterSpeakingStatus===It.sr?e.changeVolumeByInterpreter(30):e.changeVolumeByInterpreter(100):this._interpretationMuted?e.changeVolumeByInterpreter(0):this._interpreterSpeakingStatus===It.sr?e.changeVolumeByInterpreter(10):e.changeVolumeByInterpreter(100)}))}_changeCurrentLangInterpreterSpeakingStatus(e,t){const i=this._mid2RemoteRTCAudioPlayer.get(e);if(!i)return!1;null!=i&&i.isInterpreter()&&(null==i?void 0:i.getLang())===this._interpretationCurrentLang&&(t?i.increaseInterpreterSpeakingCount():i.decreaseInterpreterSpeakingCount())}}class ii{constructor(e,t){this.pc=e,this.midMgr=t,this.audioSsrcToSR=new Map,this.videoSsrcToSR=new Map}setAudioSR(e){const{ntptime:t,rtptime:i,abssrc:s}=e,a=BigInt(t),n=Number(a>>BigInt(32)),o=Number(a&BigInt(4294967295));this.audioSsrcToSR.set(s,{rtpTimestamp:i,ntpTimestamp:n+o/Math.pow(2,32),createdTime:performance.now()})}setVideoSR(e){e.forEach((e=>{let{ssrc:t,ntptime:i,rtptime:s}=e;const a=BigInt(i),n=Number(a>>BigInt(32)),o=Number(a&BigInt(4294967295));this.videoSsrcToSR.set(t,{rtpTimestamp:s,ntpTimestamp:n+o/Math.pow(2,32),createdTime:performance.now()})}))}getAVSyncDiff(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:9e4,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:48e3;var s,a;const n=this.midMgr.getAudioMidByUserId(e),o=this.midMgr.getVideoMidByUserId(e);if(n&&o){const e=null===(s=this.pc.getRecvTransceiverByMid(n))||void 0===s?void 0:s.receiver,r=null===(a=this.pc.getRecvTransceiverByMid(o))||void 0===a?void 0:a.receiver;if(e&&r){const s=r.getSynchronizationSources()[0],a=e.getSynchronizationSources()[0];if(s&&a){const e=this.convertAudioRtpTimeToWallTime(a,i),n=this.convertVideoRtpTimeToWallTime(s,t);if(e&&n)return{audioNtpTimestamp:e,videoNtpTimestamp:n,diff:a.timestamp-e-(s.timestamp-n)}}}}}deleteSRByMid(e){var t;const i=null===(t=this.pc.getRecvTransceiverByMid(e))||void 0===t?void 0:t.receiver;if(i){const{source:e}=i.getSynchronizationSources()[0]||{};e&&(this.audioSsrcToSR.delete(e),this.videoSsrcToSR.delete(e))}}convertAudioRtpTimeToWallTime(e,t){const{source:i,rtpTimestamp:s}=e,a=this.audioSsrcToSR.get(i);if(a)return this.rtpTimeToWallTime(s,a,t)}convertVideoRtpTimeToWallTime(e,t){const{source:i,rtpTimestamp:s}=e,a=this.videoSsrcToSR.get(i);if(a)return this.rtpTimeToWallTime(s,a,t)}rtpTimeToWallTime(e,t,i){const{rtpTimestamp:s,ntpTimestamp:a,createdTime:n}=t,o=e-s;if(Math.abs(o)>Math.pow(2,24)||performance.now()-n>5e3)return;const r=o/i;return Math.round(1e3*(a+r))}}function si(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,s)}return i}function ai(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?si(Object(i),!0).forEach((function(t){(0,c.A)(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):si(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}const ni=te.getTracer("WmscApiImpl"),oi=e=>{ni.log(e),te.monitorLog("".concat(e))},ri=l,{zk:ci}=s;class di{constructor(e,t){ni.log("created, config: ".concat(JSON.stringify(e))),x.setConfig(e||{}),this.messageCallback=t,this.resetRunTimeParams(),this.negotiationMsgId=0,this.negotiationTimeCost=[],this.pc=null,this.mIdMgr=new yt([]),Ut.mIdMgr=this.mIdMgr,this._isWMSCAudioEnabled()&&this.createWmscAudioMgr(x.nodeId,this.mIdMgr),this.createPeerConnection(),x.nodeId&&(Ut.setUserId(x.nodeId),Ut.start()),this._isWMSCVideoEnabled()&&(this.initVideoConfig(),Ut.isWebRTCVideoEnabled=!0),this.startNegotiation(),this.renegotiationQueue=[],this.numOfTasks=0,this.createdMLine=[],this.removedMids=[],this.updatedMlineFmtp=[],this.lastStreamReqSeq=0,this.lastStreamStatusSeq=0,this.localIceCredential=null,this.ongoingUpdateBitrateTasks=[],this._handlePageVisibilityChange=this._handlePageVisibilityChange.bind(this),this.isOnline=!0,this._handleOnline=this._handleOnline.bind(this),this._handleOffline=this._handleOffline.bind(this),window.addEventListener("online",this._handleOnline),window.addEventListener("offline",this._handleOffline)}_handleOnline(){oi("WMSC_ONLINE-".concat(this.isOnline)),this.isOnline||this.restartIce(),this.isOnline=!0}_handleOffline(){oi("WMSC_OFFLINE"),this.isOnline=!1}destroy(){var e,t;this.sendBye(),this.closeAllPeerConnections(),this.resetRunTimeParams(),null===(e=this._wmscAudioMgr)||void 0===e||e.destroy(),qe.stop(),null==Ut||Ut.stop(),null===(t=this.mIdMgr)||void 0===t||t.destory(),document.removeEventListener("visibilitychange",this._handlePageVisibilityChange),window.removeEventListener("online",this._handleOnline),window.removeEventListener("offline",this._handleOffline)}resetRunTimeParams(){ni.log("reset run time parameters");const{negotiationTimer:e,reconnectTimer:t}=this.pcInfo||{};e&&clearTimeout(e),t&&clearTimeout(t),this.pcInfo={status:u.IDLE,reconnectionCount:0,negotiationTimer:0,reconnectTimer:0,offerMsgId:0,useIceServers:!1,isNegotitating:!1,iceCredentialMsgId:0,iceRestartCount:0,isConnecting:!1},this.camStreams=null,this.bActiveVideo=!1,this.bPrevActiveVideo=!1,this.lastSubList=[],this.sourceVideoSize=-1,this.lastUpdatedSourceVideoSize=-1,this._toSubscribeBuffer=[],this._videoTagMappingBuffer=new Map,this.mIdMgr=null,this.subscriptions=new Map,this.maxSubVideoSize=-1}renewPeerConnection(){this.createPeerConnection(),this._isWMSCVideoEnabled()&&$e.init(this.pc,this.recvMLineNum),this.camStreams&&this._addVideoStreams(this.camStreams),this.startNegotiation()}initVideoConfig(e){oi("WMSC_VCN-".concat($e.recvCodecNum,"-").concat($e.sendCodecNum)),x.setConfig(e||{});const t=x.videoSettings;Mt.setLimits({maxSendVideoSize:t.maxCaptureVideoSize,maxRecvVideoNum:t.maxRecvVideoNum}),this.videoCapabilities=Mt.getCapabilities();const{maxSendVideoSize:i,maxRecvVideoSize:s,maxRecvVideoNum:a}=this.videoCapabilities;oi("WMSC_V_Cap_Updated: ".concat(i,"|").concat(s,"|").concat(a)),this.recvMLineNum=a,this.maxRecvVideoSize=s,$e.registerMessageCallback(this.onMediaMessage.bind(this)),$e.setVideoSettings(t),$e.setMaxSendLayerId(i),Ut.onDecodeError=this._handleDecodeError.bind(this),$e.init(this.pc,this.recvMLineNum),this.camStreams&&this._addVideoStreams(this.camStreams),this._mapBufferedVideoTag(),$e.onMediaRequest(this.lastSubList),qe.registerSendUsageStateUpdateCallback(this.onSendUsageStateUpdate.bind(this)),qe.registerMaxRecvVideoSizeUpdateCallback(this.onMaxRecvVideoSizeUpdate.bind(this)),qe.start(x.qosOptions),this.messageCallback({type:W.VIDEO_CAPABILITIES_CHANGE,data:this.videoCapabilities}),oi("WMSC_SW_PRE: ".concat(Ae("send"),"|").concat(Ae("recv")))}_isWMSCAudioEnabled(){return x.webrtcMode&It.h}_isWMSCVideoEnabled(){return x.webrtcMode&It.Q9}_handleAudioSessionStatus(e,t){switch(e){case"requestSelfRenegotiation":this.requestSelfRenegotiation(t);break;case"recapture":this.messageCallback({type:W.AUDIO_RECAPTURE})}}createWmscAudioMgr(e,t){this._wmscAudioMgr||(oi("INITWMSCAUDIO"),this._wmscAudioMgr=new ti({userId:e,mIdMgr:t,signalSendSink:this._sendMessageToRwg.bind(this),messageCallback:this._handleAudioSessionStatus.bind(this)}))}getWMSCAudioMgr(){return this._wmscAudioMgr}stopReceiveVideo(){oi("WMSC_Stop_Recv_Video"),this.sendBye(),this.closePeerConnection(),this.mIdMgr=null}createPeerConnection(){var e,t;oi("WMSC_Start_Create_PC");let i=null===(e=this.pcInfo)||void 0===e?void 0:e.useIceServers;this.pc=new jt({iceServers:i?x.iceServers:[]}),oi("WMSC_PC_Create_Success"),null===(t=this._wmscAudioMgr)||void 0===t||t.onPCCreated(this.pc),this._wmscAVSyncMgr=new ii(this.pc,this.mIdMgr),Ut.avSyncMgr=this._wmscAVSyncMgr,this.pc.on(Ye.f7.ConnectionStateChange,this._handlePcStateChange.bind(this)),this.pc.on(Ye.f7.Track,this._handleRemoteStream.bind(this)),this.pc.on(Ye.f7.SignalingStateChange,this._handleSignalingStateChange.bind(this)),this.pc.on(Ye.f7.IceConnectionStateChange,this._handleIceConnectionStateChange.bind(this)),this.pc.on(Ye.f7.IceGatheringStateChange,(e=>{oi("WMSC_CANDGA: ".concat(e))})),this.pc.on(Ye.f7.IceCandidateError,(e=>{const{errorCode:t,errorText:i}=e;oi("WMSC_onicecandidateerror: ".concat(t)),te.globalTrace({logLevel:"error",log:"WMSC_onicecandidateerror: ".concat(t,"|").concat(i)})})),this.pc.on(Ye.f7.StatsReport,(e=>{Ve.onStats(e),Ut.onStatsReport(e)}))}async _addVideoStreams(e){var t,i,s;const a=null===(t=e[0])||void 0===t||null===(t=t.stream)||void 0===t?void 0:t.getVideoTracks()[0],n=null===(i=e[0])||void 0===i?void 0:i.constraints,o=null===(s=e[e.length-1])||void 0===s||null===(s=s.stream)||void 0===s?void 0:s.getVideoTracks()[0],r=a&&!a.muted,c=r?J(o.getSettings(),n):null;qe.setVideoSourceLiveState(r),await $e.publishVideoTrack(o,c)}async onVideoStreamsAsync(e){var t;if(this.camStreams=e,null!=e&&e.length){var i,s;const t=null===(i=e[0].stream)||void 0===i?void 0:i.getVideoTracks()[0],a=e[0].constraints,n=null===(s=e[e.length-1].stream)||void 0===s?void 0:s.getVideoTracks()[0];this.sourceVideoSize=Re(a),t.addEventListener("unmute",(()=>{$e.updateVideoSourceSettings(J(n.getSettings(),a)),qe.setVideoSourceLiveState(!0)})),t.addEventListener("mute",(()=>{qe.setVideoSourceLiveState(!1)})),t.addEventListener("ended",(()=>{qe.setVideoSourceLiveState(!1)}))}else this.sourceVideoSize=-1;return this.lastUpdatedSourceVideoSize=-1,Ut.camStream=null===(t=e[0])||void 0===t?void 0:t.stream,await this._addVideoStreams(e),Promise.resolve(!0)}async startNegotiation(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;const i=this.pcInfo;let s;e||(i.status=u.CONNECTING),i.isNegotitating=!0,(!e||null!=t&&t.iceRestart)&&this._detectConnectionTimeout();try{var a,n;if(this.negotiationTimeCost=[performance.now()],s=await this.pc.createOffer(t),this.negotiationTimeCost.push(performance.now()),oi("WMSC_CO"),$e.mungeLocalOffer(s),null===(a=this._wmscAudioMgr)||void 0===a||a.mungeLocalOffer(s),null!=t&&t.iceRestart&&this.pc.updateOfferIceCredential(this.localIceCredential),e||(this.negotiationMsgId++,this.pcInfo.offerMsgId=this.negotiationMsgId),await this.pc.setOffer(),this.negotiationTimeCost.push(performance.now()),oi("WMSC_SLDS"),e)return s;const i=he.cloneSdp(s);he.mungeEgressOfferToRemote(i),null===(n=this._wmscAudioMgr)||void 0===n||n.handleLocalOffer(i);const o=he.writeSdp(i);this._handleSdpOffer(o)}catch(t){let i="";s&&(i=he.writeSdp(s)),q(i,E.GZIP_BASE64).then((i=>{te.globalTrace({logLevel:"error",log:"WMSC_OFSLDF: ".concat(e,"|").concat(t.message,"|").concat(i)})})).catch((()=>{te.globalTrace({logLevel:"error",log:"WMSC_OFSLDF: ".concat(e,"|").concat(t.message,"|").concat(i)})})),oi("WMSC_OFSLDF-".concat(e,"-").concat(t.message)),"closed"!==this.pc.signalingState&&(e?this.messageCallback({type:W.SDP_NEGOTIATION_FAIL}):this.restartNegotiation())}}restartNegotiation(){const e=this.pcInfo;this.sendBye(),this.closePeerConnection(),e.reconnectionCount<S?(e.reconnectionCount++,oi("WMSC_Restart_Nego: ".concat(e.reconnectionCount)),this._isWMSCAudioEnabled()&&this.messageCallback({type:W.ERROR_MESSAGE,data:{type:"PC_RECONNECT",mediaType:"audio"}}),this._isWMSCVideoEnabled()&&this.messageCallback({type:W.ERROR_MESSAGE,data:{type:"PC_RECONNECT",mediaType:"video"}}),this.renewPeerConnection()):this.messageCallback({type:W.SDP_NEGOTIATION_FAIL})}closePeerConnection(){if(this.pc){var e;const t=this.pcInfo;clearTimeout(t.negotiationTimer),t.status=u.IDLE,this.pc.removeAllListeners(),this.pc.close(),$e.handlePcClose(),null===(e=this.mIdMgr)||void 0===e||e.removeAllMIdResource()}}closeAllPeerConnections(){this.closePeerConnection()}onMediaMessage(e){const{type:t,data:i}=e;switch(ni.log("onMediaMessage, type: ".concat(t)),t){case y.ERROR:ni.error("onMediaMessage, error: ".concat(i));break;case y.UPDATE_BITRATE:this._pushToRenegotiationQueue([ai({type:ci.UPDATE_BITRATE},i)]);break;default:ni.error("onMediaMessage, unknown type: ".concat(t))}}onSendUsageStateUpdate(e,t){if(e===C.UNDERUSING){const e=Ce(this.sourceVideoSize);e&&e.formatIndex===t&&this._maybeUpdateVideoSourceConstraints(this.sourceVideoSize+1)}}_maybeUpdateVideoSourceConstraints(e){let{maxCaptureVideoSize:t,hdVideoEnabled:i}=x.videoSettings;if(i||(t=Math.min(2,t)),e<=t&&e!==this.lastUpdatedSourceVideoSize){const t=Ce(e),i={width:t.width,height:t.height,frameRate:t.maxFramerate};return this.messageCallback({type:W.UPDATE_VIDEO_CAPTURE_CONSTRAINTS,data:i}),this.lastUpdatedSourceVideoSize=e,!0}return!1}onMaxRecvVideoSizeUpdate(e){this.maxRecvVideoSize=Math.min(this.videoCapabilities.maxRecvVideoSize,e);const t=[];for(const[i,s]of this.subscriptions){const a=this.mIdMgr.getVideoSizeByUserId(i),n=Math.min(e,s);a!==n&&t.push({id:i,size:n})}t.length&&this._updateSubscriptions(t)}_handleVideoTagMappingBuffer(e,t,i){const s=this._videoTagMappingBuffer.get(e)||[];switch(t){case"add":s.push(i),this._videoTagMappingBuffer.set(e,s);break;case"remove":for(let e=0;e<s.length;)s[e]===i?s.splice(e,1):e++;s.length||this._videoTagMappingBuffer.delete(e);break;default:oi("WMSC_Mapping_Buffer_Action_E: ".concat(e,"|").concat(t))}}onVideoTagMapping(e){const t=parseInt(e.userId),{videodom:i,action:s}=e;if(oi("WMSC_Video_Tag_Mapping: ".concat(t,"|").concat(s,"|").concat(!!this.mIdMgr)),this.mIdMgr)switch(s){case"add":case"buffer":this.mIdMgr.saveVideoTag(t,i),this.messageCallback({type:W.VIDEO_TAG_MAPPED,data:t});break;case"remove":this.mIdMgr.removeVideoTag(t,i);break;default:oi("WMSC_Mapping_Action_E: ".concat(t,"|").concat(s))}else ni.warn("onVideoTagMapping, mIdMgr not ready yet. Will do mapping later."),this._handleVideoTagMappingBuffer(t,s,i)}getUserIdVideo(e){return this.mIdMgr?this.mIdMgr.getVideoTagsByUserId(e):null}_mapBufferedVideoTag(){this._videoTagMappingBuffer.size&&(this._videoTagMappingBuffer.forEach(((e,t)=>{(null==e?void 0:e.length)>0&&e.forEach((e=>{this.onVideoTagMapping({userId:t,videodom:e,action:"buffer"})}))})),this._videoTagMappingBuffer.clear())}subscribeVideo(e){const t=this.pcInfo;if(t.status!==u.CONNECTED)return e.forEach((e=>{this._toSubscribeBuffer.push({params:e,toSub:!0})})),void oi("WMSC_SubV_PC_N_Ready: ".concat(t.status));const i=Math.min(this.maxRecvVideoSize,qe.getMaxFeasibleRecvVideoSize());let s=-1;e.forEach((e=>{const{id:t,size:a}=e;this.subscriptions.set(t,a),a>s&&(s=a);const n=Math.min(a,i);n!==a&&(e.size=n),this.mIdMgr.setVideoSize(t,n),Ut.updateSubInfo(t,n)})),s>this.maxSubVideoSize&&(this.maxSubVideoSize=s,qe.updateMaxSubVideoSize(s)),this.messageCallback({type:W.UPDATE_VIDEO_SUBSCRIPTION,data:e})}unSubscribeVideo(e){if(this.pcInfo.status!==u.CONNECTED)return e.forEach((e=>{this._toSubscribeBuffer.push({params:e,toSub:!1})})),void oi("WMSC_UnsubV_PC_N_Ready");let t=-1;e.forEach((e=>{this.subscriptions.delete(e.id),Ut.updateSubInfo(e.id,-1),this.mIdMgr.setVideoSize(e.id,-1)}));for(const[,e]of this.subscriptions)e>t&&(t=e);this.maxSubVideoSize!==t&&(this.maxSubVideoSize=t,qe.updateMaxSubVideoSize(t)),this.messageCallback({type:W.UPDATE_VIDEO_UNSUBSCRIPTION,data:e})}_updateSubscriptions(e){const t=[];e.forEach((e=>{var i;const{id:s,size:a}=e;(null===(i=this.mIdMgr)||void 0===i?void 0:i.getMainVideoMId(s))&&(t.push({id:s,size:a,bOn:!1}),this.mIdMgr.setVideoSize(s,a))})),this.messageCallback({type:W.UPDATE_VIDEO_SUBSCRIPTION,data:t})}onRwgMessage(e){var t;const i="string"==typeof e.data?JSON.parse(e.data):e.data;if((null==i?void 0:i.evt)===ut||(null==i?void 0:i.evt)===mt){const e=i.body;switch(e.type){case tt:return ni.log("on SDP_ANSWER"),this.onSdpAnswer(e),!0;case st:return ni.log("on SDP_BYE"),this.onSdpBye(e),!0;case at:return ni.log("on ICE_DISCONNECTED"),this.onIceDisconnected(e),!0;case lt:return this.onSubscribeList(e.activeVideo,e.prevActiveVideo,e.privateVideo),!0;case ht:return this.onCommand(e),!0;case nt:return this._handleStreamRequest(e),!0;case ct:return null===(t=this._wmscAudioMgr)||void 0===t||t.onRWGCMDQos(e),qe.onQosReport(e),Ut.onQosReport(e),!0;case rt:var s,a;return null===(s=this._wmscAVSyncMgr)||void 0===s||s.setAudioSR(e),null===(a=this._wmscAudioMgr)||void 0===a||a.onRWGCMDRtcpSR(e),!0;case dt:var n;return null===(n=this._wmscAVSyncMgr)||void 0===n||n.setVideoSR(e.srInfos),!0;default:return ni.warn("Received unknown RWG message type: ".concat(e.type)),!1}}}async onSdpAnswer(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(!t&&!this._checkMsgIdForPC(e))return;let s=e,a=null;try{var n;if(this.negotiationTimeCost.push(performance.now()),!t){oi("WMSC_REAN");const t=this.pc,{sdp:n,sdpEncoding:o}=e;if(s=await function(e,t){return H(this,void 0,void 0,(function*(){switch(t){case E.GZIP_BASE64:{const t=function(e){const t=atob(e),i=new Uint8Array(t.length);for(let e=0;e<i.length;e++)i[e]=t.charCodeAt(e);return i.buffer}(e);return function(e){return H(this,void 0,void 0,(function*(){if(window.DecompressionStream){const t=new DecompressionStream("gzip"),i=t.writable.getWriter();return i.write(e),i.close(),new Response(t.readable).arrayBuffer().then((function(e){return(new TextDecoder).decode(e)}))}{const{ungzip:t}=yield i.e(404).then(i.bind(i,3075));return(new TextDecoder).decode(t(e).buffer)}}))}(t)}case E.PLAIN:return e;default:return null}}))}(n,o),this.pc!==t||!this._checkMsgIdForPC(e))return void oi("WMSC_ODAN");Ut.sendSdpLog("ANSWER",s),a=he.parseSdp(s),$e.updateConfigFromSdp(a)}a||(a=this.pc.getAnswer()),null===(n=this._wmscAudioMgr)||void 0===n||n.mungeAnswer(a),$e.mungeAnswer(a);let r=he.writeSdp(a);var o;await this.pc.setAnswer(r),this.negotiationTimeCost.push(performance.now()),this.pcInfo.isNegotitating=!1,oi("WMSC_SRDS"),t?this._handleSelfNegotiationSuccess():(this.sendSdpOk(),$e.saveCodecList(),$e.saveRecvMLineTemp(),null===(o=this._wmscAudioMgr)||void 0===o||o.saveRecvMLineTemp()),this._popRenegotiationQueue()}catch(e){const i=s||he.writeSdp(this.pc.answer);q(i,E.GZIP_BASE64).then((i=>{te.globalTrace({logLevel:"error",log:"WMSC_SRDF: ".concat(t,"|").concat(e.message,"|").concat(i)})})).catch((()=>{te.globalTrace({logLevel:"error",log:"WMSC_SRDF: ".concat(t,"|").concat(e.message,"|").concat(i)})})),oi("WMSC_SRDF-".concat(t,"-").concat(e.message)),"closed"!==this.pc.signalingState&&(t?this.messageCallback({type:W.SDP_NEGOTIATION_FAIL}):this.restartNegotiation())}}onSdpBye(e){this._checkMsgIdForPC(e)&&"have-local-offer"===this.pc.signalingState&&(this.closePeerConnection(),te.globalTrace({logLevel:"error",log:"WMSC_SDP_BYE_REJECT"}),oi("WMSC_BYEREJ"),this.messageCallback({type:W.SDP_NEGOTIATION_FAIL}))}onIceDisconnected(e){this._checkMsgIdForPC(e)&&(oi("WMSC_ICE_DISCON"),te.globalTrace({logLevel:"error",log:"WMSC_RestartIce_F_S"}),this.restartIce())}restartIce(){const e=this.renegotiationQueue.find((e=>{let{type:t}=e;return t===ci.ICE})),{iceRestartCount:t,isConnecting:i}=this.pcInfo;if(!e&&!i)if(t<_){this.pcInfo.iceRestartCount++,this.localIceCredential=he.generateIceCredentials(),this.pcInfo.iceCredentialMsgId++;const e=St(x.confId,null,null,null,null,ai({generation_id:this.pcInfo.iceCredentialMsgId},this.localIceCredential),this.lastStreamReqSeq,this.lastStreamStatusSeq);this._sendMessageToRwg({evt:ut,body:e}),oi("WMSC_ICECREDREQ:".concat(this.pcInfo.iceCredentialMsgId,",").concat(this.lastStreamReqSeq,",").concat(this.lastStreamStatusSeq)),this.lastStreamStatusSeq++}else this.messageCallback({type:W.PC_FAIL})}onSubscribeList(e,t,i){var s;oi(X("WMSC_On_Sub_List: ".concat(JSON.stringify(e),"|").concat(JSON.stringify(t),"|").concat(JSON.stringify(i)))),Ut.updateSubscribedSize(e,t,i);const a=h()(s=Array.from(new Set([...e,...t,...i]).values()).filter((e=>e>=0))).call(s);Y(a,this.lastSubList)||(this.lastSubList=[...a],this.pcInfo.status===u.CONNECTED&&$e.onMediaRequest(a))}onCommand(e){if(0===e.cmdId){let t;try{t=JSON.parse(e.cmdParam)}catch(t){ni.warn("Invalid command message: ".concat(JSON.stringify(e)))}void 0!==t.receiverBW?qe.onReceiverBandwidthReport(t.receiverBW):void 0!==t.subInfo?(qe.onSubInfo(t.subInfo),Ut.onDualCallState(t.subInfo)):void 0!==t.ingressReport&&(qe.onReceiverReport(t.ingressReport),Ut.onReceiverReport(t.ingressReport))}else ni.warn("Unknown command id ".concat(e.cmdId))}onActiveVideoSourceChange(e){const t=parseInt(x.nodeId)===parseInt(e.userId);return this.bPrevActiveVideo=this.bActiveVideo&&!t,this.bActiveVideo=t,Ut.setActiveSpeaker(e.userId,this.bPrevActiveVideo),oi("WMSC_OASC: ".concat(e.userId)),this.mIdMgr.setActiveSpeaker(e.userId),!0}updateWmscParams(e){ni.log("updateWmscParams, data: ".concat(JSON.stringify(e))),Object.entries(e).forEach((e=>{let[t,i]=e;switch(t){case"nodeId":var s;x.setConfig({nodeId:i}),Ut.setUserId(i),Ut.start(),null===(s=this._wmscAudioMgr)||void 0===s||s.setUserId(i);break;case"hdVideoEnabled":{const e=!!i;x.setConfig({videoSettings:ai(ai({},x.videoSettings),{},{hdVideoEnabled:e})}),$e.enableHdVideo(e)}break;case"maxEncodingFramerate":$e.setMaxEncodingFramerate(i);break;case"preferSoftwareCodec":{const e=Ae("send"),t=Ae("recv");this._updateSoftwareCodecPreference(i),t!==Ae("recv")&&(oi("WMSC_SW_PRE_RECV: ".concat(!t)),this.pcInfo.status!==u.IDLE&&this._sendRecvCodecPreference(Ye.zu.MainVideo)),e!==Ae("send")&&(oi("WMSC_SW_PRE_SEND: ".concat(!e)),this.pcInfo.status!==u.IDLE&&this._pushToRenegotiationQueue([{type:ci.MEDIA,mediaType:Ye.zu.MainVideo,preferSoftwareCodec:!e}]));break}default:ni.warn("updateWmscParams, unknown param name: ".concat(t))}}))}updateVideoSourceSettings(e){var t;const i=null===(t=this.camStreams)||void 0===t?void 0:t[0];if(!i)return;if(!e)return void $e.updateVideoSourceSettings(null);let{constraints:s,settings:a}=e;var n;s&&(i.constraints=s),a||(a=null===(n=i.stream)||void 0===n||null===(n=n.getVideoTracks()[0])||void 0===n?void 0:n.getSettings());const o=J(a,i.constraints);this.sourceVideoSize=Re(o),$e.updateVideoSourceSettings(o)}async getStats(){const e=await this.pc.getStats();for(const[t,i]of e)if("outbound-rtp"===i.type||"remote-inbound-rtp"===i.type){const e=this.mIdMgr.getMediaTypeByMid(i.mid);i.nodeId=x.nodeId,i.isSharing=e===Ye.zu.ShareAudio||e===Ye.zu.ShareVideo}else if("inbound-rtp"===i.type||"remote-outbound-rtp"===i.type){const e=this.mIdMgr.getUserIdBySsrc(i.ssrc);i.nodeId=Q(e),i.isSharing=!!(512&e)}return e}sendBye(){const e=(t=x.confId,i=o.VIDEO,s=ri,a=this.negotiationMsgId,{type:st,confID:t,sessionID:i,peerID:s,msgID:a,sdp:""});var t,i,s,a;this._sendMessageToRwg({evt:ut,body:e}),oi("WMSC_SDPBYE")}sendSdpOk(){const e=(t=x.confId,i=o.VIDEO,s=ri,a=this.negotiationMsgId,{type:it,confID:t,sessionID:i,peerID:s,msgID:a});var t,i,s,a;this._sendMessageToRwg({evt:ut,body:e}),oi("WMSC_SDPOK")}_sendMessageToRwg(e){this.messageCallback({type:W.WMSC_MESSAGE_TO_RWG_BY_SDK,data:JSON.stringify(e)})}async _handleRemoteStream(e){var t;const i=new MediaStream,{track:s,transceiver:a,streams:n=[]}=e,{kind:o}=s,r=a.mid,c=(null===(t=n[0])||void 0===t?void 0:t.id)||"";if(oi("WMSC_RSV_M: ".concat(r,"-").concat(o)),"video"===o)this.mIdMgr.addMidResource(r,{streamId:c,track:s,transceiver:a});else if("audio"===o){var d;this.mIdMgr.addMidResource(r,{streamId:c}),i.addTrack(s);const e=this.mIdMgr.getUserIdByMid(r);null===(d=this._wmscAudioMgr)||void 0===d||d.onRemoteStream(i,s,r,e)}}async _handleSdpOffer(e){let t=E.PLAIN,i=e;const s=this.pc;try{i=await q(e,E.GZIP_BASE64),t=E.GZIP_BASE64}catch(e){te.globalTrace({logLevel:"error",log:"WMSC_Compress_SDP_Offer_F",errorEvent:e})}if(this.pc!==s)return;const a=this.pcInfo.offerMsgId,n=((e,t,i,s,a,n,o,r,c,d)=>{const h=[{key:"webrtc_dynamic_egress_media_streams",value:!0},{key:"webrtc_client_sending_codec_preference",value:o},{key:"webrtc_client_recving_codec_preference",value:r}];return c&&h.push({key:"webrtc_max_total_video_streams",value:c}),d===z.WEBRTC_SYNC&&h.push({key:"webrtc_egress_avsync_enabled",value:!0}),{type:et,confID:e,sessionID:t,peerID:i,msgID:s,sdp:a,sdpEncoding:n,featureToggles:h}})(x.confId,o.VIDEO,ri,a,i,t,$e.getPreferPayloadTypes("send"),$e.getPreferPayloadTypes("recv"),(0,de.GN)()?this.recvMLineNum:null,x.avSyncMode);this._sendMessageToRwg({evt:ut,body:n}),Ut.sendSdpLog("OFFER",e)}_handlePcStateChange(e){const t=this.pcInfo;if(oi("WMSC_onconnectionstatechange: ".concat(e)),"connected"===e){this.negotiationTimeCost.push(performance.now());const e=this._getNegotiationTime(),i="-".concat(t.iceRestartCount,"-").concat(t.reconnectionCount);for(te.globalTrace({logLevel:"directReport",log:e.join("-")+i,tags:["WMSC Negotiation time"]}),oi("WMSCNT-".concat(e.join("-")).concat(i)),clearTimeout(t.negotiationTimer),clearTimeout(t.reconnectTimer),t.status=u.CONNECTED,t.reconnectionCount=0,t.negotiationTimer=0,t.iceRestartCount=0,t.isConnecting=!1,ni.log("_handlePcStateChange: connected"),$e.onMediaRequest(this.lastSubList);this._toSubscribeBuffer.length;){const e=this._toSubscribeBuffer.shift();e.toSub?this.subscribeVideo([e.params]):this.unSubscribeVideo([e.params])}this.messageCallback({type:W.PC_CONNECTED})}else if("disconnected"===e)this.pcInfo.reconnectTimer=setTimeout((()=>{"disconnected"===this.pc.connectionState&&(oi("WMSC_PC_Disconn"),this.restartIce())}),p);else if("failed"===e){const e="WMSC_PC_State_Failed: ".concat(this._getNegotiationTime().join("-"));te.globalTrace({logLevel:"error",log:e}),oi(e),this._enableTURN(),this.restartIce()}}_handlePageVisibilityChange(){"visible"===document.visibilityState&&(this.messageCallback({type:W.PC_CLOSED}),document.removeEventListener("visibilitychange",this._handlePageVisibilityChange))}_handleSignalingStateChange(e){oi("WMSC_onsignalingstatechange: ".concat(e)),"closed"===e&&setTimeout((()=>{di.PC_CLOSE_CNT++,"hidden"===document.visibilityState?(te.globalTrace({logLevel:"error",log:"WMSC_PC_CLOSE: HIDDEN"}),document.addEventListener("visibilitychange",this._handlePageVisibilityChange)):(di.PC_UNKNOWN_CLOSE_CNT>=v?this.messageCallback({type:W.PC_FAIL}):this.messageCallback({type:W.PC_CLOSED}),di.PC_UNKNOWN_CLOSE_CNT++,te.globalTrace({logLevel:"error",log:"WMSC_PC_CLOSE_UNKNOWN: ".concat(di.PC_UNKNOWN_CLOSE_CNT)}))}),1500)}_handleIceConnectionStateChange(e){oi("WMSC_ICESTATE: ".concat(e)),"failed"===e&&te.globalTrace({logLevel:"error",log:"WMSC_ICE_State_Error: ".concat(e)})}_handleDecodeError(e){$e.removeRecvCodecByProfile(e),0===$e.ingressCodecList.length?(te.globalTrace({logLevel:"error",log:"WMSC_No_Recv_Codec"}),oi("WMSC_ERC"),this.messageCallback({type:W.VIDEO_FAIL,data:ri})):this._sendRecvCodecPreference(Ye.zu.MainVideo)}_checkMsgIdForPC(e){const{msgID:t}=e,{offerMsgId:i}=this.pcInfo;return t===i||(ni.warn("Message id ".concat(t," doesn't match the offer message id ").concat(i)),!1)}_getNegotiationTime(){const e=this.negotiationTimeCost,t=[];if(e){const i=e.length;for(let s=0;s<i-1;s++)t.push(Math.round(e[s+1]-e[s]));t.push(Math.round(performance.now()-e[0]))}return t}_updateSoftwareCodecPreference(e){var t;let{videoSettings:i}=x.getConfig();var s;null!==(t=i)&&void 0!==t&&t.preferSoftwareCodec?i.preferSoftwareCodec=ai(ai({},null===(s=i)||void 0===s?void 0:s.preferSoftwareCodec),e):i={preferSoftwareCodec:e},x.setConfig({videoSettings:i})}_handleNewMLine(e){const{mediaType:t}=e;let i;if(t===Ye.zu.MainVideo)i=$e.addRecvVideoSDP(e),i.rtp_payload_type=$e.getRecvCodecPayloads();else if(t===Ye.zu.MainAudio){var s;i=null===(s=this._wmscAudioMgr)||void 0===s?void 0:s.addRecvAudioSDP(e)}else if(t===Ye.zu.ShareAudio){var a;i=null===(a=this._wmscAudioMgr)||void 0===a?void 0:a.addRecvAudioSDP(e)}this.createdMLine.push(i)}async doRenegotiation(){if("closed"===this.pc.signalingState)return;this.numOfTasks=this.renegotiationQueue.length;let e=!1;for(let i=0;i<this.numOfTasks;i++){const s=this.renegotiationQueue[i],{type:a,mediaType:n}=s;if(a===ci.ICE)e=s;else if(a===ci.REMOVE_MLINE){const{mid:e}=s,t=this.pc.getRecvTransceiverByMid(e);t&&t.stop()}else if(a===ci.ADD_MLINE){let e;if(n===Ye.zu.MainVideo)e=$e.addRecvTransceiver();else if(n===Ye.zu.MainAudio||n===Ye.zu.ShareAudio){var t;const{ssrcs:i,msid:a,user_id:o}=s,{rtp:r}=i;e=null===(t=this._wmscAudioMgr)||void 0===t?void 0:t.addRecvTransceiver(n,null==o?void 0:o.node_id,r,a,null==o?void 0:o.is_current)}s.transceiver=e.transceiver}}const i=[];try{await this.startNegotiation(!0,{iceRestart:!!e}),this.pc.removeUnusedTransceiver();for(let t=0;t<this.numOfTasks;t++){const n=this.renegotiationQueue[t],{type:o}=n;if(o===ci.ADD_MLINE)this._handleNewMLine(n),i.push("".concat(ci.ADD_MLINE,"-").concat(n.mediaType,"-").concat(n.transceiver.mid));else if(o===ci.REMOVE_MLINE){const{mid:e}=n;this.pc.removeMLineSDPFromAnswer(e),this.removedMids.push(e),i.push("".concat(ci.REMOVE_MLINE,"-").concat(e))}else if(o===ci.MEDIA){const{mediaType:e,preferSoftwareCodec:t}=n;if(e===Ye.zu.MainVideo)$e.updateEgressAnswerCodec(t);else if(e===Ye.zu.MainAudio){var s;this.updatedMlineFmtp.push(null===(s=this._wmscAudioMgr)||void 0===s?void 0:s.getUpdatedMlineFtmpFromLocalOffer())}i.push("".concat(ci.MEDIA,"-").concat(e,"-").concat(t))}else if(o===ci.ICE){var a;const{remoteIceCredential:t,generation_id:s}=e;this.pc.updateAnswerIceCredential(t),$e.updateRecvMLineTemp(t),null===(a=this._wmscAudioMgr)||void 0===a||a.updateRecvMLineTemp(t),i.push("".concat(ci.ICE,"-").concat(s))}else o===ci.UPDATE_BITRATE&&this.ongoingUpdateBitrateTasks.push(n)}if(this.ongoingUpdateBitrateTasks.length){const{bitrate:e}=this.ongoingUpdateBitrateTasks[this.ongoingUpdateBitrateTasks.length-1];$e.updateMinOutgoingBitrateInSDP(e),i.push("".concat(ci.UPDATE_BITRATE,"-").concat(e))}this.onSdpAnswer(null,!0),oi("WMSC_DORN: ".concat(i.join("|")))}catch(e){const{message:t}=e;te.globalTrace({logLevel:"error",log:"WMSC_SRNF: ".concat(t),errorEvent:e}),oi("WMSC_SRNF: ".concat(t))}}requestSelfRenegotiation(e){this._pushToRenegotiationQueue([{type:ci.MEDIA,mediaType:e}])}_pushToRenegotiationQueue(e){e.length&&(this.renegotiationQueue=this.renegotiationQueue.concat(e),this.pcInfo.isNegotitating||this.doRenegotiation())}_popRenegotiationQueue(){this.renegotiationQueue.splice(0,this.numOfTasks),this.renegotiationQueue.length&&!this.pcInfo.isNegotitating&&this.doRenegotiation()}_handleStreamRequest(e){var t,i;const s=[];this.lastStreamReqSeq=e.stream_request_msg_index;let a=[],n=[];if(e.delete&&e.delete.forEach((e=>{var t,i;null===(t=this._wmscAVSyncMgr)||void 0===t||t.deleteSRByMid(e),this.pc.getRecvTransceiverByMid(e)&&s.push({type:ci.REMOVE_MLINE,mid:e});const a=this.mIdMgr.getUserIdByMid(e);a&&Ut.resetRecvStats(a),this.mIdMgr.removeMidResource(e),null===(i=this._wmscAudioMgr)||void 0===i||i.onMlineRemoved(e)})),e.create&&e.create.forEach((e=>{let{msid:t,media_type:i,ssrcs:n,user_id:o}=e,r="";o&&(r=this._getUserId(o)),r&&!t&&(t=this.mIdMgr.getMactchedMSIDByUserId(r)),i===Ye.zu.MainVideo?s.push({type:ci.ADD_MLINE,mediaType:Ye.zu.MainVideo,msid:t,ssrcs:n,user_id:o}):i!==Ye.zu.MainAudio&&i!==Ye.zu.ShareAudio||s.push({type:ci.ADD_MLINE,mediaType:i,msid:t,ssrcs:n,user_id:o}),a.push("".concat(i,"-").concat(r))})),e.associate&&e.associate.forEach((e=>{let{media_type:t,mid:i,user_id:s,ssrcs:a}=e;const{is_current:o}=s,r=this._getUserId(s);if(this.mIdMgr.attachMid(r,i,t,o),t===Ye.zu.MainAudio||t===Ye.zu.ShareAudio){var c;const{rtp:e}=a;null===(c=this._wmscAudioMgr)||void 0===c||c.onMlineAssignedNodeId(t,i,s.node_id,e,o)}n.push("".concat(t,"-").concat(i,"-").concat(r))})),e.ice_restart_resp){const{generation_id:t,ice_ufrag:i,ice_pwd:a}=e.ice_restart_resp;t===this.pcInfo.iceCredentialMsgId&&s.push({type:ci.ICE,remoteIceCredential:{ice_ufrag:i,ice_pwd:a},generation_id:t})}this._pushToRenegotiationQueue(s),oi("WMSC_SREQ:".concat(a.join(","),"|").concat((null===(t=e.delete)||void 0===t?void 0:t.join(","))||"","|").concat(n.join(","),"|").concat((null===(i=e.ice_restart_resp)||void 0===i?void 0:i.generation_id)||""))}_getUserId(e){const{node_id:t,is_current:i}=e;return 0==i?1|t:t}_handleSelfNegotiationSuccess(){let e=[];if(this.createdMLine.forEach((t=>{var i;let{mid:s,user_id:a,media_type:n,ssrcs:o}=t;const{rtp:r}=o;let c="";a&&(c=this._getUserId(a),this.mIdMgr.attachMid(c,s,n,a.is_current)),this.mIdMgr.ssrcMidMap.set(r,s),null==a||!a.node_id||n!==Ye.zu.MainAudio&&n!==Ye.zu.ShareAudio||null===(i=this._wmscAudioMgr)||void 0===i||i.onMlineAssignedNodeId(n,s,null==a?void 0:a.node_id,r,null==a?void 0:a.is_current),e.push("".concat(n,"-").concat(s,"-").concat(c))})),this.ongoingUpdateBitrateTasks.forEach(((e,t)=>{const{resolve:i,reject:s}=e;t===this.ongoingUpdateBitrateTasks.length-1?i():s()})),this.createdMLine.length||this.removedMids.length||this.updatedMlineFmtp.length){const t=St(x.confId,this.createdMLine,this.removedMids,this.updatedMlineFmtp,null,null,this.lastStreamReqSeq,this.lastStreamStatusSeq);this._sendMessageToRwg({evt:ut,body:t}),oi("WMSC_SRES:".concat(e.join(","),"|").concat(this.removedMids.join(","),"|").concat(this.updatedMlineFmtp.join(","),"|").concat(this.lastStreamReqSeq,"|").concat(this.lastStreamStatusSeq)),this.lastStreamStatusSeq++}this.createdMLine=[],this.removedMids=[],this.updatedMlineFmtp=[],this.ongoingUpdateBitrateTasks=[],oi("WMSCNTS-".concat(this._getNegotiationTime().join("-")))}_sendRecvCodecPreference(e){if(e===Ye.zu.MainVideo){const t=$e.getRecvCodecPayloads();if(t.length>0){const i=St(x.confId,null,null,null,[{media_type:e,rtp_payload_type:t}],null,this.lastStreamReqSeq,this.lastStreamStatusSeq);this._sendMessageToRwg({evt:ut,body:i}),oi("WMSC_SRCP:".concat(t.join(","),",").concat(this.lastStreamReqSeq,",").concat(this.lastStreamStatusSeq)),this.lastStreamStatusSeq++}}}_detectConnectionTimeout(){const{useIceServers:e,negotiationTimer:t}=this.pcInfo;t&&clearTimeout(t),this.pcInfo.isConnecting=!0,this.pcInfo.negotiationTimer=setTimeout((()=>{if(this.pcInfo.isConnecting=!1,"connected"!==this.pc.connectionState){var e,t;const i=this._getNegotiationTime();te.globalTrace({logLevel:"error",log:"WMSC Negotiation timeout: ".concat(this.pcInfo.useIceServers?1:0,"-").concat(i.length,"-").concat(this.pcInfo.offerMsgId,"-").concat(i.join("-"))}),te.globalTrace({logLevel:"error",log:"WMSC_PCCT: ".concat(null===(e=x.iceServers)||void 0===e?void 0:e.length,"|").concat(this.pc.connectionState)}),oi("WMSC_PCCT: ".concat(null===(t=x.iceServers)||void 0===t?void 0:t.length,"|").concat(this.pc.connectionState)),this._enableTURN(),this.pc.currentRemoteDescription?this.restartIce():this.restartNegotiation()}else this.pcInfo.iceRestartCount=0}),e?g:m)}_enableTURN(){const{useIceServers:e}=this.pcInfo;e||(te.globalTrace({logLevel:"directReport",log:"WMSC_USE_TURN"}),this.pcInfo.useIceServers=!0,this.pc.currentRemoteDescription&&this.pc.setConfiguration({iceServers:x.iceServers||[]}))}}(0,c.A)(di,"PC_UNKNOWN_CLOSE_CNT",0);const hi=di,li=te.getTracer("Wmsc"),ui=e=>{li.log(e),te.monitorLog("".concat(e))};class mi{constructor(e,t){this.messageCallback=t,this.config=e,this.config.probe||(te.setTrace(),te.setTelemetry(t),Ut.setTelemetry(t),ui("WMSC_INIT"))}setTrace(e,t){te.setTrace(e,t)}updateQosSubscription(e,t){Ut.updateQosSubscription(e,t)}enableVideoObserver(e,t){Ut.enableVideoObserver(e,t)}reportWMSCPeerConnectionRawStats(){Ut.reportRawStats()}getHasPausedVideo(){var e;return null===(e=this.wmscApiImpl)||void 0===e||null===(e=e.mIdMgr)||void 0===e?void 0:e.getHasPausedVideo()}playAllUsedVideoTag(){var e;return null===(e=this.wmscApiImpl)||void 0===e||null===(e=e.mIdMgr)||void 0===e?void 0:e.playAllUsedVideoTag()}getUserIdVideo(e){var t;return null===(t=this.wmscApiImpl)||void 0===t?void 0:t.getUserIdVideo(e)}destroy(){var e;ui("WMSC_DESTROYED"),null===(e=this.wmscApiImpl)||void 0===e||e.destroy(),this.wmscApiImpl=null}onMessage(e,t){if(e!==F.NOTIFY_SDK_JOIN_RWG_SUCCESS&&!this.wmscApiImpl)return this.sendMessage&&this.sendMessage({type:W.ERROR,data:"WMSC on MediaSDK message, MediaSDK not ready, type = "+e}),li.error("onMessage, the caller not ready type ".concat(e)),!1;switch(e){case F.NOTIFY_SDK_JOIN_RWG_SUCCESS:return this.messageCallback?(this.wmscApiImpl=new hi(this.config,this.sendMessage.bind(this)),!0):(li.error("onMessage, messageCallback to the caller not set"),!1);case F.NOTIFY_SDK_JOIN_RWG_FAILURE:return!0;case F.WMSC_MESSAGE_FROM_RWG:return this._onRwgMessage(t.data);case F.NOTIFY_WMSC_VIDEO_TAG_MAPPING:return this._onVideoTagMapping(t.data);case F.NOTIFY_SDK_SUBSCRIBE_VIDEO:return this._onSubscribeVideo(t.data);case F.NOTIFY_SDK_UNSUBSCRIBE_VIDEO:return this._onUnSubscribeVideo(t.data);case F.NOTIFY_SDK_ACTIVE_VIDEO_INDICATION:return this._onActiveVideoSourceChange(t.data);case F.UPDATE_WMSC_PARAMS:return this._onUpdateWmscParams(t.data);case F.UPDATE_VIDEO_SOURCE_SETTINGS:return this._updateVideoSourceSettings(t.data);default:return this.sendMessage({type:W.ERROR,data:"WSMC receive not handled event type = "+e}),li.error("onMessage, unknown type ".concat(e)),ui("WSMC_Rece_U_E: ".concat(e)),!1}}onMessageAsync(e,t){return li.log("WMSC_Recv_Async_M",e,JSON.stringify(t)),ui("WMSC_Recv_Async_M: ".concat(e)),e===F.VIDEO_STREAMS?this._onVideoStreamsAsync(t.data):(this.sendMessage({type:W.ERROR,data:"WSMC receive not handled event type =".concat(e)}),li.error("WSMC receive not handled event type =".concat(e)),Promise.reject("Unknown message type"))}sendMessage(e){li.log("sendMessage",JSON.stringify(e)),this.messageCallback&&this.messageCallback(e)}getWmscAudio(){return this.wmscApiImpl.getWMSCAudioMgr()}_onVideoStreamsAsync(e){return this.wmscApiImpl.onVideoStreamsAsync(e)}_onRwgMessage(e){return this.wmscApiImpl.onRwgMessage(e)}_onVideoTagMapping(e){return this.wmscApiImpl.onVideoTagMapping(e)}_onSubscribeVideo(e){return this.wmscApiImpl.subscribeVideo(e)}_onUnSubscribeVideo(e){return this.wmscApiImpl.unSubscribeVideo(e)}_onActiveVideoSourceChange(e){return this.wmscApiImpl.onActiveVideoSourceChange(e)}_onUpdateWmscParams(e){return this.wmscApiImpl.updateWmscParams(e)}_updateVideoSourceSettings(e){return this.wmscApiImpl.updateVideoSourceSettings(e)}getStats(){return this.wmscApiImpl.getStats()}}class pi{constructor(){this.status="pending",this.promise=new Promise(((e,t)=>{this.reject=e=>(this.status="rejected",t(e)),this.resolve=t=>(this.status="fullfilled",e(t))})),this.then=this.promise.then,this.catch=this.promise.catch}}var gi,Si,_i,vi=i(385),fi=i(7080),yi=i(7350),Mi=i.n(yi),Ci=i(1223),Ii=function(e,t,i,s){return new(i||(i=Promise))((function(a,n){function o(e){try{c(s.next(e))}catch(e){n(e)}}function r(e){try{c(s.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?a(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,r)}c((s=s.apply(e,t||[])).next())}))};!function(e){e.visibilitychange="visibilitychange",e.streamCaptureSuccess="streamCaptureSuccess",e.videoTrackUnmute="videoTrackUnmute",e.addRenderVideo="addRenderVideo",e.userClick="userClick",e.fromVBModule="fromVBModule",e.reuseCaptureStream="reuseCaptureStream"}(gi||(gi={})),function(e){e.destroy="destroy"}(Si||(Si={})),function(e){e.WMSC_WSS_OPEN_FAIL_IN_30s="WMSC_WSS_OPEN_FAIL_IN_30s",e.WMSC_WSS_NOT_RECEIVE_MSG_IN_30s="WMSC_WSS_NOT_RECEIVE_MSG_IN_30s",e.WMSC_WSS_CLOSE="WMSC_WSS_CLOSE",e.WMSC_WSS_ERROR="WMSC_WSS_ERROR",e.WMSC_SDP_NEGOTIATION_FAIL="WMSC_SDP_NEGOTIATION_FAIL",e.WMSC_PC_FAIL="WMSC_PC_FAIL",e.WMSC_VIDEO_FAIL="WMSC_VIDEO_FAIL",e.WMSC_PC_CLOSED="WMSC_PC_CLOSED"}(_i||(_i={}));class Ei{constructor(e){this._config={webRTCWebSocketUrl:"",confId:"",nodeId:"",hdVideoEnabled:!1,mediaStreamController:void 0,iceServers:[],videoCodecConfig:void 0,webrtcMode:0,probe:!1,requestHandler:null},this._websocket=null,this._wmsc=null,this._isDestroyed=!1,this._qosFlag=new Set,this.isJoinRWGSuccess=!1,this._joinRWGSuccessPromise=new pi,this._initAudioSuccessPromise=new pi,this._lastTimeStamp=0,this.selfVideoDomMap=new Map,this.activeSpeakerVideoDom=null,this._selfStream=null,this._activeSpeakerSsrc=-1,this.isMirror=!1,this._vbSettingVideoDom=null,this._notifyAudioSuccess=!1,this._sourceVideoSettings=null,this.meetingEnded=!1,this._createWSS=()=>{this._onWSSOpenTimer=setTimeout((()=>{this._tryFailover(_i.WMSC_WSS_OPEN_FAIL_IN_30s)}),3e4);const{webRTCWebSocketUrl:e}=this._config;this._websocket=(0,bt.Gj)(e),this._websocket.onopen=this._onOpen,this._websocket.onclose=this._onClose,this._websocket.onmessage=this._onMessage,this._websocket.onerror=this._onError,this.wmscAddMonitorLog("WMSC_Create_WSS:".concat(e.replace(/(\/media\/)\d+/,"$1".concat("meetingNumber"))))},this._onOpen=()=>{if(clearTimeout(this._onWSSOpenTimer),!this._wmsc){const{confId:e,nodeId:t,hdVideoEnabled:i,iceServers:s,videoCodecConfig:a,webrtcMode:n,probe:o,avSyncMode:r}=this._config,c=(0,de.j4)();if(this.wmscAddMonitorLog("WMSC_Instance_Params: ".concat(e,"|").concat(t,"|").concat(i,"|").concat(c,"}")),!e)return;const d={confId:e,nodeId:t||"",isMacIntel:c,iceServers:s,videoSettings:Object.assign(Object.assign({},a),{maxCaptureVideoSize:3,maxRecvVideoNum:this._config.probe?1:26,hdVideoEnabled:i}),webrtcMode:n,probe:o,avSyncMode:r};this._wmsc=new mi(d,this._wmscCallBack),this.sendMessageToWMSC({type:F.NOTIFY_SDK_JOIN_RWG_SUCCESS,data:""}),this.isJoinRWGSuccess=!0,this._joinRWGSuccessPromise.resolve()}},this._isKeepAliveMessage=e=>{let t=!0;for(let i=0;i<4;i++)if(0!==e[i]){t=!1;break}return t},this._checkReceiveTimeout=()=>{clearTimeout(this._keepAliveTimer),this._keepAliveTimer=setTimeout((()=>{Date.now(),this._tryFailover(_i.WMSC_WSS_NOT_RECEIVE_MSG_IN_30s)}),3e4)},this._replyActiveAliveMessage=e=>{(null==e?void 0:e.data)instanceof Blob&&bt.Ay.readBlobAsBuffer(e.data).then((e=>{var t;const i=new Int8Array(e);this._isKeepAliveMessage(i)&&(null===(t=this._websocket)||void 0===t||t.send(i))})).catch((e=>{vi.Ay.error("WMSC_Read_Alive_F",e)}))},this._onMessage=e=>{var t;if(this._websocket.isRlb||(this._checkReceiveTimeout(),this._replyActiveAliveMessage(e)),!((null==e?void 0:e.data)instanceof Blob)&&this._wmsc){if(e.data&&"string"==typeof e.data){let i,s,a;try{const{evt:t="",body:{reason:n,subReason:o}}=JSON.parse(e.data);i=t,s=n,a=o}catch(e){return void vi.Ay.error("WMSC_Unexpect_Wsss_Message",e)}if(i===Ht.zag&&(!(null===(t=Gt.A.shouldKeepAVWhenFailover)||void 0===t?void 0:t.waitingRoom)||5!==s||1!==a)){this.meetingEnded=!0;const e="WMSC_Meeting_Ended_Indicat: ".concat(Date.now());this.wmscAddMonitorLog(e),vi.Ay.error(e)}}this.sendMessageToWMSC({type:F.WMSC_MESSAGE_FROM_RWG,data:e})}},this._onClose=e=>{1e3!==e.code?this._tryFailover(_i.WMSC_WSS_CLOSE,e.code):this.wmscAddMonitorLog("WMSC_WSS_NORMAL_CLOSE: ".concat(e.code,"|").concat(this._isDestroyed,"|").concat(this.meetingEnded))},this._onError=e=>{this._tryFailover(_i.WMSC_WSS_ERROR)},this._tryFailover=(e,t)=>{if(this._config.probe)return;const i=(0,bt.Tv)();let s="".concat(i),a=!1,n=!1;switch(e){case _i.WMSC_WSS_OPEN_FAIL_IN_30s:s="WMSC_WSS_OPEN_FAIL:"+s;break;case _i.WMSC_WSS_NOT_RECEIVE_MSG_IN_30s:s="WMSC_WSS_RECV_FAIL:"+s;break;case _i.WMSC_WSS_CLOSE:s="WMSC_WSS_CLOSE: ".concat(t,"|")+s;break;case _i.WMSC_WSS_ERROR:s="WMSC_WSS_ERROR:"+s;break;case _i.WMSC_SDP_NEGOTIATION_FAIL:s="WMSC_SDP_NEGO_F:"+s,n=!0,this._config.webrtcMode&It.Q9||(a=!0);break;case _i.WMSC_PC_FAIL:s="WMSC_PC_F:"+s,a=!!(this._config.webrtcMode&It.h),n=!!(this._config.webrtcMode&It.Q9);break;case _i.WMSC_VIDEO_FAIL:s="WMSC_VIDEO_F:"+s,n=!0;break;case _i.WMSC_PC_CLOSED:s="WMSC_PC_CLOSED:"+s;break;default:s="WMSC_FAILOVER_UNEXPECT:"+s}if((this._isDestroyed||this.meetingEnded)&&vi.Ay.log("WMSC destroyed or meeting end, but try failover : ".concat(s,"|").concat(n,"|").concat(a,"|").concat(this._isDestroyed,"|").concat(this.meetingEnded)),!this._isDestroyed&&!this.meetingEnded){this.destroy(),Gt.A.supportAVSimultaneousFallback&&(a||n)&&(vi.Ay.directReport("audio and video fallback together, audioFailover: ".concat(a,", videoFailover: ").concat(n)),a=!0,n=!0);const e="".concat(s,"|").concat(n,"|").concat(a);this.wmscAddMonitorLog(s),vi.Ay.error(e),Gt.A.Notify_APPUI(Ht.oQY,{audio:a?It.nm:0,video:n?1:0})}},this._disconnect=e=>{var t;const i="WMSC_WSS_Dissconn: ".concat(e,"|").concat(null===(t=null==this?void 0:this._websocket)||void 0===t?void 0:t.readyState);this.wmscAddMonitorLog(i),vi.Ay.log(i),!this._websocket||this._websocket.readyState!==WebSocket.CONNECTING&&this._websocket.readyState!==WebSocket.OPEN||this._websocket.close()},this.sendMessageToWMSC=e=>{var t;(null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.data)instanceof Blob||this._wmsc&&this._wmsc.onMessage(e.type,e)},this.sendMessageToWMSCAsync=e=>this._wmsc?this._wmsc.onMessageAsync(e.type,e):Promise.reject("this._wmsc is undefined"),this._wmscCallBack=e=>{var t,i,s,a,n,o,r,c,d,h,l;if(!e)return;const{type:u,data:m}=e;switch(u){case W.WMSC_MESSAGE_TO_RWG_BY_SDK:this.sendMesssageToRWG(m);break;case W.SDP_NEGOTIATION_FAIL:null===(i=(t=this._config).requestHandler)||void 0===i||i.call(t,"negotiationResult",!1),this._tryFailover(_i.WMSC_SDP_NEGOTIATION_FAIL);break;case W.PC_FAIL:null===(a=(s=this._config).requestHandler)||void 0===a||a.call(s,"negotiationResult",!1),this._tryFailover(_i.WMSC_PC_FAIL);break;case W.VIDEO_FAIL:null===(o=(n=this._config).requestHandler)||void 0===o||o.call(n,"negotiationResult",!1),this._tryFailover(_i.WMSC_VIDEO_FAIL);break;case W.PC_CLOSED:this._tryFailover(_i.WMSC_PC_CLOSED);break;case W.GLOBAL_TRACE:{const{logLevel:e,log:t,errorEvent:i,tags:s}=m;vi.Ay[e](t,i||s);break}case W.MONITOR:this.wmscAddMonitorLog(m);break;case W.DIRECT_MONITOR:fi.A.send_monitor_directly(m);break;case W.VIDEO_QOS_DATA:Gt.A.Notify_APPUI(Ht.PgM,m);break;case W.CURRENT_DECODE_VIDEO_QUALITY:Gt.A.Notify_APPUI(Ht.TaW,m);break;case W.CURRENT_DECODE_VIDEO_FPS:Gt.A.Notify_APPUI(Ht.$xb,m);break;case W.NETWORK_QUALITY_CHANGE:Gt.A.Notify_APPUI(Ht.Ah8,m);break;case W.UPDATE_VIDEO_CAPTURE_CONSTRAINTS:(null===(r=this._config.mediaStreamController)||void 0===r?void 0:r.isUsingFileInputVideoSource())||this._updateVideoConstraints(m);break;case W.VIDEO_CAPABILITIES_CHANGE:this._websocket.send(JSON.stringify({evt:Ht.I6S,body:{fullHDOption:m.maxRecvVideoSize>=4?1:0}}));break;case W.PC_CONNECTED:null===(d=(c=this._config).requestHandler)||void 0===d||d.call(c,"negotiationResult",!0),this._config.webrtcMode&It.h&&(this._initAudioSuccessPromise.resolve(),Gt.A.Notify_APPUI(Ht.LYk,{mediaType:"audio"})),this._config.webrtcMode&It.Q9&&Gt.A.Notify_APPUI(Ht.LYk,{mediaType:"video"});break;case W.UPDATE_VIDEO_SUBSCRIPTION:Ci.A.sendSubscribeVideoMsgToRWG(m);break;case W.UPDATE_VIDEO_UNSUBSCRIPTION:Ci.A.sendUnsubscribeVideoMsgToRWG(m);break;case W.AUDIO_RECAPTURE:null===(l=(h=this._config).requestHandler)||void 0===l||l.call(h,"audioRecapture",!0);break;case W.ERROR_MESSAGE:this.handleWMSCErrorMsg(m)}},this.waitJoinRWGSuccess=()=>this._joinRWGSuccessPromise.promise,this.waitInitAudioSuccess=()=>this._initAudioSuccessPromise.promise,this.getConnectionId=()=>this._config.confId,this.updateQosSubscription=(e,t,i)=>{var s,a;e?(this._qosFlag.add(t),null===(s=this._wmsc)||void 0===s||s.updateQosSubscription(e,i)):(this._qosFlag.delete(t),0===this._qosFlag.size&&(null===(a=this._wmsc)||void 0===a||a.updateQosSubscription(e,i)))},this.playAllVideoTag=e=>{var t;if(this.selfVideoDomMap.forEach((t=>{t.paused&&this.playSelfVideo(e,t)})),null===(t=null==this?void 0:this._wmsc)||void 0===t?void 0:t.playAllUsedVideoTag){if(!this._wmsc.getHasPausedVideo())return;this._wmsc.playAllUsedVideoTag().then((()=>{})).catch((t=>{const i="WMSC_RV_P_F: ".concat(e,"|").concat(t);this.wmscAddMonitorLog(i),vi.Ay.error(i)}))}},this.playSelfVideo=(e,t)=>{var i;let s="";"visible"!==document.visibilityState&&(s="WMSC_SV_V_F: ".concat(document.visibilityState,"-").concat(e)),t||(s="WMSC_SV_DOM_F: ".concat(e)),t.srcObject||(s="WMSC_SV_SRC_F: ".concat(e));const a=null===(i=null==t?void 0:t.srcObject)||void 0===i?void 0:i.getVideoTracks();if(Array.isArray(a)&&a[0]&&a[0].muted&&(s="WMSC_SV_TM_F: ".concat(document.visibilityState,"-").concat(e)),t.paused||(s="WMSC_SV_P_F: ".concat(e)),s)return this.wmscAddMonitorLog(s),void vi.Ay.error(s);t.readyState>t.HAVE_CURRENT_DATA||t.play().then((()=>{this.wmscAddMonitorLog("WMSC_SV_SUCCESS: ".concat(e))})).catch((t=>{s="WMSC_SV_P_E: ".concat(e,"|").concat(t.name,":").concat(t.message),this.wmscAddMonitorLog(s),vi.Ay.error(s,t)}))},this.setNodeId=e=>{this._config.nodeId!==e&&(this._config.nodeId=e,this.sendMessageToWMSC({type:F.UPDATE_WMSC_PARAMS,data:{nodeId:e}}))},this.getUserIdVideo=e=>{var t;return 1==e?[this.activeSpeakerVideoDom]:this.isSelfVideo(e)?[Array.from(this.selfVideoDomMap.values()).find((e=>!e.paused))]:null===(t=this._wmsc)||void 0===t?void 0:t.getUserIdVideo(e)},this.mirrorVideoEle=(e,t)=>{const i="rotateY(".concat(t?180:0,"deg)");let s=e.style.transform;const a=-1!==s.indexOf("rotateY");(t||a)&&-1===s.indexOf(i)&&(a?s=s.replace(/rotateY\([0-9]+(deg)?\)/,i):s+=" ".concat(i),e.style.transform=s)},this.mirrorSelfVideo=e=>{if(this.isMirror=e,this.selfVideoDomMap.size>0&&this.selfVideoDomMap.forEach((e=>{this.mirrorVideoEle(e,this.isMirror)})),this.activeSpeakerVideoDom&&this._isSelfActiveSpeaker()&&this.mirrorVideoEle(this.activeSpeakerVideoDom,this.isMirror),this.vbSettingVideoDom&&this.mirrorVideoEle(this.vbSettingVideoDom,this.isMirror),this.selfVideoDomMap.size<=0&&!this.activeSpeakerVideoDom&&!this.vbSettingVideoDom){const t="WMSC_MIRROR_F:".concat(e);this.wmscAddMonitorLog(t),vi.Ay.error(t)}},this.wmscAddMonitorLog=e=>{this._config.probe||fi.A.add_monitor(e)},this.onActiveSpeakerChange=e=>{this.sendMessageToWMSC({type:F.NOTIFY_SDK_ACTIVE_VIDEO_INDICATION,data:{userId:e}}),this._activeSpeakerSsrc=e,this._updateActiveSpeakerStream()},this._updateActiveSpeakerStream=()=>{this.activeSpeakerVideoDom&&(this._isSelfActiveSpeaker()?this._selfStream&&(this.activeSpeakerVideoDom.srcObject=this._selfStream,this.mirrorVideoEle(this.activeSpeakerVideoDom,this.isMirror)):this.mirrorVideoEle(this.activeSpeakerVideoDom,!1))},this.isSelfVideo=e=>{const{nodeId:t}=this._config;return(0,bt.XF)(e)===(0,bt.XF)(t)},this.handleWMSCErrorMsg=e=>{if(this._config.probe)return;const{type:t}=e;switch(t){case"WEBRTC_VIDEO_HEALTH_CHECK_FAILED":this._tryFailover(_i.WMSC_VIDEO_FAIL);break;case"PC_RECONNECT":(0,Xt.iK)(Ht.ZSj,e)}},this.destroy=()=>{var e;clearTimeout(this._onWSSOpenTimer),clearTimeout(this._keepAliveTimer),this._cleanUserEventListener&&this._cleanUserEventListener(),this.selfVideoDomMap.clear(),null===(e=this._wmsc)||void 0===e||e.destroy(),this._wmsc=null,this.isJoinRWGSuccess=!1,this._isDestroyed=!0,this._disconnect(Si.destroy)},this._isDestroyed=!1,this._config=Object.assign(this._config,e),this._createWSS(),this._config.probe||(this._throttlePlayAllVideoTag=Mi()(this.playAllVideoTag,500),this._cleanUserEventListener=(0,bt.zV)((()=>this._throttlePlayAllVideoTag(gi.userClick))),document.addEventListener("visibilitychange",(()=>{"visible"===document.visibilityState&&this._throttlePlayAllVideoTag(gi.visibilitychange)})))}sendMesssageToRWG(e){var t;this._websocket&&this._websocket.readyState===WebSocket.OPEN?"object"==typeof e?this._websocket.send(JSON.stringify(e)):this._websocket.send(e):vi.Ay.error("WMSC_Wsss_Message_Status_Error: ".concat(null===(t=this._websocket)||void 0===t?void 0:t.readyState,", msg: ").concat(e))}enableVideoObserver(e,t){var i;null===(i=this._wmsc)||void 0===i||i.enableVideoObserver(e,t)}reportWMSCPeerConnectionRawStats(){var e;null===(e=this._wmsc)||void 0===e||e.reportWMSCPeerConnectionRawStats()}addSelfVideoDom(e,t){this.selfVideoDomMap.set(e,t),this.mirrorVideoEle(t,this.isMirror),this.playSelfVideo(gi.addRenderVideo,t)}removeSelfVideoDom(e){this.selfVideoDomMap.delete(e)}updateSelfVideoStream(e,t){this.selfVideoDomMap.forEach((i=>{i.srcObject=t,this.playSelfVideo(e,i)}))}publishVideoStream(e){return Ii(this,void 0,void 0,(function*(){const{mediaStreamController:t}=this._config,i=t.getProcessedVideoStream();this.streamId=i.id,this._selfStream=i,this._updateActiveSpeakerStream(),this._monitorSourceVideo(i);const s=[{stream:t.getVideoStream(),constraints:e}];t.isVideoStreamProcessed()&&s.push({stream:i}),yield this.sendMessageToWMSCAsync({type:F.VIDEO_STREAMS,data:s})}))}unpublishVideoStream(){return Ii(this,void 0,void 0,(function*(){this._selfStream=null,this._sourceVideoDom&&(this._sourceVideoDom.srcObject=null),yield this.sendMessageToWMSCAsync({type:F.VIDEO_STREAMS,data:[]})}))}_monitorSourceVideo(e){if(this._sourceVideoDom)return void(this._sourceVideoDom.srcObject=e||null);const t=_t.A.createVideoElement();t.autoplay=!1,t.muted=!0,t.playsInline=!0,t.style.display="none",t.srcObject=e||null,t.onresize=()=>{const{videoWidth:e,videoHeight:i}=t;this._maybeUpdateVideoSourceSettings(e,i)},this._sourceVideoDom=t}_maybeUpdateVideoSourceSettings(e,t){const{width:i,height:s}=this._sourceVideoSettings||{};i===e&&s===t||i===t&&s===e||(this._sourceVideoSettings=Object.assign(Object.assign({},this._sourceVideoSettings),{width:e,height:t}),this.wmscAddMonitorLog("WMSC_Update_V_Settings: ".concat(e,"|").concat(t)),this.sendMessageToWMSC({type:F.UPDATE_VIDEO_SOURCE_SETTINGS,data:{settings:this._sourceVideoSettings}}))}_updateVideoConstraints(e){return Ii(this,void 0,void 0,(function*(){const{width:t,height:i,frameRate:s}=e,{mediaStreamController:a}=this._config;a&&!this._isDestroyed&&t&&i&&s?a.changeVideoResolution(t,i,s,!0).then((()=>{this.sendMessageToWMSC({type:F.UPDATE_VIDEO_SOURCE_SETTINGS,data:{constraints:e}}),fi.A.add_monitor("WMSC_Update_V_Constraints_S: ".concat(t,"|").concat(i,"|").concat(s))})).catch((e=>{this.wmscAddMonitorLog("WMSC_Update_V_Constraints_E: ".concat(t,"|").concat(i,"|").concat(s,",").concat(null==e?void 0:e.name,":").concat(null==e?void 0:e.message)),vi.Ay.error("WMSC_Update_V_Constraints_E",e)})):this.wmscAddMonitorLog("WMSC_Update_V_Constraints_F: ".concat(!!a,"|").concat(this._isDestroyed,"|").concat(t,"|").concat(i,"|").concat(s))}))}_isSelfActiveSpeaker(){const{nodeId:e}=this._config;return(0,bt.XF)(this._activeSpeakerSsrc)===(0,bt.XF)(e)}set vbSettingVideoDom(e){this._vbSettingVideoDom=e,this._vbSettingVideoDom&&(this._vbSettingVideoDom.setAttribute("autoplay","true"),this._vbSettingVideoDom.setAttribute("playsinline","true"),this._vbSettingVideoDom.muted=!0,this.isMirror&&this.mirrorVideoEle(this._vbSettingVideoDom,this.isMirror),this._selfStream&&(this._vbSettingVideoDom.srcObject=this._selfStream))}get vbSettingVideoDom(){return this._vbSettingVideoDom}setActiveSpeakerVideoDom(e){this.activeSpeakerVideoDom=e,this.activeSpeakerVideoDom&&this._updateActiveSpeakerStream()}getWMSCAudio(){var e;return null===(e=this._wmsc)||void 0===e?void 0:e.getWmscAudio()}getStats(){var e;return null===(e=this._wmsc)||void 0===e?void 0:e.getStats()}isDestroyed(){return this._isDestroyed}}},7007:e=>{"use strict";var t,i="object"==typeof Reflect?Reflect:null,s=i&&"function"==typeof i.apply?i.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)};t=i&&"function"==typeof i.ownKeys?i.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var a=Number.isNaN||function(e){return e!=e};function n(){n.init.call(this)}e.exports=n,e.exports.once=function(e,t){return new Promise((function(i,s){function a(i){e.removeListener(t,n),s(i)}function n(){"function"==typeof e.removeListener&&e.removeListener("error",a),i([].slice.call(arguments))}g(e,t,n,{once:!0}),"error"!==t&&function(e,t){"function"==typeof e.on&&g(e,"error",t,{once:!0})}(e,a)}))},n.EventEmitter=n,n.prototype._events=void 0,n.prototype._eventsCount=0,n.prototype._maxListeners=void 0;var o=10;function r(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function c(e){return void 0===e._maxListeners?n.defaultMaxListeners:e._maxListeners}function d(e,t,i,s){var a,n,o,d;if(r(i),void 0===(n=e._events)?(n=e._events=Object.create(null),e._eventsCount=0):(void 0!==n.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),n=e._events),o=n[t]),void 0===o)o=n[t]=i,++e._eventsCount;else if("function"==typeof o?o=n[t]=s?[i,o]:[o,i]:s?o.unshift(i):o.push(i),(a=c(e))>0&&o.length>a&&!o.warned){o.warned=!0;var h=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");h.name="MaxListenersExceededWarning",h.emitter=e,h.type=t,h.count=o.length,d=h,console&&console.warn&&console.warn(d)}return e}function h(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function l(e,t,i){var s={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},a=h.bind(s);return a.listener=i,s.wrapFn=a,a}function u(e,t,i){var s=e._events;if(void 0===s)return[];var a=s[t];return void 0===a?[]:"function"==typeof a?i?[a.listener||a]:[a]:i?function(e){for(var t=new Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(a):p(a,a.length)}function m(e){var t=this._events;if(void 0!==t){var i=t[e];if("function"==typeof i)return 1;if(void 0!==i)return i.length}return 0}function p(e,t){for(var i=new Array(t),s=0;s<t;++s)i[s]=e[s];return i}function g(e,t,i,s){if("function"==typeof e.on)s.once?e.once(t,i):e.on(t,i);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function a(n){s.once&&e.removeEventListener(t,a),i(n)}))}}Object.defineProperty(n,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(e){if("number"!=typeof e||e<0||a(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");o=e}}),n.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},n.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||a(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},n.prototype.getMaxListeners=function(){return c(this)},n.prototype.emit=function(e){for(var t=[],i=1;i<arguments.length;i++)t.push(arguments[i]);var a="error"===e,n=this._events;if(void 0!==n)a=a&&void 0===n.error;else if(!a)return!1;if(a){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var r=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw r.context=o,r}var c=n[e];if(void 0===c)return!1;if("function"==typeof c)s(c,this,t);else{var d=c.length,h=p(c,d);for(i=0;i<d;++i)s(h[i],this,t)}return!0},n.prototype.addListener=function(e,t){return d(this,e,t,!1)},n.prototype.on=n.prototype.addListener,n.prototype.prependListener=function(e,t){return d(this,e,t,!0)},n.prototype.once=function(e,t){return r(t),this.on(e,l(this,e,t)),this},n.prototype.prependOnceListener=function(e,t){return r(t),this.prependListener(e,l(this,e,t)),this},n.prototype.removeListener=function(e,t){var i,s,a,n,o;if(r(t),void 0===(s=this._events))return this;if(void 0===(i=s[e]))return this;if(i===t||i.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete s[e],s.removeListener&&this.emit("removeListener",e,i.listener||t));else if("function"!=typeof i){for(a=-1,n=i.length-1;n>=0;n--)if(i[n]===t||i[n].listener===t){o=i[n].listener,a=n;break}if(a<0)return this;0===a?i.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(i,a),1===i.length&&(s[e]=i[0]),void 0!==s.removeListener&&this.emit("removeListener",e,o||t)}return this},n.prototype.off=n.prototype.removeListener,n.prototype.removeAllListeners=function(e){var t,i,s;if(void 0===(i=this._events))return this;if(void 0===i.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==i[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete i[e]),this;if(0===arguments.length){var a,n=Object.keys(i);for(s=0;s<n.length;++s)"removeListener"!==(a=n[s])&&this.removeAllListeners(a);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=i[e]))this.removeListener(e,t);else if(void 0!==t)for(s=t.length-1;s>=0;s--)this.removeListener(e,t[s]);return this},n.prototype.listeners=function(e){return u(this,e,!0)},n.prototype.rawListeners=function(e){return u(this,e,!1)},n.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):m.call(e,t)},n.prototype.listenerCount=m,n.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]}},8048:(e,t,i)=>{e.exports=i(6083)},3148:(e,t,i)=>{"use strict";var s=i(8280),a=i(1310),n=String.prototype;e.exports=function(e){var t=e.trimStart;return"string"==typeof e||e===n||s(n,e)&&t===n.trimStart?a:t}},1310:(e,t,i)=>{"use strict";i(1454);var s=i(1747);e.exports=s("String","trimLeft")},9419:(e,t,i)=>{"use strict";var s=i(5993).start,a=i(5819);e.exports=a("trimStart")?function(){return s(this)}:"".trimStart},9793:(e,t,i)=>{"use strict";var s=i(1091),a=i(9419);s({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==a},{trimLeft:a})},1454:(e,t,i)=>{"use strict";i(9793);var s=i(1091),a=i(9419);s({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==a},{trimStart:a})},6083:(e,t,i)=>{"use strict";var s=i(3148);e.exports=s}}]);
2
+ //# sourceMappingURL=https://d1cdksi819e9z7.cloudfront.net/sourcemap/wmsc.min.js-e3e45833592c9385ddff.map