import"webrtc-adapter/out/adapter";function e(e,t,i,s,n){var a={};return Object.keys(s).forEach((function(e){a[e]=s[e]})),a.enumerable=!!a.enumerable,a.configurable=!!a.configurable,("value"in a||a.initializer)&&(a.writable=!0),a=i.slice().reverse().reduce((function(i,s){return s(e,t,i)||i}),a),n&&void 0!==a.initializer&&(a.value=a.initializer?a.initializer.call(n):void 0,a.initializer=void 0),void 0===a.initializer&&(Object.defineProperty(e,t,a),a=null),a}let t=(new Date).getTime(),i=0;const s=function(){return(new Date).getTime()+i},n=function(){const e=new Date;return e.setTime(s()),e.toLocaleString()},a="canvas",o="audio",r="video",d="screen",c="small",l="big",h="auxiliary",u="aux",_="smallVideo",m="user",p="environment",g="mute",S="unmute",f="ended",v="playing",I="pause",y="error",T="loadeddata",b="audioinput",E="videoinput",w="detail",k="text",R="main",A="backup",C="banned",D="kick",N="user_time_out",P="room_disband",M="sei-message",L="PLAYING",O="PAUSED",V="STOPPED",U="inactive",x="sendonly",$="recvonly",F="add",B="remove",H="replace",j="track",J="wss://trtc.rtc.qq.com",W="wss://webrtc.qq.com",G="qcloud",z="trtc",q="webrtc";let K="";const Q="jssdk_log",X="jssdk_event",Y="jssdk_new_endreport",Z=e=>K=e,ee=1,te=2,ie=20,se=21,ne="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",ae="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",oe=2,re=R,de=h,ce="DISCONNECTED",le="CONNECTING",he="RECONNECTING",ue="CONNECTED",_e="new",me="connecting",pe="failed",ge="closed",Se="disconnected",fe="connected",ve="completed",Ie="join",ye="delta-join",Te="rejoin",be="leave",Ee="delta-leave",we="publish",ke="delta-publish",Re="unpublish",Ae="subscribe",Ce="unsubscribe",De="uplink-connection",Ne="uplink-reconnection",Pe="downlink-connection",Me="downlink-reconnection",Le="setLocalDescription",Oe="setRemoteDescription",Ve="iceConnectionState",Ue="stream-initialize",xe="websocketConnectionState",$e="websocketReconnectionState",Fe="update-stream",Be="recover-subscription",He="start-mix-transcode",je="stop-mix-transcode",Je="player-error",We="schedule",Ge="unsubscribe",ze="subscribe_change",qe={MANUAL:"manual",PRESET_LAYOUT:"preset-layout"},Ke={REMOTE:"$PLACE_HOLDER_REMOTE$"},Qe={IT_AUDIO_VIDEO:0,IT_PICTURE:2,IT_CANVAS:3,IT_PURE_AUDIO:4,IT_PURE_VIDEO:5},Xe="string",Ye="number",Ze="boolean",et="array",tt="object",it={ADD:F,REMOVE:B},st={unknown:0,wifi:1,"4g":2,"3g":3,"2g":4,wired:5},nt=-1,at=0,ot=1,rt=l,dt=c,ct="schedule.cloud-rtc.com",lt="schedule.rtc.qcloud.com",ht="schedule.rtc.tencentcloud.com",ut="schedule-ecdn.rtc.tencentcloud.com";let _t="";const mt=e=>_t=e,pt="TRTC",gt="Client",St="LocalStream",ft="RemoteStream",vt="Stream",It="web.sdk.qcloud.com",yt="web.sdk.tencent.cn",Tt="web.sdk.cloud.tencent.cn",bt=`https://${It}/trtc/webrtc/doc`,Et=`${bt}/zh-cn/`,wt={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,NONE:5},kt=1,Rt=2,At=1,Ct=2,Dt=Object.keys(wt),Nt=["normal leave","timeout leave","kick","role change"],Pt="ric",Mt="Resolution reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386",Lt={"TRTC.checkSystemRequirements":40001,"TRTC.isScreenShareSupported":40002,"TRTC.isSmallStreamSupported":40003,"TRTC.createClient.rtc":40004,"TRTC.createClient.live":40005,"TRTC.createClient.intRoomId":40006,"TRTC.createClient.stringRoomId":40007,"TRTC.createClient.autoSubscribe":40008,"TRTC.createClient.manualSubscribe":40009,"TRTC.enableUploadLog":40010,"TRTC.disableUploadLog":40011,"Client.publish":40012,"Client.publish.isAuxiliary":40013,"Client.switchRole":40014,"Client.startPublishCDNStream":40015,"Client.stopPublishCDNStream":40016,"Client.startMixTranscode":40017,"Client.stopMixTranscode":40018,"Client.enableAudioVolumeEvaluation":40019,"Client.enableSmallStream":40020,"Client.disableSmallStream":40021,"Client.setSmallStreamProfile":40022,"Client.setRemoteVideoStreamType":40023,"Client.sendSEIMessage":40024,"Client.setProxyServer":40025,"Client.setTurnServer":40026,"LocalStream.setAudioProfile.standard":40027,"LocalStream.setAudioProfile.high":40028,"LocalStream.setAudioProfile.standard-stereo":40029,"LocalStream.setAudioProfile.high-stereo":40030,"LocalStream.setVideoProfile.120p":40031,"LocalStream.setVideoProfile.120p_2":40032,"LocalStream.setVideoProfile.180p":40033,"LocalStream.setVideoProfile.180p_2":40034,"LocalStream.setVideoProfile.240p":40035,"LocalStream.setVideoProfile.240p_2":40036,"LocalStream.setVideoProfile.360p":40037,"LocalStream.setVideoProfile.360p_2":40038,"LocalStream.setVideoProfile.480p":40039,"LocalStream.setVideoProfile.480p_2":40040,"LocalStream.setVideoProfile.720p":40041,"LocalStream.setVideoProfile.1080p":40042,"LocalStream.setVideoProfile.1440p":40043,"LocalStream.setVideoProfile.4K":40044,"LocalStream.setScreenProfile.480p":40045,"LocalStream.setScreenProfile.480p_2":40046,"LocalStream.setScreenProfile.720p":40047,"LocalStream.setScreenProfile.720p_2":40048,"LocalStream.setScreenProfile.1080p":40049,"LocalStream.setScreenProfile.1080p_2":40050,"LocalStream.setVideoContentHint.motion":40051,"LocalStream.setVideoContentHint.detail":40052,"LocalStream.setVideoContentHint.text":40053,"LocalStream.setAudioCaptureVolume":40054,"LocalStream.getVideoFrame":40055,"RemoteStream.setAudioOutput":40056,"RemoteStream.getVideoFrame":40057,AI_DENOISER:1700,SPATIAL_AUDIO:1701,"2K_4K":1704},Ot=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId"],Vt="AVOID_REPEATED_CALL",Ut="INVALID_PARAMETER_REQUIRED",xt="INVALID_PARAMETER_TYPE",$t="INVALID_PARAMETER_EMPTY",Ft="INVALID_PARAMETER_INSTANCE",Bt="INVALID_PARAMETER_RANGE",Ht="API_CALL_TIMEOUT",jt="SIGNAL_CHANNEL_RECONNECTION_FAILED",Jt="SIGNAL_CHANNEL_SETUP_FAILED",Wt="ERROR_MESSAGE",Gt="EXCHANGE_SDP_TIMEOUT",zt="DOWNLINK_RECONNECTION_FAILED",qt="EXCHANGE_SDP_FAILED",Kt="UPLINK_RECONNECTION_FAILED",Qt="INVALID_PURE_AUDIO",Xt="INVALID_STREAMID",Yt="INVALID_USER_DEFINE_RECORDID",Zt="INVALID_USER_DEFINE_PUSH_ARGS",ei="INVALID_PROXY",ti="INVALID_JOIN",ii="INVALID_ROOMID_STRING",si="INVALID_ROOMID_INTEGER",ni="JOIN_ROOM_TIMEOUT",ai="JOIN_ROOM_FAILED",oi="REJOIN_ROOM_FAILED",ri="INVALID_DESTROY",di="INVALID_PUBLISH",ci="INVALID_UNPUBLISH",li="INVALID_AUDIENCE",hi="INVALID_INITIALIZE",ui="INVALID_DUPLICATE_PUBLISHING",_i="INVALID_REMOTE_STREAM",mi="SUBSCRIBE_FAILED",pi="INVALID_ROLE",gi="INVALID_OPERATION_SWITCH_ROLE",Si="SWITCH_ROLE_TIMEOUT",fi="SWITCH_ROLE_FAILED",vi="CLIENT_BANNED",Ii="INVALID_OPERATION_START_PUBLISH_CDN",yi="INVALID_OPERATION_STOP_PUBLISH_CDN",Ti="INVALID_STREAM_ID",bi="START_PUBLISH_CDN_FAILED",Ei="STOP_PUBLISH_CDN_FAILED",wi="START_MIX_TRANSCODE",ki="STOP_MIX_TRANSCODE",Ri="INVALID_AUDIO_VOLUME",Ai="ENABLE_SMALL_STREAM_PUBLISHED",Ci="DISABLE_SMALL_STREAM_PUBLISHED",Di="NOT_SUPPORTED_SMALL_STREAM",Ni="INVALID_SMALL_STREAM_PROFILE",Pi="INVALID_PARAMETER_REMOTE_STREAM",Mi="INVALID_SWITCH_DEVICE",Li="INVALID_SWITCH_DEVICE_PUBLISHING",Oi="INVALID_REPLACE_TRACK",Vi="INVALID_INITIALIZE_LOCAL_STREAM",Ui="INVALID_ADD_TRACK_REPETITIVE",xi="INVALID_ADD_TRACK_REMOVING",$i="INVALID_ADD_TRACK_PUBLISHING",Fi="INVALID_STREAM_INITIALIZED",Bi="INVALID_ADD_TRACK_NUMBER",Hi="INVALID_REMOVE_AUDIO_TRACK",ji="INVALID_REMOVE_AUDIO_ADDING",Ji="INVALID_REMOVE_AUDIO_ON",Wi="INVALID_REMOVE_TRACK_PUBLISHING",Gi="INVALID_REMOVE_TRACK_NOT_PUBLISHING",zi="INVALID_REMOVE_TRACK_NUMBER",qi="INVALID_REPLACE_TRACK_NO_TRACK",Ki="REPEAT_JOIN",Qi="CLIENT_DESTROYED",Xi="START_MIX_TRANSCODE_FAILED",Yi="STOP_MIX_TRANSCODE_FAILED",Zi="MIX_TRANSCODE_NOT_STARTED",es="CANNOT_LESS_THAN_ZERO",ts="MIX_PARAMS_VIDEO_FRAMERATE",is="MIX_PARAMS_VIDEO_GOP",ss="MIX_PARAMS_AUDIO_BITRATE",ns="MIX_PARAMS_USER_Z_ORDER",as="MIX_PARAMS_NOT_SELF",os="MIX_PARAMS_USER_STREAM",rs="INVALID_ELEMENT_ID",ds="INVALID_ELEMENT_ID_TYPE",cs="PLAY_FAILED",ls="INVALID_CREATE_STREAM_SOURCE",hs="INVALID_CREATE_STREAM_SCREEN",us="INVALID_CREATE_STREAM_AUDIO",_s="INVALID_CREATE_STREAM_SCREEN_AUDIO",ms="NOT_SUPPORTED_HTTP",ps="NOT_SUPPORTED_WEBRTC",gs="NOT_SUPPORTED_PROFILE",Ss="NOT_SUPPORTED_H264ENCODE",fs="NOT_SUPPORTED_H264DECODE",vs="NOT_SUPPORTED_TRACK",Is="NOT_SUPPORTED_SWITCH_DEVICE",ys="NOT_SUPPORTED_CAPTURE",Ts="NOT_SUPPORTED_AUX",bs="MICROPHONE_NOT_FOUND",Es="CAMERA_NOT_FOUND",ws="SIGNAL_RESPONSE_FAILED",ks="CATCH_HANDLER_ERROR",Rs="API_NOT_EXIST",As="CONNECTION_CLOSED",Cs="SUBSCRIBE_ALL_FALSE",Ds="SEI_NOT_SUPPORT",Ns="SEI_DISABLED",Ps="SEI_EMPTY",Ms="SEI_OVERSIZE",Ls="SEI_BEFORE_PUBLISH",Os="SEI_NOT_VIDEO",Vs="CALL_FREQUENCY_LIMIT",Us="CONNECTION_ABORTED",xs="API_CALL_ABORTED",$s="DUPLICATE_AUX",Fs={AVOID_REPEATED_CALL:e=>`previous ${e.name}() is ongoing, please avoid repeated calls.`,INVALID_PARAMETER_REQUIRED:({key:e,rule:t,fnName:i,value:s})=>`'${e||t.name}' is a required param when calling ${i}(), received: ${s}.`,INVALID_PARAMETER_TYPE({key:e,rule:t,fnName:i,value:s}){const n=`${e||t.name}`;let a="";return a=Array.isArray(t.type)?t.type.join("|"):t.type,`'${n}' must be type of ${a} when calling ${i}(), received type: ${Sa(s)}.`},INVALID_PARAMETER_EMPTY:({key:e,rule:t,fnName:i,value:s})=>`'${e||t.name}' cannot be '${s}' when calling ${i}().`,INVALID_PARAMETER_INSTANCE:({key:e,rule:t,fnName:i,value:s})=>`'${`${e||t.name}`}' must be instanceof ${`${t.instanceOf.name||t.instanceOf}`} when calling ${i}(), received type: ${Sa(s)}.`,INVALID_PARAMETER_RANGE:({key:e,rule:t,fnName:i,value:s})=>`'${e||t.name}' must be one of ${t.values.join("|")} when calling ${i}(), received: ${s}.`,API_CALL_TIMEOUT:e=>`${e.commandDesc||e.command} timeout observed.`,SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED:e=>`SignalChannel setup failure: (errorCode: ${e.errorCode}, errorMsg: ${e.errorMsg} }).`,ERROR_MESSAGE(e){let t=`${e.type} failed`;return e.message&&(t=`${t}: ${e.message}.`),t},EXCHANGE_SDP_TIMEOUT:"exchange sdp timeout.",DOWNLINK_RECONNECTION_FAILED:"downlink reconnection failed, please check your network and re-join room.",EXCHANGE_SDP_FAILED:e=>`exchange sdp failed ${e.errMsg}.`,UPDATE_OFFER_TIMEOUT:"update offer timeout observed.",UPLINK_RECONNECTION_FAILED:"uplink reconnection failed, please check your network and publish again.",INVALID_RECORDID:"recordId must be an integer number.",INVALID_PURE_AUDIO:"pureAudioPushMode must be 1 or 2.",INVALID_STREAMID:"streamId must be a sting literal within 64 bytes, and not be empty.",INVALID_USER_DEFINE_RECORDID:"userDefineRecordId must be a sting literal contains (a-zA-Z),(0-9), underline and hyphen, within 64 bytes, and not be empty.",INVALID_USER_DEFINE_PUSH_ARGS:"userDefinePushArgs must be a sting literal within 256 bytes, and not be empty.",INVALID_PROXY:'proxy server url must start with "wss://".',INVALID_JOIN:"duplicate join() called.",INVALID_ROOMID_STRING:e=>`'${e}' must be validate string when useStringRoomId is true.`,INVALID_ROOMID_INTEGER:e=>`'${e}' must be an integer between [1, 4294967294] when useStringRoomId is false.`,INVALID_SIGNAL_CHANNEL:"SignalChannel is not ready yet.",JOIN_ROOM_TIMEOUT:"join room timeout.",JOIN_ROOM_FAILED:({error:e,code:t})=>`Failed to join room - ${e} code: ${t}`,REJOIN_ROOM_FAILED:e=>`reJoin room: ${e.roomId} failed, please check your network.`,INVALID_DESTROY:"please call leave() before destroy().",INVALID_PUBLISH:"please call join() before publish().",INVALID_UNPUBLISH:"stream has not been published yet.",INVALID_AUDIENCE:'no permission to publish() under live/audience, please call switchRole("anchor") firstly before publish().',INVALID_INITIALIZE:"cannot publish stream because stream is not initialized, is switching device, or has been closed.",INVALID_DUPLICATE_PUBLISHING:e=>`duplicate ${e} stream publishing, please unpublish your prev ${e} stream and then re-publish.`,INVALID_SUBSCRIBE_UNDEFINED:"stream is undefined or null.",INVALID_SUBSCRIBE_LOCAL:"stream cannot be LocalStream.",INVALID_REMOTE_STREAM:"remoteStream does not exist because it has been unpublished by remote peer.",SUBSCRIBE_FAILED:({message:e,stream:t})=>`failed to subscribe ${t.getUserId()} ${t.getType()} stream, reason: ${e}.`,INVALID_ROLE:"switchRole can only be called in live mode.",INVALID_PARAMETER_SWITCH_ROLE:"role could only be set to a value as anchor or audience.",INVALID_OPERATION_SWITCH_ROLE:"please call join() before switchRole().",SWITCH_ROLE_TIMEOUT:"switchRole timeout.",SWITCH_ROLE_FAILED:e=>`switchRole failed, errCode: ${e.code} errMsg: ${e.message}.`,CLIENT_BANNED:e=>"client was banned because of "+e.message+".",INVALID_OPERATION_START_PUBLISH_CDN:"please call startPublishCDNStream() before client join the room or after client join the room and successfully publish the local stream.",INVALID_OPERATION_STOP_PUBLISH_CDN:"please call startPublishCDNStream() before stopPublishCDNStream().",START_PUBLISH_CDN_FAILED:e=>`startPublishCDNStream failed, errMsg: ${e.message}.`,STOP_PUBLISH_CDN_FAILED:e=>`stopPublishCDNStream failed, errMsg: ${e.message}.`,INVALID_STREAM_ID:e=>`'${e}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`,START_MIX_TRANSCODE:"please call startMixTranscode() after join().",STOP_MIX_TRANSCODE:"please call stopMixTranscode() after startMixTranscode().",INVALID_AUDIO_VOLUME:"interval must be a number.",ENABLE_SMALL_STREAM_PUBLISHED:"Cannot enable small stream after localStream published.",DISABLE_SMALL_STREAM_PUBLISHED:"Cannot disable small stream after localStream published.",NOT_SUPPORTED_SMALL_STREAM:"your browser does not support opening small stream.",INVALID_SMALL_STREAM_PROFILE:"small stream profile is invalid.",INVALID_PARAMETER_REMOTE_STREAM:"remoteStream is invalid.",INVALID_OPERATION_CHANGE_SMALL:"cannot switch to the small stream without subscribing to the video of remoteStream.",REMOTE_NOT_PUBLISH_SMALL_STREAM:"remote peer does not publish small stream.",INVALID_SWITCH_DEVICE:"cannot switch device on current stream.",INVALID_SWITCH_DEVICE_PUBLISHING:"cannot switch device when publishing localStream.",INVALID_REPLACE_TRACK:"cannot replace track when publishing localStream.",INVALID_INITIALIZE_LOCAL_STREAM:"local stream has not initialized yet.",INVALID_ADD_TRACK_REPETITIVE:"previous addTrack is ongoing, please avoid repetitive execution.",INVALID_ADD_TRACK_REMOVING:"cannot add track when a track is removing.",INVALID_ADD_TRACK_PUBLISHING:"cannot add track when publishing localStream.",INVALID_STREAM_INITIALIZED:"your local stream haven't been initialized yet.",INVALID_ADD_TRACK_NUMBER:"a Stream has at most one audio track and one video track.",INVALID_REMOVE_AUDIO_TRACK:"remove audio track is not supported on your browser.",INVALID_REMOVE_AUDIO_ADDING:"cannot remove track when a track is adding.",INVALID_REMOVE_AUDIO_ON:"previous removeTrack is ongoing, please avoid repetitive execution.",INVALID_REMOVE_TRACK_PUBLISHING:"cannot remove track when publishing localStream.",INVALID_REMOVE_TRACK_NOT_PUBLISHING:"the track to be removed is not being publishing.",INVALID_REMOVE_TRACK_NUMBER:"remove the only video track is not supported, please use replaceTrack or muteVideo.",INVALID_REPLACE_TRACK_NO_TRACK:e=>`cannot replace ${e.kind} track because stream has not ${e.kind} track`,START_MIX_TRANSCODE_FAILED:e=>`startMixTranscode failed, errMsg: ${e.message}.`,STOP_MIX_TRANSCODE_FAILED:e=>`stopMixTranscode failed, errMsg: ${e.message}.`,MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO:({key:e,rule:t,fnName:i,value:s})=>`'${e||t.name}' cannot be less than 0 when calling ${i}().`,MIX_PARAMS_VIDEO_FRAMERATE:"'config.videoFramerate' should be an integer between 0 and 30, excluding 0.",MIX_PARAMS_VIDEO_GOP:"'config.videoGOP' should be an integer between 1 and 8.",MIX_PARAMS_AUDIO_BITRATE:"'config.audioBitrate' should be an integer between 32 and 192.",MIX_PARAMS_USER_Z_ORDER:e=>`'${e}' is required and must be between 1 and 15.`,MIX_PARAMS_NOT_SELF:"'config.mixUsers' must contain self.",MIX_PARAMS_USER_STREAM:"'config.videoWidth' and 'config.videoHeight' of output stream should be contain all mix stream.",INVALID_PLAY:"duplicate play() call observed, please stop() firstly.",INVALID_ELEMENT_ID:({key:e,fnName:t})=>`'${e}' is not found in the document object when calling ${t}().`,INVALID_ELEMENT_ID_TYPE:({key:e,fnName:t,type:i})=>`the element corresponding to '${e}' must be instanceof HTMLDivElement when calling ${t}(), received: ${i}.`,PLAY_FAILED:e=>`${e.media} play failed,browser exception: ${e.error.toString()}`,INVALID_USERID:"userId cannot be all spaces.",INVALID_CREATE_STREAM_SOURCE:"LocalStream must be created by createStream() with either audio/video or audioSource/videoSource, but can not be mixed with audio/video and audioSource/videoSource.",INVALID_CREATE_STREAM_SCREEN:"screen/video cannot be both true.",INVALID_CREATE_STREAM_AUDIO:"audio/screenAudio cannot be both true.",INVALID_CREATE_STREAM_SCREEN_AUDIO:"when screen is true, screenAudio can be configured.",NOT_SUPPORTED_HTTP:"http protocol does not support the ability to capture and publish streams, please use the https protocol.",NOT_SUPPORTED_WEBRTC:"your browser or environment does not support full WebRTC capabilities.",NOT_SUPPORTED_PROFILE:"your browser does not support setVideoProfile.",NOT_SUPPORTED_MEDIA:"your browser or environment does not support navigator.mediaDevices.",NOT_SUPPORTED_H264ENCODE:"your device does not support H.264 encoding.",NOT_SUPPORTED_H264DECODE:"your device does not support H.264 decoding.",NOT_SUPPORTED_TRACK:e=>`${e}Track is not supported on your browser.`,NOT_SUPPORTED_SWITCH_DEVICE:"switchDevice is not supported on your browser.",NOT_SUPPORTED_CAPTURE:"Your browser or environment does not support screen sharing, please check whether the browser version.",MICROPHONE_NOT_FOUND:"no microphone detected, please check your microphone and the configuration on TRTC.createStream.",CAMERA_NOT_FOUND:"no camera detected, please check your camera and the configuration on TRTC.createStream.",SIGNAL_RESPONSE_FAILED:e=>`${e.signalResponse} failed, response code is ${e.code} , errMsg: ${e.message}.`,CATCH_HANDLER_ERROR:({name:e,event:t})=>`an error was caught on ${e}.on('${t}', handler), please check your code on 'handler'.`,API_NOT_EXIST:({name:e})=>`experimental api ${e} does not exist.`,REPEAT_JOIN:e=>`[${e}] is calling client.join api or has already joined room, please avoid repeated join.`,CONNECTION_CLOSED:"remoteStream has been unsubscribed or unpublished by remote user.",SUBSCRIBE_ALL_FALSE:"cannot subscribe when both audio & video are false, use client.unsubscribe() instead",CLIENT_DESTROYED:({funName:e})=>`failed to call ${e}() because client was destroyed.`,SEI_NOT_SUPPORT:e=>"not support to sendSEIMessage"+(!1===e?" without using h264 codec":""),SEI_DISABLED:"SEI is disabled, to enable SEI: TRTC.createClient({ enableSEI: true })",SEI_EMPTY:"buffer cannot be empty",SEI_OVERSIZE:e=>`buffer size(${e}) is over 1000 Bytes`,SEI_BEFORE_PUBLISH:"please call sendSEIMessage() after publish() success",SEI_NOT_VIDEO:"cannot send sei when localStream has not video.",CALL_FREQUENCY_LIMIT:({isSize:e,name:t,timesInSecond:i,maxSizeInSecond:s})=>`api ${t} call ${e?"size":"times"} is over ${e?s+" bytes":i} in a second.`,CONNECTION_ABORTED:e=>"connection aborted due to: "+e,API_CALL_ABORTED(e){let t;return t=e.message.includes("REMOTE_STREAM_NOT_EXIST")?`Subscribe ${e.stream.getUserId()} ${e.stream.getType()} stream aborted, reason: remote user ${e.stream.getUserId()} unpublished stream.`:`API aborted, reason: ${e.message}`,t},DUPLICATE_AUX:"only one auxiliary stream can be published in a room.",NOT_SUPPORTED_AUX:"publish auxiliary stream is not supported on your browser."},Bs=window.navigator&&window.navigator.userAgent||"",Hs=/AppleWebKit\/([\d.]+)/i.exec(Bs);Hs&&parseFloat(Hs.pop());const js=/iPad/i.test(Bs),Js=navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&/Macintosh/.test(Bs),Ws=/iPhone/i.test(Bs)&&!js,Gs=/iPod/i.test(Bs),zs=Ws||js||Gs||Js,qs=/Android/i.test(Bs);qs&&function(){const e=Bs.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(!e)return null;const t=e[1]&&parseFloat(e[1]),i=e[2]&&parseFloat(e[2]);t&&i&&parseFloat(e[1]+"."+e[2])}();qs&&/webkit/i.test(Bs);const Ks=/Firefox/i.test(Bs),Qs=Ks&&function(){const e=Bs.match(/Firefox\/(\d+)/);return e&&e[1]?parseFloat(e[1]):null}(),Xs=/Edge\//i.test(Bs),Ys=Xs&&function(){var e=Bs.match(/Edge\/(\d+)/i);if(e&&e[1])return e[1]}(),Zs=/Edg\//i.test(Bs),en=Zs&&function(){const e=Bs.match(/Edg\/(\d+)/);return e&&e[1]?parseFloat(e[1]):null}(),tn=/SogouMobileBrowser\//i.test(Bs),sn=tn&&function(){const e=Bs.match(/SogouMobileBrowser\/(\d+)/);return e&&e[1]?parseFloat(e[1]):null}(),nn=/MetaSr\s/i.test(Bs),an=nn&&function(){const e=Bs.match(/MetaSr(\s\d+(\.\d+)+)/);return e&&e[1]?parseFloat(e[1]):null}(),on=/TBS\/\d+/i.test(Bs),rn=on&&function(){var e=Bs.match(/TBS\/(\d+)/i);if(e&&e[1])return e[1]}(),dn=/XWEB\/\d+/i.test(Bs),cn=dn&&function(){var e=Bs.match(/XWEB\/(\d+)/i);if(e&&e[1])return e[1]}();/MSIE\s8\.0/.test(Bs);/MSIE\/\d+/i.test(Bs)&&function(){const e=/MSIE\s(\d+)\.\d/.exec(Bs);let t=e&&parseFloat(e[1]);!t&&/Trident\/7.0/i.test(Bs)&&/rv:11.0/.test(Bs)&&(t=11)}();const ln=/(micromessenger|webbrowser)/i.test(Bs),hn=ln&&function(){var e=Bs.match(/MicroMessenger\/(\d+)/i);if(e&&e[1])return e[1]}(),un=!on&&/MQQBrowser\/\d+/i.test(Bs)&&/COVC\/\d+/i.test(Bs),_n=!on&&/MQQBrowser\/\d+/i.test(Bs)&&!/COVC\/\d+/i.test(Bs),mn=(_n||un)&&function(){const e=Bs.match(/ MQQBrowser\/([\d.]+)/);return e&&e[1]?e[1]:null}(),pn=!on&&/ QQBrowser\/\d+/i.test(Bs),gn=pn&&function(){const e=Bs.match(/ QQBrowser\/([\d.]+)/);return e&&e[1]?e[1]:null}(),Sn=!on&&/QQBrowserLite\/\d+/i.test(Bs),fn=Sn&&function(){const e=Bs.match(/QQBrowserLite\/([\d.]+)/);return e&&e[1]?e[1]:null}(),vn=!on&&/MQBHD\/\d+/i.test(Bs),In=vn&&function(){const e=Bs.match(/MQBHD\/([\d.]+)/);return e&&e[1]?e[1]:null}(),yn=/Windows/i.test(Bs),Tn=!zs&&/MAC OS X/i.test(Bs),bn=!qs&&/Linux/i.test(Bs);/MicroMessenger/i.test(Bs);const En=/UCBrowser/i.test(Bs);/Electron/i.test(Bs);const wn=/MiuiBrowser/i.test(Bs),kn=wn&&function(){const e=Bs.match(/MiuiBrowser\/([\d.]+)/);return e&&e[1]?e[1]:null}(),Rn=/HuaweiBrowser/i.test(Bs),An=/Huawei/i.test(Bs),Cn=Rn&&function(){const e=Bs.match(/HuaweiBrowser\/([\d.]+)/);return e&&e[1]?e[1]:null}(),Dn=/SamsungBrowser/i.test(Bs),Nn=Dn&&function(){const e=Bs.match(/SamsungBrowser\/([\d.]+)/);return e&&e[1]?e[1]:null}(),Pn=/HeyTapBrowser/i.test(Bs),Mn=Pn&&function(){const e=Bs.match(/HeyTapBrowser\/([\d.]+)/);return e&&e[1]?e[1]:null}(),Ln=/VivoBrowser/i.test(Bs),On=Ln&&function(){const e=Bs.match(/VivoBrowser\/([\d.]+)/);return e&&e[1]?e[1]:null}(),Vn=()=>{const e=Bs.match(/Chrome\/(\d+)/);return e&&e[1]?Number(e[1]):null},Un=/Chrome/i.test(Bs),xn=!Xs&&!nn&&!tn&&!on&&!dn&&!Zs&&!pn&&!wn&&!Rn&&!Dn&&!Pn&&!Ln&&/Chrome/i.test(Bs),$n=xn&&Vn(),Fn=xn&&function(){const e=Bs.match(/Chrome\/([\d.]+)/);return e&&e[1]?e[1]:null}(),Bn=!Un&&!_n&&!un&&!Sn&&!vn&&/Safari/i.test(Bs),Hn=function(){if(Bn){const e=Bs.match(/Version\/([\d.]+)/);if(e&&e[1])return e[1]}return""}(),jn=/Android.*(wv|.0.0.0)/.test(Bs),Jn=(()=>{if(Js)return Hn;if(zs){const e=Bs.match(/OS (\d+)_(\d+)/i);if(e&&e[1]){let t=e[1];return e[2]&&(t+=`.${e[2]}`),t}}return""})(),Wn=Number(Jn.split(".")[0]),Gn="15.1"===Hn,zn="15.1"===Jn,qn=(()=>{const e=Number(Jn.split(".")[0]);return 14===e||13===e})(),Kn="file:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname,Qn=(()=>{let e;return()=>{if(la(e))try{e=window.localStorage}catch(t){Oo.warn(t),e=!1}return e}})(),Xn=new Map([[Ks,["Firefox",Qs]],[Zs,["Edg",en]],[xn,["Chrome",Fn]],[Bn,["Safari",Hn]],[on,["TBS",rn]],[dn,["XWEB",cn]],[ln&&Ws,["WeChat",hn]],[pn,["QQ(Win)",gn]],[_n,["QQ(Mobile)",mn]],[un,["QQ(Mobile X5)",mn]],[Sn,["QQ(Mac)",fn]],[vn,["QQ(iPad)",In]],[wn,["MI",kn]],[Rn,["HW",Cn]],[Dn,["Samsung",Nn]],[Pn,["OPPO",Mn]],[Ln,["VIVO",On]],[Xs,["EDGE",Ys]],[tn,["SogouMobile",sn]],[nn,["Sogou",an]]]);function Yn(){let e="unknown",t="unknown";return Xn.get(!0)&&(e=Xn.get(!0)[0],t=Xn.get(!0)[1]),{name:e,version:t}}const Zn=(e,t)=>t?bt+"/"+e+"/"+t:bt+"/"+e+"/index.html",ea=()=>{if(!Qn())return!1;const e=localStorage.getItem("trtc_error_assistance");e&&!(e=>{const t=e.saveTime&&(new Date).getTime()-e.saveTime>=6048e5,i=!e.saveVersion||"4.15.19"!==e.saveVersion;return t||i})(JSON.parse(e))||(Oo.info("init debug info"),(()=>{const e=new XMLHttpRequest;if(e.open("GET","https://web.sdk.qcloud.com/trtc/webrtc/download/error-message/0.0.3/script.js",!1),e.send(null),4===e.readyState&&200===e.status){const t=document.createElement("script");t.type="text/javascript",t.text=e.responseText,document.body.appendChild(t),localStorage.setItem("trtc_error_assistance",JSON.stringify({message:e.responseText,saveTime:(new Date).getTime(),saveVersion:"4.15.19"})),document.body.removeChild(t)}})())};function ta(e){const{key:t,data:i,link:s,addDocLink:n=!0}=e;let a="",o="",r="";ca(Fs[t])?a=Fs[t](i):ha(Fs[t])&&(a=Fs[t]);const{TRTC_ERROR_INFO:d,TRTC_ERROR_LINK:c}=(()=>{if(window.TRTC_ERROR_INFO&&window.TRTC_ERROR_LINK)return{TRTC_ERROR_INFO:window.TRTC_ERROR_INFO,TRTC_ERROR_LINK:window.TRTC_ERROR_LINK};{let e=localStorage.getItem("trtc_error_assistance");if(e){e=JSON.parse(e);const t=document.createElement("script");t.type="text/javascript",t.text=e.message,document.body.appendChild(t);const i=window.TRTC_ERROR_INFO,s=window.TRTC_ERROR_LINK;return document.body.removeChild(t),{TRTC_ERROR_INFO:i,TRTC_ERROR_LINK:s}}}return{}})();s?r=`${s.className}.html#${s.fnName}`:c&&c[t]&&(ca(c[t])?r=c[t](i):ha(c[t])&&(r=c[t]));let l=a;return ya()&&(d&&d[t]&&(ca(d[t])?o=d[t](i):ha(d[t])&&(o=d[t])),o&&(l=n?o+"\n请查看文档: "+Zn("zh-cn",r)+"\n\n":o+"\n\n",l+=a)),n&&(l+=" \nRefer to: "+Zn("en",r)+"\n"),l}const ia=function(){return function(e){const t=window.location.search.match(new RegExp("(\\?|&)"+e+"=([^&]*)(&|$)"));return t?decodeURIComponent(t[2]):""}("trtc_env")},sa=e=>(e=Number(e))>0&&e<14e8,na=function(e,t){let i;i=K?K.includes("http")?K:"https://"+K:sa(e)?"https://apisgp.my-imcloud.com":"https://yun.tim.qq.com";return`${i}/v5/AVQualityReportSvc/C2S?random=${Math.floor(Math.random()*2**31)}&sdkappid=${e}&cmdtype=${t}`};function aa(){const e=navigator.userAgent,t=navigator.connection;let i=e.match(/NetType\/\w+/)?e.match(/NetType\/\w+/)[0]:"";i=i.toLowerCase().replace("nettype/",""),"3gnet"===i&&(i="3g");const s=t&&t.type&&t.type.toLowerCase();let n=t&&t.effectiveType&&t.effectiveType.toLowerCase();"slow-2"===n&&(n="2g");let a=i||"unknown";if(s)switch(s){case"cellular":case"wimax":a=n||"unknown";break;case"wifi":a="wifi";break;case"ethernet":a="wired";break;case"none":case"other":case"unknown":a="unknown"}return a}const oa=function(e){if(!e||"object"!=typeof e||"[object Object]"!=Object.prototype.toString.call(e))return!1;var t=Object.getPrototypeOf(e);if(null===t)return!0;var i=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return"function"==typeof i&&i instanceof i&&Function.prototype.toString.call(i)===Function.prototype.toString.call(Object)};function ra(e,t=1,i=1){return e<=1?i:ra(e-1,i,t+i)}function da(e){const t=Math.round(e/2)+1;return t>6?13e3:1e3*ra(t)}const ca=e=>"function"==typeof e,la=e=>void 0===e,ha=e=>"string"==typeof e,ua=e=>"number"==typeof e,_a=e=>"boolean"==typeof e,ma=e=>"object"===Sa(e),pa=e=>"array"===Sa(e),ga=e=>Sa(e)==="MediaStreamTrack".toLowerCase();function Sa(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}function fa(e){const t={};return t.urls=`turn:${e.url}`,la(e.username)||la(e.credential)||(t.username=e.username,t.credential=e.credential,t.credentialType="password",la(e.credentialType)||(t.credentialType=e.credentialType)),t}function va(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}function Ia(e,t="big"){if(!ha(e))return 0;const i=e.split(".");return"big"===t?(Number(i[0])<<24|Number(i[1])<<16|Number(i[2])<<8|Number(i[3]))>>>0:(Number(i[3])<<24|Number(i[2])<<16|Number(i[1])<<8|Number(i[0]))>>>0}const ya=()=>{let e=navigator.language||navigator.userLanguage;return e=e.substr(0,2),"zh"===e},Ta=(()=>{let e=!1,t=document.visibilityState;return()=>{document.visibilityState!==t&&Oo.info(`visibility change: ${document.visibilityState}`),e||(document.addEventListener("visibilitychange",(()=>{Oo.info("visibility change: "+document.visibilityState),t=document.visibilityState})),e=!0)}})();window.AudioContext=window.AudioContext||window.webkitAudioContext||window.mozAudioContext;const ba=()=>new window.AudioContext,Ea=(()=>{let e;return()=>{if(e)return e;e=new window.AudioContext;return e.onstatechange=()=>{Oo.info(`gain context state: ${e.state}`),"suspended"===e.state?(e.resume(),document.addEventListener("click",e.resume)):"interrupted"===e.state?e.resume():document.removeEventListener("click",e.resume)},e}})(),wa=!!window.AudioWorkletNode,ka=(e,t)=>{const i=e.emit;return e.emit=(...s)=>{try{i.apply(e,s)}catch(n){const e=ta({key:ks,data:{name:t,event:s[0]},addDocLink:!1});Oo.warn(e+"\n\n"+n.stack)}},e},Ra=e=>+e<10?`0${e}`:e,Aa=e=>{const t=e.match(/^\d+\.\d+\.\d+/)[0];if(!t)return e;const i=t.split("."),s=Ra(i[1])+Ra(i[2]);i[1]-15>0&&(i[1]="15"),i[2]-15>0&&(i[2]="15");return i.join(".")+"."+s};function Ca(e,t){try{if(pa(e))return`[${e.map((e=>Ca(e,t))).join(",")}]`;if(!oa(e)||!pa(t))return JSON.stringify(e);const i={},s=new Set(t);return Object.keys(e).forEach((t=>{s.has(t)&&(i[t]=e[t])})),JSON.stringify(i)}catch(i){return"{}"}}function Da(e){const{url:t,body:i,method:s,timeout:n}=e;let a=new XMLHttpRequest;return new Promise(((e,o)=>{a.onload=t=>{if(a.status>=200&&a.status<300&&a.responseText.length>0)try{let t=JSON.parse(a.response);e({data:t})}catch(i){e({data:a.response})}else a.status>0&&o({code:a.status,message:`request failed, readyState:${a.readyState} status:${a.status} loaded size:${t.loaded}`})};const r=e=>{o({code:a.readyState,message:`request ${e.type}, readyState:${a.readyState} status:${a.status} loaded size:${e.loaded}`})};a.onerror=r,a.onabort=r,a.ontimeout=r,a.timeout=n||5e3,a.open(s||"POST",t,!0),a.send(i)}))}var Na="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},Pa={exports:{}};!function(e){var t=Object.prototype.hasOwnProperty,i="~";function s(){}function n(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function a(e,t,s,a,o){if("function"!=typeof s)throw new TypeError("The listener must be a function");var r=new n(s,a||e,o),d=i?i+t:t;return e._events[d]?e._events[d].fn?e._events[d]=[e._events[d],r]:e._events[d].push(r):(e._events[d]=r,e._eventsCount++),e}function o(e,t){0==--e._eventsCount?e._events=new s:delete e._events[t]}function r(){this._events=new s,this._eventsCount=0}Object.create&&(s.prototype=Object.create(null),(new s).__proto__||(i=!1)),r.prototype.eventNames=function(){var e,s,n=[];if(0===this._eventsCount)return n;for(s in e=this._events)t.call(e,s)&&n.push(i?s.slice(1):s);return Object.getOwnPropertySymbols?n.concat(Object.getOwnPropertySymbols(e)):n},r.prototype.listeners=function(e){var t=i?i+e:e,s=this._events[t];if(!s)return[];if(s.fn)return[s.fn];for(var n=0,a=s.length,o=new Array(a);n{const p=o||this;try{const t=await e.apply(p,r);0!==c&&ca(a)&&a.call(p,c),c=0,_(t)}catch(g){const e=()=>{clearTimeout(l),c=0,h=2,m(g)},a=()=>{2!==h&&c{l=-1,u(_,m)}),la(t.timeout)?1e3:t.timeout)):(e(),ca(n)&&n.call(p,g))};ca(i)?i.call(p,g,a,m,r,c):a()}};return new Promise(u)}}class Po{constructor(e){this.log=e.log,this.level=e.level,this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.forAllJoinedClients=e.forAllJoinedClients,this.uploaded=!1}}class Mo{constructor(e){this.id_=e.id,this.userId_=e.userId,this.sdkAppId_=e.sdkAppId,this.type_=e.type,this.isLocal_=!_a(e.isLocal)||e.isLocal}setUserId(e){this.userId_=e}setSdkAppId(e){this.sdkAppId_=e}log(e,t){Oo.log({log:`[${this.isLocal_?"↑":"↓"}${this.id_}] ${this.type_?this.type_+" ":""}${t}`,level:e,forAllJoinedClients:la(this.userId_),userId:this.userId_,sdkAppId:this.sdkAppId_})}info(e){this.log(wt.INFO,e)}debug(e){this.log(wt.DEBUG,e)}warn(e){this.log(wt.WARN,e)}error(e){this.log(wt.ERROR,e)}}const Lo=!(zs||qs);var Oo=new class{constructor(){this.clients_=new Set,this.queue_=[],this.timeoutId_=-1,this.logLevel_=wt.DEBUG,this.logLevelToUpload_=wt.INFO,this.enableUploadLog_=!0,this.isAbleToUpload_=!1,this.checkURLParam(),La.on(qa,(({client:e})=>{-1===this.timeoutId_&&this.startUpload(),this.clients_.add(e)})),La.on(Xa,(({client:e})=>this.clients_.delete(e))),La.on(Ka,(e=>{e&&oa(e.config)&&Dt[e.config.logLevelToUpload]&&(this.logLevelToUpload_=e.config.logLevelToUpload)})),La.on(xa,this.setIsAbleToUpload,this),La.on($a,this.setIsAbleToUpload,this)}getIsAbleToUpload(){return this.isAbleToUpload_}setIsAbleToUpload(){this.isAbleToUpload_=!0,La.off(xa,this.setIsAbleToUpload,this),La.off($a,this.setIsAbleToUpload,this)}async startUpload(){try{await this.upload()}catch(e){}this.timeoutId_=setTimeout((()=>this.startUpload()),2e3)}getLogsToUpload(){const e={map:new Map,splicedQueue:[]};if(this.queue_[0].forAllJoinedClients&&0===this.clients_.size)return e;let t=0;for(;t{if(!s.getIsJoined())return;const n=s.getUserId(),a=s.getSDKAppId();if(!t.has(`${n}-${a}`))if(t.add(`${n}-${a}`),e.map.has(n)){const{logs:t}=e.map.get(n);t.push(i)}else e.map.set(n,{userId:n,sdkAppId:a,logs:[i]})}))}else if(e.map.has(i.userId)){const{logs:t}=e.map.get(i.userId);t.push(i)}else e.map.set(i.userId,{userId:i.userId,sdkAppId:i.sdkAppId,logs:[i]})}return e.map.size>0&&(e.splicedQueue=this.queue_.splice(0,t)),e}async upload(){if(0===this.queue_.length||!this.isAbleToUpload_)return;const{map:e,splicedQueue:t}=this.getLogsToUpload();if(0===e.size)return;try{const t=[...e.values()];for(let e=0;ee.log)).join("\n")}),s),a.forEach((e=>e.uploaded=!0))}}catch(s){}const i=t.filter((e=>!e.uploaded));i.length>0&&(this.queue_=i.concat(this.queue_))}uploadLogWithRetry(e,t){return No({retryFunction:()=>Da({url:na(t,Q),body:e,timeout:5e3}),settings:{retries:3,timeout:1e3},onError:(e,t)=>{t()}})()}getPrefix(e){const t=new Date;return t.setTime(s()),String.prototype.padStart?`[${t.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")}:${t.getMilliseconds().toString().padStart(3,"0")}] <${Dt[e]}>`:`[${t.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")}:${t.getMilliseconds()}] <${Dt[e]}>`}getLogLevel(){return this.logLevel_}setLogLevel(e){la(Dt[e])||(this.logLevel_!==e&&this.info(`setLogLevel ${e}`),this.logLevel_=e)}enableUploadLog(){this.enableUploadLog_=!0}disableUploadLog(){this.enableUploadLog_=!1}log({log:e,level:t,forAllJoinedClients:i=!0,userId:s,sdkAppId:n}){if(e=`${this.getPrefix(t)} ${e}`,this.enableUploadLog_&&t>=this.logLevelToUpload_&&this.queue_.push(new Po({log:e,level:t,userId:s,sdkAppId:n,forAllJoinedClients:i})),t`;super(t+""+(n?` constraint: ${n}`:"")+(null!=t&&t.includes(a)?"":" "+a)),this.code_=i,this.extraCode_=s,this.name=e,this.message_=t,n&&(this.constraint=n)}getCode(){return this.code_}getExtraCode(){return this.extraCode_}}const Sr=32768,fr=32769,vr=32770,Ir=32771,yr=32772,Tr=32773,br=32774,Er=32775,wr=32777,kr=32778,Rr=32779,Ar=32780,Cr=32781,Dr=32782,Nr=32783,Pr=32784,Mr=32785,Lr=32786,Or=32787,Vr=32788,Ur=32789,xr=32790,$r=32791,Fr=32792,Br=32793,Hr=32794,jr=32795,Jr=32796,Wr=32797,Gr=32798,zr=32799,qr=32800,Kr=32801,Qr=32802,Xr=32803,Yr=32804,Zr=new Map,ed=function(e,t){let i=Zr.get(e);i||(Zr.set(e,[]),i=Zr.get(e)),i.push(t)};var td=Object.prototype.hasOwnProperty;function id(e){if(null==e)return!0;if("boolean"==typeof e)return!1;if("number"==typeof e)return 0===e;if("string"==typeof e)return 0===e.length;if("function"==typeof e)return 0===e.length;if(Array.isArray(e))return 0===e.length;if(e instanceof Error)return""===e.message;if(oa(e))switch(Object.prototype.toString.call(e)){case"[object File]":case"[object Map]":case"[object Set]":return 0===e.size;case"[object Object]":for(var t in e)if(td.call(e,t))return!1;return!0}return!1}var sd=new class{constructor(){const{name:e,version:t}=Yn();this.roomIdMap_=new Map,this.configs_={sdkAppId:"",userId:"",version:"4.15.19",env:G,browserVersion:e+t,ua:navigator.userAgent}}setConfig({sdkAppId:e,env:t,userId:i,roomId:s}){e!==this.configs_.sdkAppId&&(this.configs_.sdkAppId=String(e)),this.configs_.env=t,this.configs_.userId=i,this.roomIdMap_.set(i,String(s))}logEvent(e){if(Kn)return;const t={...e,...this.configs_,userId:e.userId||this.configs_.userId};la(t.code)&&(t.code="failed"===t.result?pr.UNKNOWN:0),this.sendRequest(na(this.configs_.sdkAppId,X),t)}logSuccessEvent(e){Kn||(this.logEvent({...e,result:"success",roomId:this.roomIdMap_.get(e.userId)}),this.configs_.env===G&&this.uploadEventToKibana({...e,result:"success"}))}logFailedEvent(e){if(Kn)return;const{eventType:t,code:i,error:s,userId:n}=e,a={roomId:this.roomIdMap_.get(n),userId:n,eventType:t,result:"failed",code:i||(s instanceof gr?s.getExtraCode()||s.getCode():pr.UNKNOWN)};this.logEvent(a),this.configs_.env===G&&this.uploadEventToKibana({...a,error:s})}uploadEventToKibana(e){let t=`stat-${e.eventType}-${e.result}`;"delta-join"!==e.eventType&&"delta-leave"!==e.eventType&&"delta-publish"!==e.eventType||(t=`${e.eventType}:${e.delta}`),this.uploadEvent({log:t,userId:e.userId}),"failed"===e.result&&(t=`stat-${e.eventType}-${e.result}-${e.code}`,this.uploadEvent({log:t,userId:e.userId,error:e.error}))}uploadEvent({log:e,userId:t,error:i}){const s={timestamp:n(),sdkAppId:this.configs_.sdkAppId,userId:t||this.configs_.userId,version:this.configs_.version,log:e};i&&(s.errorInfo=i.message),this.sendRequest(na(this.configs_.sdkAppId,Q),s)}sendRequest(e,t){Oo.getIsAbleToUpload()?Da({url:e,body:JSON.stringify(t)}).catch((()=>{})):setTimeout((()=>{this.sendRequest(e,t)}),1e3)}};class nd{constructor(e){this.client_=e.client,this.sdkAppId_=e.sdkAppId,this.userId_=e.userId,this.userSig_=e.userSig,this.url_=e.url,this.backupUrl_=e.backupUrl;let t=`?sdkAppId=${encodeURIComponent(this.sdkAppId_)}&userId=${encodeURIComponent(this.userId_)}&userSig=${encodeURIComponent(this.userSig_)}&roomId=${encodeURIComponent(e.roomId)}`;const i=this.client_.getSystemResult();if(i&&i.detail){const{isH264EncodeSupported:e,isVp8EncodeSupported:s,isH264DecodeSupported:n,isVp8DecodeSupported:a}=i.detail;t+=`&enc264=${Number(e)}&dec264=${Number(n)}&encVp8=${Number(s)}&decVp8=${Number(a)}`}e.signalDomainWhenUnifiedProxy&&(t+=`&signalDomain=${encodeURIComponent(e.signalDomainWhenUnifiedProxy)}`),this.urlWithParam_=`${this.url_}${t}`,this.backupUrlWithParam_=`${this.backupUrl_}${t}`,this.isConnected_=!1,this.isConnecting_=!1,this.socketInUse_=null,this.socket_=null,this.backupSocket_=null,this.backupTimer_=-1,this.signalInfo_={},this.currentState_=Ho,this.reconnectionCount_=0,this.reconnectionTimer_=-1,this.lastMessageTime_=-1,this.seq_=0,this.log_=Oo.createLogger({id:"ws|"+this.userId_,userId:this.userId_,sdkAppId:this.sdkAppId_}),this.emitter_=new Ma}get isOnline(){return this.currentState_===Wo&&Date.now()-this.lastMessageTime_<12e3}connect(){return new Promise(((e,t)=>{this.log_.info(`connect to url: ${this.urlWithParam_}`),this.emitConnectionStateChanged(jo),this.socket_=new WebSocket(this.urlWithParam_),this.bindSocket(this.socket_),this.backupTimer_=setTimeout((()=>{this.isConnected_||(this.log_.info("trying to connect to backupUrl"),this.tryConnectBackup())}),5e3);const i=setTimeout((()=>{this.close(),t(new gr({code:pr.JOIN_ROOM_FAILED,message:"join room timeout"}))}),1e4);this.once(Fo,(()=>{clearTimeout(i),e()})),this.once(Bo,(e=>{clearTimeout(i),t(e)}))}))}tryConnectBackup(){this.backupSocket_||(this.unbindAndCloseSocket(R),this.log_.debug(`try to connect to url: ${this.backupUrlWithParam_}`),this.backupSocket_=new WebSocket(this.backupUrlWithParam_),this.bindSocket(this.backupSocket_))}bindSocket(e){e.onopen=this.onopen.bind(this),e.onclose=this.onclose.bind(this),e.onerror=this.onerror.bind(this),e.onmessage=this.onmessage.bind(this)}unbindSocket(e){e.onopen=()=>{},e.onclose=()=>{},e.onerror=()=>{},e.onmessage=()=>{}}unbindAndCloseSocket(e){if(e===R){if(this.socket_){this.unbindSocket(this.socket_);try{this.socket_.close(1e3)}catch(t){}this.socket_=null}}else if(this.backupSocket_){this.unbindSocket(this.backupSocket_);try{this.backupSocket_.close(1e3)}catch(t){}this.backupSocket_=null}}clearBackupTimer(){-1!==this.backupTimer_&&(clearTimeout(this.backupTimer_),this.backupTimer_=-1)}clearReconnectionTimer(){-1!==this.reconnectionTimer_&&(clearTimeout(this.reconnectionTimer_),this.reconnectionTimer_=-1)}onopen(e){if(this.isConnected_)return;this.isConnected_=!0,this.isConnecting_=!1,this.isReconnecting_&&id(this.signalInfo_)&&this.stopReconnection(),this.clearBackupTimer(),e.target===this.socket_?(this.unbindAndCloseSocket(A),this.socketInUse_=this.socket_):(this.unbindAndCloseSocket(R),this.socketInUse_=this.backupSocket_);const t=e.target.url;this.log_.info(`websocket[${t}] is connected`),this.currentState_===jo?this.addSignalEvent($r,"signal channel is connected"):this.currentState_===Jo&&this.addSignalEvent(jr,"signal channel reconnect success"),this.emitConnectionStateChanged(Wo),this.emitter_.emit(Fo)}onclose(e){const t=e.target.url,i=e.target===this.socketInUse_;if(this.log_.info(`websocket[${t} InUse: ${i}] is closed with code: ${e.code}`),i&&(this.isConnected_=!1,this.emitConnectionStateChanged(Ho),this.addSignalEvent(xr,"signal channel is disconnected"),!e.wasClean||1e3!==e.code)){this.log_.warn(`onclose code:${e.code} reason:${e.reason}`),this.log_.warn("close current websocket and schedule a reconnect timeout"),this.socketInUse_.onclose=()=>{},this.socketInUse_.close(4011);const t=this.socketInUse_===this.socket_;this.socket_=this.backupSocket_=this.socketInUse_=null,this.reconnect(t?A:R)}}onerror(e){const t=e.target.url;if(this.log_.error(`websocket[${t}] error observed`),this.isConnected_){if(e.target===this.socketInUse_){this.isConnected_=!1,this.unbindAndCloseSocket(R),this.unbindAndCloseSocket(A);const e=this.socketInUse_===this.socket_;this.socketInUse_=null,this.reconnect(e?A:R)}}else this.isReconnecting_||sd.logFailedEvent({userId:this.client_.getUserId(),eventType:xe,code:pr.UNKNOWN}),e.target==this.socket_?(this.unbindAndCloseSocket(R),this.reconnect(A)):(this.unbindAndCloseSocket(A),this.reconnect(R));this.isConnecting_=!1,this.isConnected_=!1}onmessage(e){if(!this.isConnected_)return;this.lastMessageTime_=Date.now();const s=JSON.parse(e.data),{cmd:n,data:a}=s,o=Object.values(Go),r=Object.keys(Go)[o.indexOf(n)],d=qo[r];switch(zo.includes(n)||(this.log_.debug(`received msg: ${e.data}`),this.log_.info(`Received event: [ ${d||"unknown cmd: "+n} ]`)),n){case Go.CHANNEL_SETUP_RESULT:if(0===s.code)this.signalInfo_.clientIp=a.clientIp,this.signalInfo_.signalIp=a.signalInnerIp,this.signalInfo_.tinyId=s.tinyId,a.svrTime&&function(e){t=e,i=t-(new Date).getTime();const s=new Date;s.setTime(e),Oo.info("baseTime from server: "+s+" offset: "+i)}(a.svrTime),this.log_.info("ChannelSetup Success"),sd.logSuccessEvent({userId:this.userId_,eventType:xe}),this.emitter_.emit(Uo,{signalInfo:this.signalInfo_});else{const e=new gr({code:pr.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:s.code,message:ta({key:Jt,data:{errorCode:s.code,errorMsg:s.message}})});this.log_.error(`${s.code}, ${s.message}`),this.close(),sd.logFailedEvent({userId:this.userId_,eventType:xe,error:e}),this.emitter_.emit(xo,e)}break;case Go.JOIN_ROOM_RESULT:0===s.code&&(this.signalInfo_.relayIp=a.relayOuterIp,this.signalInfo_.relayInnerIp=a.relayInnerIp,this.signalInfo_.relayPort=a.relayPort,this.log_.info(`signalIp:${this.signalInfo_.signalIp} clientIp:${this.signalInfo_.clientIp} relayIp: ${this.signalInfo_.relayIp}`)),this.emitter_.emit(d,{data:s});break;case Go.CHANNEL_RECONNECT_RESULT:0===s.code?(this.log_.warn("reconnect success"),this.stopReconnection(),sd.logSuccessEvent({userId:this.userId_,eventType:$e}),this.client_.syncUserList(),this.client_.checkConnectionsToReconnect()):(this.log_.warn(`reconnect failed, ${s.code} ${s.message}`),this.client_.reJoin());break;default:this.emitter_.emit(d,{data:s})}}addSignalEvent(e,t){ed(this.userId_,{eventId:e,eventDesc:t,timestamp:s(),userId:this.userId_,tinyId:this.signalInfo_.tinyId})}reconnect(e=R){if(this.isConnecting_||-1!==this.reconnectionTimer_)return void this.log_.info("signal channel is reconnecting, ignoring current reconnection");if(La.emit(Ya,this.client_),this.reconnectionCount_>=30){this.log_.warn("SDK has tried reconnect signal channel for 30 times, but all failed. please check your network");const e=new gr({code:pr.SIGNAL_CHANNEL_RECONNECTION_FAILED,message:ta({key:jt})});return sd.logFailedEvent({userId:this.client_.getUserId(),eventType:$e,error:e}),this.addSignalEvent(Jr,"signal channel reconnect fail"),void this.emitter_.emit(Bo,e)}this.isConnecting_=!0,this.reconnectionCount_++,this.currentState_!==Jo&&(this.emitConnectionStateChanged(Jo),this.addSignalEvent(Hr,"signal channel is reconnecting")),this.log_.warn(`reconnecting to ${e} signal channel [${this.reconnectionCount_}/30]`);const t=this.getReconnectionUrl(e);e===R?(this.socket_=new WebSocket(t),this.bindSocket(this.socket_)):(this.backupSocket_=new WebSocket(t),this.bindSocket(this.backupSocket_));const i=da(this.reconnectionCount_);this.reconnectionTimer_=setTimeout((()=>{this.log_.warn(`reconnect ${e} signal channel timeout(${i/1e3}s), close and try again`),this.isConnecting_=!1,this.clearReconnectionTimer(),this.unbindAndCloseSocket(e),this.reconnect(e===R?A:R)}),i)}isConnected(){return this.isConnected_}get isReconnecting_(){return-1!==this.reconnectionTimer_}getReconnectionUrl(e){let t=e===R?this.urlWithParam_:this.backupUrlWithParam_;if(!id(this.signalInfo_)&&-1===t.indexOf("&rc=1")){const e=this.client_.getRoomId(),i=this.client_.getUseStringRoomId();t+=`&rc=1&relayInnerIp=${this.signalInfo_.relayInnerIp}&relayOuterIp=${this.signalInfo_.relayIp}&relayPort=${this.signalInfo_.relayPort}&roomId=${e}&useStringRoomId=${i}`}return t}send(e,t={}){if(this.isConnected_){const i={cmd:e,data:t,userId:this.userId_,tinyId:this.signalInfo_.tinyId,seq:++this.seq_};return this.socketInUse_.send(JSON.stringify(i)),i.seq}}sendWaitForResponse({command:e,data:t,timeout:i=5e3,responseCommand:s,commandDesc:n,enableLog:a=!0}){return new Promise(((o,r)=>{const d=setTimeout((()=>{this.off(s,c);const t=new gr({code:pr.API_CALL_TIMEOUT,message:ta({key:Ht,data:{commandDesc:n,command:e}})});a&&this.log_.warn(t),r(t)}),i),c=e=>{e.data.seq===l&&(clearTimeout(d),this.off(s,c),o(e))};this.on(s,c);const l=this.send(e,t)}))}sendWaitForResponseWithRetry(...e){const{commandDesc:t,command:i,retries:s=0,retryTimeout:n=0}=e[0];return No({retryFunction:this.sendWaitForResponse,onRetrying:e=>{this.log_.warn(`${t||i} timeout observed, retrying [${e}/${s}]`)},settings:{retries:s,timeout:n},context:this})(...e)}getCurrentState(){return this.currentState_}getSignalInfo(){return this.signalInfo_}stopReconnection(){this.isReconnecting_&&(this.reconnectionCount_=0,this.clearReconnectionTimer())}close(){this.log_.info("close SignalChannel"),this.clearBackupTimer(),this.stopReconnection(),this.signalInfo_={},this.isConnecting_=!1,this.isConnected_=!1,this.socketInUse_=null,this.unbindAndCloseSocket(R),this.unbindAndCloseSocket(A),this.emitConnectionStateChanged(Ho)}on(e,t,i){this.emitter_.on(e,t,i)}removeListener(e,t,i){this.emitter_.removeListener(e,t,i)}once(e,t,i){this.emitter_.once(e,t,i)}off(e,t,i){this.emitter_.off(e,t,i)}emitConnectionStateChanged(e){e!==this.currentState_&&(this.emitter_.emit($o,{prevState:this.currentState_,state:e}),this.currentState_=e)}}var ad={},od={},rd={exports:{}},dd=rd.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",t+=null!=e["network-cost"]?" network-cost %d":"%v"}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",t+=null!=e.rateNumerator?" rate=%s":"",t+=null!=e.rateDenominator?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(dd).forEach((function(e){dd[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))})),function(e){var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,s){var n=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:n&&!i[e.name]&&(i[e.name]={});var a=e.push?{}:n?i[e.name]:i;!function(e,i,s,n){if(n&&!s)i[n]=t(e[1]);else for(var a=0;a1&&(e[s[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(a,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],s=e.split(" ").map(t),n=0;n=s)return e;var n=i[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(n);case"%d":return Number(n);case"%v":return""}}))},ud=function(e,t,i){var s=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var n=0;n{e({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-t))})}),1e3)},Ed=(null===(Id=window)||void 0===Id?void 0:Id.cancelIdleCallback)||function(e){clearTimeout(e)};let wd=(null===(yd=window)||void 0===yd?void 0:yd.cancelAnimationFrame)||(null===(Td=window)||void 0===Td?void 0:Td.mozCancelAnimationFrame);class kd{static taskMap=new Map;static currentTaskID=1;static generateTaskID(){return this.currentTaskID++}static run(e="timeout",t,i){i="interval"===e?{delay:2e3,count:0,backgroundTask:!0,...i}:e===Pt?{delay:1e4,count:0,...i}:"raf"===e?{fps:60,delay:16.6,count:0,backgroundTask:!0,...i}:{delay:2e3,count:0,backgroundTask:!0,...i},ma(t)&&(i={...i,...t}),ca(e)&&(t=e,e="timeout");let s={taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:e,callback:t,...i};return this.taskMap.set(s.taskID,s),this[e](s),s.taskID}static interval(e){return e.intervalID=setInterval((()=>{e.callback(),e.loopCount+=1,this.isBreakLoop(e)}),e.delay)}static timeout(e){const t=()=>{if(e.callback(),e.loopCount+=1,!this.isBreakLoop(e))return e.timeoutID=setTimeout(t,e.delay)};return e.timeoutID=setTimeout(t,e.delay)}static ric(e){let t,i=va();const s=()=>{if(t=va()-i,t>=e.delay&&(i=va()-Math.floor(t%e.delay),e.callback(),e.loopCount+=1),!this.isBreakLoop(e))return e.ricID=bd(s,{timeout:e.delay})};return e.ricID=bd(s,{timeout:e.delay})}static raf(e){e.delay=(1e3/e.fps).toFixed(2);let t,i=va();const s=()=>{if(document.hidden&&e.backgroundTask){if(t=va()-i,i=va(),e.callback(),e.loopCount+=1,this.isBreakLoop(e))return;return e.timeoutID=setTimeout(s,e.delay-Math.floor(t%e.delay))}if(t=va()-i,t>=e.delay&&(i=va()-Math.floor(t%e.delay),e.callback(),e.loopCount+=1),!this.isBreakLoop(e))return e.rafID=requestAnimationFrame(s)};if(e.rafID=requestAnimationFrame(s),e.backgroundTask){const t=()=>{if(document.hidden){let t=va()-i;t>=e.delay?s():e.timeoutID=setTimeout(s,e.delay-t)}};document.addEventListener("visibilitychange",t),e.onVisibilitychange=t,document.hidden&&t()}return e.taskID}static hasTask(e){return this.taskMap.has(e)}static clearTask(e){if(!this.taskMap.has(e))return!0;const{intervalID:t,timeoutID:i,rafID:s,ricID:n,onVisibilitychange:a}=this.taskMap.get(e);return t&&clearInterval(t),i&&clearTimeout(i),s&&wd(s),n&&Ed(n),a&&document.removeEventListener("visibilitychange",a),this.taskMap.delete(e),!0}static isBreakLoop(e){return!this.taskMap.has(e.taskID)||0!==e.count&&e.loopCount>=e.count&&(this.clearTask(e.taskID),!0)}}var Rd=new class{constructor(){this.prefix_="TRTC",this.queue_=new Map,this.checkStorage()}getRealKey(e){return`${this.prefix_}_${e}`}checkStorage(){if(!Qn())return;Object.keys(localStorage).filter((e=>{if(e.startsWith(this.prefix_)){const t=JSON.parse(localStorage.getItem(e));if(t&&t.expiresInlocalStorage.removeItem(e)))}doFlush(){if(Qn())try{for(const[e,t]of this.queue_)localStorage.setItem(e,JSON.stringify(t))}catch(e){Oo.warn(e)}}getItem(e){if(!Qn())return null;try{const t=JSON.parse(localStorage.getItem(this.getRealKey(e)));return t&&t.expiresIn>=Date.now()?t.value:null}catch(t){Oo.warn(t)}}setItem(e,t,i=!1){if(Qn())try{const s={expiresIn:Date.now()+6048e5,value:t};i?localStorage.setItem(this.getRealKey(e),JSON.stringify(s)):(this.queue_.set(this.getRealKey(e),s),kd.hasTask(this.intervalId_)||(this.intervalId_=kd.run(Pt,this.doFlush.bind(this),{count:1})))}catch(s){Oo.warn(s)}}deleteItem(e){if(!Qn())return!1;try{return e=this.getRealKey(e),this.queue_.delete(e),localStorage.removeItem(e),!0}catch(t){return Oo.warn(t),!1}}clear(){if(Qn())try{localStorage.clear()}catch(e){Oo.warn(e)}}};let Ad={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isMediaDevicesSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}};const Cd=function(){return!En&&!Xs&&(!(Zs&&en<80)&&!(Ks&&Qs<56))},Dd=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter((e=>e in window)).length>0},Nd=async function(){if(Ad.detail.isH264EncodeSupported&&Ad.detail.isVp8EncodeSupported)return{isH264EncodeSupported:Ad.detail.isH264EncodeSupported,isVp8EncodeSupported:Ad.detail.isVp8EncodeSupported};let e="",t=!1,i=!1;try{const s=new RTCPeerConnection,n=document.createElement(a);n.getContext("2d");const o=n.captureStream(0);return s.addTrack(o.getVideoTracks()[0],o),e=await s.createOffer(),-1!==e.sdp.toLowerCase().indexOf("h264")&&(t=!0),-1!==e.sdp.toLowerCase().indexOf("vp8")&&(i=!0),s.close(),Ad.detail.isH264EncodeSupported=t,Ad.detail.isVp8EncodeSupported=i,{isH264EncodeSupported:Ad.detail.isH264EncodeSupported,isVp8EncodeSupported:Ad.detail.isVp8EncodeSupported}}catch(s){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1}}};const Pd=async function(){if(Ad.detail.isH264DecodeSupported&&Ad.detail.isVp8DecodeSupported)return{isH264DecodeSupported:Ad.detail.isH264DecodeSupported,isVp8DecodeSupported:Ad.detail.isVp8DecodeSupported};let e="",t=!1,i=!1;try{const s=new RTCPeerConnection;return e=await s.createOffer({offerToReceiveAudio:1,offerToReceiveVideo:1}),-1!==e.sdp.toLowerCase().indexOf("h264")&&(t=!0),-1!==e.sdp.toLowerCase().indexOf("vp8")&&(i=!0),s.close(),{isH264DecodeSupported:t,isVp8DecodeSupported:i}}catch(s){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1}}},Md=((e,t)=>{let i=null;return function(...s){return i||(i=e.apply(t||this,s),i.then((e=>(i=null,e))).catch((e=>{throw i=null,e})),i)}})((async function(){if(!Ld())return Ad;const e=Cd(),t=Dd(),i=function(){if(!navigator.mediaDevices)return!1;const e=["getUserMedia","enumerateDevices"];return e.filter((e=>e in navigator.mediaDevices)).length===e.length}();let{isH264EncodeSupported:s,isVp8EncodeSupported:n}=await Nd(),{isH264DecodeSupported:a,isVp8DecodeSupported:o}=await Pd();if(!s||!n){const e=await Nd();s=e.isH264EncodeSupported,n=e.isVp8EncodeSupported}if(s&&a&&(Pn||Ln||jn)&&!on&&Vn()<79){const{encode:e,decode:t}=await async function(){return new Promise((async e=>{const t={encode:!1,decode:!1};let i=null;try{const s=document.createElement("canvas"),n=s.getContext("2d");s.width=640,s.height=480;const a=setInterval((()=>{n.fillText("test",Math.floor(640*Math.random()),Math.floor(480*Math.random()))}),33);let o=-1,d=-1;i=()=>{clearInterval(o),clearInterval(a),clearTimeout(d),l.close(),h.close(),c.getTracks().forEach((e=>e.stop()))},d=setTimeout((()=>{i(),e(t)}),3e3);const c=s.captureStream(),l=new RTCPeerConnection({}),h=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});l.addEventListener("icecandidate",(e=>h.addIceCandidate(e.candidate))),h.addEventListener("icecandidate",(e=>l.addIceCandidate(e.candidate))),l.addTrack(c.getVideoTracks()[0],c);const u=await l.createOffer();await l.setLocalDescription(u),await h.setRemoteDescription(u);const _=await h.createAnswer(),m=Sd(_.sdp),p=m.media[0].rtp.findIndex((e=>"H264"===e.codec));m.media[0].rtp=[m.media[0].rtp[p]],m.media[0].fmtp=m.media[0].fmtp.filter((e=>e.payload===m.media[0].rtp[0].payload)),m.media[0].rtcpFb=m.media[0].rtcpFb.filter((e=>e.payload===m.media[0].rtp[0].payload)),_.sdp=fd(m),await h.setLocalDescription(_),await l.setRemoteDescription(_),o=setInterval((async()=>{t.encode&&t.decode&&(i(),e(t));const s=await l.getStats(),n=await h.getStats();t.encode||s.forEach((e=>{"outbound-rtp"===e.type&&e.mediaType===r&&e.framesEncoded>0&&(t.encode=!0)})),t.decode||n.forEach((e=>{"inbound-rtp"===e.type&&e.mediaType===r&&e.framesDecoded>0&&(t.decode=!0)}))}),500)}catch(s){i(),Oo.warn(s),e(t)}}))}();s=e,a=t}return Ad.result=e&&t&&i&&(s||n)&&(a||o),Ad.detail.isBrowserSupported=e,Ad.detail.isWebRTCSupported=t,Ad.detail.isMediaDevicesSupported=i,Ad.detail.isH264EncodeSupported=s,Ad.detail.isVp8EncodeSupported=n,Ad.detail.isH264DecodeSupported=a,Ad.detail.isVp8DecodeSupported=o,Ld()&&(Oo.warn(ta({key:ps})),Oo.info(`${navigator.userAgent} ${JSON.stringify(Ad.detail)}`)),Rd.setItem("checkResult",{ua:navigator.userAgent,checkResult:Ad},!0),Ad}));function Ld(){return Object.keys(Ad.detail).findIndex((e=>!Ad.detail[e]))>=0}function Od(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)}function Vd(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function Ud(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function xd(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function $d(){return"RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype}function Fd(){return"RTCRtpSender"in window&&"replaceTrack"in window.RTCRtpSender.prototype}function Bd(){return"RTCRtpSender"in window&&"setParameters"in window.RTCRtpSender.prototype&&Ud()}function Hd(){return!!la(navigator.mediaDevices)&&(Oo.error(Fs.NOT_SUPPORTED_MEDIA),!0)}function jd(){return"http:"===location.protocol&&!Kn&&(Oo.warn(ta({key:ms})),!0)}const Jd="RTCRtpSender"in window&&"createEncodedStreams"in window.RTCRtpSender.prototype&&Vn()>=86;function Wd(e){return!("candidate-pair"!==e.type||!e.nominated||"in-progress"!==e.state&&"succeeded"!==e.state)&&!(_a(e.selected)&&!e.selected)}let Gd=new Map([[qs,"Android"],[zs,"iOS"],[yn,"Windows"],[Tn,"MacOS"],[bn,"Linux"]]);function zd(){let e="unknown";return Gd.get(!0)&&(e=Gd.get(!0)),e}function qd(){let e="";if(screen.width){e+=(screen.width?screen.width*window.devicePixelRatio:"")+" * "+(screen.height?screen.height*window.devicePixelRatio:"")}return e}function Kd(){let e=!1;return(navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia)&&(e=!0),e}function Qd(){let e={isSupported:!1},t=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"];for(let i=0;i{if("outbound-rtp"===i.type){if((i.mediaType||i.kind)===r){if(!Ks&&0===i.bytesSent)return;i.ssrc!==s.video||la(i.encoderImplementation)||this.prevEncoderImplementation_===i.encoderImplementation||(this.log_.info(`encoderImplementation change to ${i.encoderImplementation}`),this.prevEncoderImplementation_=i.encoderImplementation),i.ssrc!==s.video||la(i.qualityLimitationReason)||this.prevQualityLimitationReason_===i.qualityLimitationReason||(this.log_.info(`qualityLimitationReason change to ${i.qualityLimitationReason}`),this.prevQualityLimitationReason_=i.qualityLimitationReason);let e=r;i.ssrc===s.small?e=c:i.ssrc===s.auxiliary&&(e=h),t[e].bytesSent=i.bytesSent,t[e].packetsSent=i.packetsSent,t[e].framesEncoded=i.framesEncoded}else t.audio.bytesSent=i.bytesSent,t.audio.packetsSent=i.packetsSent}else"candidate-pair"===i.type?Wd(i)&&ua(i.currentRoundTripTime)&&(t.rtt=Math.floor(1e3*i.currentRoundTripTime)):"media-source"===i.type&&(i.kind===o?(t.audio.audioLevel=i.audioLevel||0,t.audio.totalAudioEnergy=i.totalAudioEnergy||0):i.kind===r&&(i.trackIdentifier===e.getVideoTrackId(r)?t.video.fpsCapture=i.framesPerSecond:i.trackIdentifier===e.getVideoTrackId(h)?t.auxiliary.fpsCapture=i.framesPerSecond:t.small.fpsCapture=i.framesPerSecond));if(la(i.audioLevel)||(t.audio.audioLevel=i.audioLevel||0,t.audio.totalAudioEnergy=i.totalAudioEnergy||0),!la(i.frameWidth)){let n;i.trackIdentifier===e.getVideoTrackId(r)||i.ssrc===s.video?n=r:i.trackIdentifier===e.getVideoTrackId(h)||i.ssrc===s.auxiliary?n=h:i.trackIdentifier!==e.getVideoTrackId(c)&&i.ssrc!==s.small||(n=c),n&&(t[n].frameWidth=i.frameWidth,t[n].frameHeight=i.frameHeight,t[n].framesSent=i.framesSent)}})),0===t.audio.audioLevel)t.audio.audioLevel=(null===(n=e.getLocalStream())||void 0===n?void 0:n.getInternalAudioLevel())||0}catch(a){this.log_.warn("failed to getStats on sender connection "+a)}return t}async getReceiverStats(e){const t={tinyId:e.getTinyId(),userId:e.getUserId(),rtt:0,hasAudio:!1,hasVideo:!1,hasAuxiliary:!1,audio:{bytesReceived:0,packetsReceived:0,packetsLost:0,jitter:0,audioLevel:0,totalAudioEnergy:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0}},i=e.getPeerConnection();if(i)try{const n=e.getSSRC(),a=e.getTrackState();var s;if((await i.getStats()).forEach((i=>{if("inbound-rtp"===i.type){if((i.mediaType||i.kind)===o){if(i.ssrc!==n.audio||!a.audio)return;t.audio.packetsReceived=i.packetsReceived,t.audio.bytesReceived=i.bytesReceived,t.audio.packetsLost=i.packetsLost,t.audio.jitter=i.jitter,t.hasAudio=!0}else{if(Ks&&0===i.bytesReceived)return;i.ssrc===n.video&&a.video&&(t.video.packetsReceived=i.packetsReceived,t.video.bytesReceived=i.bytesReceived,t.video.packetsLost=i.packetsLost,t.video.framesReceived=i.framesReceived,t.video.framesDecoded=i.framesDecoded,t.video.fpsDecoded=i.framesPerSecond,t.hasVideo=!0,!i.decoderImplementation||this.prevDecoderImplementationMap_.has(t.userId)&&this.prevDecoderImplementationMap_.get(t.userId)===i.decoderImplementation||(this.log_.info(`${t.userId} decoderImplementation change to ${i.decoderImplementation}`),this.prevDecoderImplementationMap_.set(t.userId,i.decoderImplementation))),i.ssrc===n.auxiliary&&a.auxiliary&&(t.auxiliary.packetsReceived=i.packetsReceived,t.auxiliary.bytesReceived=i.bytesReceived,t.auxiliary.packetsLost=i.packetsLost,t.auxiliary.framesReceived=i.framesReceived,t.auxiliary.framesDecoded=i.framesDecoded,t.auxiliary.fpsDecoded=i.framesPerSecond,t.hasAuxiliary=!0)}}else"candidate-pair"===i.type&&Wd(i)&&ua(i.currentRoundTripTime)&&(t.rtt=Math.floor(1e3*i.currentRoundTripTime));la(i.frameWidth)||(i.trackIdentifier!==e.getMainStreamVideoTrackId()&&i.ssrc!==n.video||(t.video.frameWidth=i.frameWidth,t.video.frameHeight=i.frameHeight),i.trackIdentifier!==e.getAuxStreamVideoTrackId()&&i.ssrc!==n.auxiliary||(t.auxiliary.frameWidth=i.frameWidth,t.auxiliary.frameHeight=i.frameHeight)),la(i.audioLevel)||(t.audio.audioLevel=i.audioLevel||0,t.audio.totalAudioEnergy=i.totalAudioEnergy||0)})),0===t.audio.audioLevel)t.audio.audioLevel=(null===(s=e.getMainStream())||void 0===s?void 0:s.getInternalAudioLevel())||0}catch(n){this.log_.warn("failed to getStats on receiver connection "+n)}return t}async getStats(e,t){let i={};e&&(i=await this.getSenderStats(e));const s=[];for(let[n,a]of t){const e=await this.getReceiverStats(a);s.push(e)}return{senderStats:i,receiverStats:s}}getDifferenceValue(e,t){if(id(e))return t;const i=t-e;return i<0?0:i}prepareReport({stats:e,report:t,freezeMap:i}){if(!id(e.senderStats)){let i;i={uint32_audio_level:1e8*e.senderStats.audio.audioLevel,uint32_audio_energy:1e6*e.senderStats.audio.totalAudioEnergy,uint32_audio_codec_bitrate:e.senderStats.audio.bytesSent,audioLevel:e.senderStats.audio.audioLevel};let s=[],n={uint32_video_stream_type:2,uint32_video_codec_fps:e.senderStats.video.framesSent,uint32_video_capture_fps:e.senderStats.video.fpsCapture,uint32_video_width:e.senderStats.video.frameWidth,uint32_video_height:e.senderStats.video.frameHeight,uint32_video_codec_bitrate:e.senderStats.video.bytesSent,uint32_video_enc_fps:e.senderStats.video.framesEncoded};if(s.push(n),e.senderStats.small.bytesSent){let t={uint32_video_stream_type:3,uint32_video_codec_fps:e.senderStats.small.framesSent||0,uint32_video_capture_fps:e.senderStats.small.fpsCapture||0,uint32_video_width:e.senderStats.small.frameWidth||0,uint32_video_height:e.senderStats.small.frameHeight||0,uint32_video_codec_bitrate:e.senderStats.small.bytesSent,uint32_video_enc_fps:e.senderStats.small.framesEncoded||0};s.push(t)}if(e.senderStats.auxiliary.bytesSent){let t={uint32_video_stream_type:7,uint32_video_codec_fps:e.senderStats.auxiliary.framesSent||0,uint32_video_capture_fps:e.senderStats.auxiliary.fpsCapture||0,uint32_video_width:e.senderStats.auxiliary.frameWidth||0,uint32_video_height:e.senderStats.auxiliary.frameHeight||0,uint32_video_codec_bitrate:e.senderStats.auxiliary.bytesSent,uint32_video_enc_fps:e.senderStats.auxiliary.framesEncoded||0};s.push(t)}let a={uint32_bitrate:0,uint32_rtt:e.senderStats.rtt};t.msg_up_stream_info={msg_audio_status:i,msg_video_status:s,msg_network_status:a}}const s=this.statInterval;t.msg_down_stream_info=[],e.receiverStats.forEach((e=>{const s={};if(s.msg_user_info={str_identifier:e.userId,uint64_tinyid:e.tinyId},s.msg_network_status={uint32_rtt:e.rtt},s.msg_video_status={},e.hasAudio){const t={uint32_audio_codec_bitrate:e.audio.bytesReceived,uint32_audio_total_bitrate:e.audio.bytesReceived,uint32_audio_level:1e8*e.audio.audioLevel,uint32_audio_energy:1e6*e.audio.totalAudioEnergy,uint32_audio_receive:e.audio.packetsReceived,uint32_audio_origin_lost:e.audio.packetsLost,audioLevel:e.audio.audioLevel};s.msg_audio_status=t}if(s.msg_video_status=[],e.hasVideo){const t=i.get(e.userId+"_"+re),n=t?t.duration:0,a={uint32_video_stream_type:2,uint32_video_receive_fps:e.video.framesReceived,uint32_video_width:e.video.frameWidth,uint32_video_height:e.video.frameHeight,uint32_video_codec_bitrate:e.video.bytesReceived,uint32_video_receive:e.video.packetsReceived,uint32_video_origin_lost:e.video.packetsLost,uint32_video_block_time:n,uint32_video_dec_fps:e.video.framesDecoded};s.msg_video_status.push(a)}if(e.hasAuxiliary){const t=i.get(e.userId+"_"+de),n=t?t.duration:0,a={uint32_video_stream_type:7,uint32_video_receive_fps:e.auxiliary.framesReceived,uint32_video_width:e.auxiliary.frameWidth,uint32_video_height:e.auxiliary.frameHeight,uint32_video_codec_bitrate:e.auxiliary.bytesReceived,uint32_video_receive:e.auxiliary.packetsReceived+e.auxiliary.packetsLost,uint32_video_origin_lost:e.auxiliary.packetsLost,uint32_video_block_time:n,uint32_video_dec_fps:e.auxiliary.framesDecoded};s.msg_video_status.push(a)}t.msg_down_stream_info.push(s)}));const n=this.prevReport_;if(this.prevReport_=JSON.parse(JSON.stringify(t)),t.msg_up_stream_info.msg_audio_status&&n.msg_up_stream_info.msg_audio_status){const e=n.msg_up_stream_info.msg_audio_status,i=t.msg_up_stream_info.msg_audio_status,a=this.getDifferenceValue(e.uint32_audio_codec_bitrate,i.uint32_audio_codec_bitrate);i.uint32_audio_codec_bitrate=Math.round(8*a/s),t.msg_up_stream_info.msg_network_status.uint32_bitrate+=i.uint32_audio_codec_bitrate}const a=n.msg_up_stream_info.msg_video_status;t.msg_up_stream_info.msg_video_status.forEach((e=>{const i=a.find((t=>t.uint32_video_stream_type===e.uint32_video_stream_type));if(!i||0===i.uint32_video_codec_bitrate)return e.uint32_video_codec_bitrate=0,e.uint32_video_enc_fps=0,void(e.uint32_video_codec_fps=0);let n=i.uint32_video_codec_bitrate,o=i.uint32_video_enc_fps,r=i.uint32_video_codec_fps;const d=this.getDifferenceValue(n,e.uint32_video_codec_bitrate);e.uint32_video_codec_bitrate=Math.round(8*d/s),t.msg_up_stream_info.msg_network_status.uint32_bitrate+=e.uint32_video_codec_bitrate,e.uint32_video_enc_fps=Math.round(this.getDifferenceValue(o,e.uint32_video_enc_fps)/s),e.uint32_video_codec_fps=Math.round(this.getDifferenceValue(r,e.uint32_video_codec_fps)/s)}));const o=t.msg_down_stream_info,r=n.msg_down_stream_info;return o.forEach((e=>{const t=r.find((t=>t.msg_user_info.uint64_tinyid===e.msg_user_info.uint64_tinyid));if(t){if(e.msg_audio_status&&t.msg_audio_status){const i=e.msg_audio_status,n=t.msg_audio_status;i.uint32_audio_origin_lost=this.getDifferenceValue(n.uint32_audio_origin_lost,i.uint32_audio_origin_lost),i.uint32_audio_receive=this.getDifferenceValue(n.uint32_audio_receive,i.uint32_audio_receive),i.uint32_audio_receive+=i.uint32_audio_origin_lost;const a=this.getDifferenceValue(n.uint32_audio_codec_bitrate,i.uint32_audio_codec_bitrate);i.uint32_audio_codec_bitrate=Math.round(8*a/s),i.uint32_audio_total_bitrate=Math.round(8*a/s)}if(e.msg_video_status&&t.msg_video_status){const i=e.msg_video_status,n=t.msg_video_status;i.forEach((e=>{const t=n.find((t=>t.uint32_video_stream_type===e.uint32_video_stream_type));if(!t)return e.uint32_video_receive=0,e.uint32_video_origin_lost=0,e.uint32_video_codec_bitrate=0,e.uint32_video_receive_fps=0,void(e.uint32_video_dec_fps=0);let i=t.uint32_video_receive,a=t.uint32_video_origin_lost,o=t.uint32_video_codec_bitrate,r=t.uint32_video_receive_fps,d=t.uint32_video_dec_fps;e.uint32_video_origin_lost=this.getDifferenceValue(a,e.uint32_video_origin_lost),e.uint32_video_receive=this.getDifferenceValue(i,e.uint32_video_receive)+e.uint32_video_origin_lost;const c=this.getDifferenceValue(o,e.uint32_video_codec_bitrate);e.uint32_video_codec_bitrate=Math.round(8*c/s);const l=this.getDifferenceValue(r,e.uint32_video_receive_fps);e.uint32_video_receive_fps=Math.round(l/s),e.uint32_video_dec_fps=Math.round(this.getDifferenceValue(d,e.uint32_video_dec_fps)/s)}))}}})),t}async getStatsReport({uplinkConnection:e,downlinkConnections:t,freezeMap:i}){const s={msg_up_stream_info:{msg_audio_status:{uint32_audio_format:0,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_level:0,uint32_audio_energy:0,audioLevel:0},msg_video_status:[{uint32_video_stream_type:0,uint32_video_codec_fps:0,uint32_video_capture_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_codec_bitrate:0,uint32_video_receive:0,uint32_video_origin_lost:0,uint32_video_final_lost:0,uint32_video_enc_fps:0}],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}},msg_down_stream_info:[{msg_user_info:{str_identifier:"",uint64_tinyid:""},msg_audio_status:{uint32_audio_format:0,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_total_bitrate:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_final_lost:0,audioLevel:0},msg_video_status:[{uint32_video_stream_type:0,uint32_video_receive_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_codec_bitrate:0,uint32_video_receive:0,uint32_video_origin_lost:0,uint32_video_block_time:0,uint32_video_dec_fps:0}],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0,uint32_jitter:0}}]},n=await this.getStats(e,t);return"{}"===JSON.stringify(this.prevReport_)&&(this.prevReport_=JSON.parse(JSON.stringify(s))),this.prepareReport({stats:n,report:s,freezeMap:i,uplinkConnection:e,downlinkConnections:t}),this.prevReportTime_=Date.now(),s}reset(){this.prevReportTime_=0,this.prevReport_={},this.prevEncoderImplementation_="",this.prevQualityLimitationReason_="",this.prevDecoderImplementationMap_=new Map}}class lc{constructor({signalChannel:e,connections:t,client:i}){this.client_=i,this.signalChannel_=e,this.connections_=t,this.client_=i,this.log_=Oo.createLogger({id:"q|"+this.client_.getUserId(),userId:this.client_.getUserId(),sdkAppId:this.client_.getSDKAppId()}),this.uplinkConnection_=null,this.uplinkNetworkQuality_=0,this.uplinkRTT_=0,this.uplinkLoss_=0,this.downlinkNetworkQuality_=0,this.downlinkRTT_=0,this.downlinkLoss_=0,this.downlinkPrevStatMap_=new Map,this.downlinkLossAndRTTMap_=new Map,this.interval_=-1,this.emitter_=new Ma,this.initialize()}get uplinkNetworkQuality(){return this.uplinkNetworkQuality_}set uplinkNetworkQuality(e){e!==this.uplinkNetworkQuality_&&this.log_.info(`uplink network quality change ${this.uplinkNetworkQuality} -> ${e}, rtt: ${this.uplinkRTT_}, loss: ${this.uplinkLoss_}`),this.uplinkNetworkQuality_=e}get downlinkNetworkQuality(){return this.downlinkNetworkQuality_}set downlinkNetworkQuality(e){if(e!==this.downlinkNetworkQuality_){const{rtt:t,loss:i}=this.getAverageLossAndRTT([...this.downlinkLossAndRTTMap_.values()]);this.log_.info(`downlink network quality change ${this.downlinkNetworkQuality} -> ${e}, rtt: ${t}, loss: ${i}`)}this.downlinkNetworkQuality_=e}initialize(){this.signalChannel_.on(qo.UPLINK_NETWORK_STATS,(e=>{this.handleUplinkNetworkQuality(e)})),this.signalChannel_.on($o,this.handleSignalConnectionStateChange.bind(this)),this.start()}handleUplinkNetworkQuality(e){if(!this.uplinkConnection_)return this.uplinkNetworkQuality=0,this.uplinkLoss_=0,void(this.uplinkRTT_=0);const t=this.uplinkConnection_.getPeerConnection();if(t&&this.isPeerConnectionDisconnected(t))return this.uplinkNetworkQuality=6,this.uplinkLoss_=0,void(this.uplinkRTT_=0);if(0===e.data.code){const t=e.data.data,i=t.expectAudPkg+t.expectVidPkg,s=t.recvAudPkg+t.recvVidPkg,n=i-s,a=t.delay;if(a&&this.updateDelay(a),0===i&&0===s)return;this.uplinkLoss_=n<=0?0:Math.round(n/i*100),this.uplinkRTT_=t.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this.uplinkLoss_,this.uplinkRTT_)}}async handleDownlinkNetworkQuality(){if(!this.connections_||0===this.connections_.size)return void(this.downlinkNetworkQuality=0);const e=[...this.connections_.values()],t=e.filter((e=>e.getPeerConnection()&&e.getPeerConnection().connectionState===fe));if(e.filter((e=>e.getPeerConnection()&&this.isPeerConnectionDisconnected(e.getPeerConnection()))).length===e.length)return void(this.downlinkNetworkQuality=6);for(let n=0;n{this.isPeerConnectionDisconnected(e)&&(this.downlinkPrevStatMap_.delete(e),this.downlinkLossAndRTTMap_.delete(e))})),0===this.downlinkLossAndRTTMap_.size)return;const{rtt:i,loss:s}=this.getAverageLossAndRTT([...this.downlinkLossAndRTTMap_.values()]);this.downlinkRTT_=i,this.downlinkLoss_=s,this.downlinkNetworkQuality=this.getNetworkQuality(s,i)}async getStat(e){const t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!Vd())return t;const i=e.getReceivers();try{for(let e=0;e{"candidate-pair"===e.type&&ua(e.currentRoundTripTime)&&(t.rtt=Math.round(1e3*e.currentRoundTripTime)),"inbound-rtp"!==e.type||e.mediaType!==o&&e.mediaType!==r||(t.totalPacketsLost+=e.packetsLost,t.totalPacketsReceived+=e.packetsReceived)}))}return t}catch(s){return t}}getAverageLossAndRTT(e){const t={rtt:0,loss:0};return Array.isArray(e)&&e.length>0&&(e.forEach((e=>{t.rtt+=e.rtt,t.loss+=e.loss})),Object.keys(t).forEach((i=>{t[i]=Math.round(t[i]/e.length)}))),t}getNetworkQuality(e,t){return e>50||t>500?5:e>30||t>350?4:e>20||t>200?3:e>10||t>100?2:e>=0||t>=0?1:0}handleSignalConnectionStateChange(e){e.state===Ho?(this.uplinkRTT_=0,this.uplinkLoss_=0,this.uplinkNetworkQuality=6):e.state===Wo&&6===this.uplinkNetworkQuality&&(this.uplinkNetworkQuality=5)}handleUplinkConnectionStateChange({state:e}){e===ce?(this.uplinkLoss_=0,this.uplinkRTT_=0,this.uplinkNetworkQuality=6):e===ue&&6===this.uplinkNetworkQuality&&(this.uplinkNetworkQuality=5)}isPeerConnectionDisconnected(e){return!(!e||e.connectionState!==Se&&e.connectionState!==pe&&e.connectionState!==ge)}setUplinkConnection(e){this.uplinkConnection_=e,this.uplinkConnection_?this.uplinkConnection_.on(tc.CONNECTION_STATE_CHANGED,this.handleUplinkConnectionStateChange.bind(this)):(this.uplinkNetworkQuality=0,this.uplinkRTT_=0,this.uplinkLoss_=0)}start(){-1===this.interval_?(this.log_.info("start network quality calculating"),this.interval_=kd.run(Pt,(()=>{this.handleDownlinkNetworkQuality(),La.emit(Ro,{client:this.client_,uplinkNetworkQuality:this.uplinkNetworkQuality,downlinkNetworkQuality:this.downlinkNetworkQuality,uplinkRTT:this.uplinkRTT_,uplinkLoss:this.uplinkLoss_,downlinkRTT:this.downlinkRTT_,downlinkLoss:this.downlinkLoss_,downlinkLossAndRTTMap:this.downlinkLossAndRTTMap_}),this.emitter_.emit(ic.NETWORK_QUALITY,{uplinkNetworkQuality:this.uplinkNetworkQuality,downlinkNetworkQuality:this.downlinkNetworkQuality,uplinkRTT:this.uplinkRTT_,uplinkLoss:this.uplinkLoss_,downlinkRTT:this.downlinkRTT_,downlinkLoss:this.downlinkLoss_})}),{delay:2e3})):this.log_.info("network quality calculating is already started")}stop(){this.log_.info("stop network quality calculating"),-1!==this.interval_&&(kd.clearTask(this.interval_),this.interval_=-1),this.downlinkLossAndRTTMap_.clear(),this.downlinkPrevStatMap_.clear()}on(e,t){this.emitter_.on(e,t)}updateDelay(e){e.forEach((({srcTinyId:e,videoDelay:t,audioDelay:i})=>{const s=this.connections_.get(e);s&&s.setDelay({videoDelay:t,audioDelay:i})}))}}class hc{constructor(e){this.log_=Oo.createLogger({id:e.client.getUserId(),userId:e.client.getUserId(),sdkAppId:e.client.getSDKAppId()}),this.localStream_=null,this.prevDevices_=[],this.initialize()}initialize(){navigator.mediaDevices&&navigator.mediaDevices.addEventListener&&(this.onDeviceChange=this.onDeviceChange.bind(this),navigator.mediaDevices.addEventListener("devicechange",this.onDeviceChange))}destroy(){navigator.mediaDevices&&navigator.mediaDevices.removeEventListener&&navigator.mediaDevices.removeEventListener("devicechange",this.onDeviceChange)}async onDeviceChange(){if(!this.localStream_||!this.localStream_.getMediaStream()||this.localStream_.getScreen())return;const e=await mc(),t=e.filter((e=>this.prevDevices_.findIndex((({deviceId:t})=>e.deviceId===t))<0)),i=this.prevDevices_.filter((t=>e.findIndex((({deviceId:e})=>t.deviceId===e))<0));t.length>0&&this.handleDeviceAdded(this.prevDevices_,t),i.length>0&&this.handleDeviceRemoved(e,i),this.prevDevices_=e}async setLocalStream(e){e&&(this.prevDevices_=await mc()),this.localStream_=e}handleDeviceAdded(e,t){var i,s;if(!this.localStream_)return;this.log_.warn(`devicesAdded: ${JSON.stringify(t)}`),this.localStream_.updateDeviceIdInUse();const n=t.filter((({kind:e})=>e===E)),a=t.filter((({kind:e})=>e===b)),o=e.filter((({kind:e})=>e===E)),r=e.filter((({kind:e})=>e===b)),d=n.length>0&&0===o.length&&"live"!==(null===(i=this.localStream_.getVideoTrack())||void 0===i?void 0:i.readyState),c=a.length>0&&0===r.length&&"live"!==(null===(s=this.localStream_.getAudioTrack())||void 0===s?void 0:s.readyState);if(c&&d)return this.log_.info("new microphone and camera detected, but there was no device before."),void this.localStream_.recoverCapture({audio:!0,video:!0,cameraId:n[0].deviceId,microphoneId:a[0].deviceId});d&&(this.log_.info("new camera detected, but there was no camera before."),this.localStream_.recoverCapture({audio:!1,video:!0,cameraId:n[0].deviceId})),c&&(this.log_.info("new microphone detected, but there was no microphone before."),this.localStream_.recoverCapture({audio:!0,video:!1,microphoneId:a[0].deviceId}))}handleDeviceRemoved(e,t){if(!this.localStream_)return;this.log_.warn(`devicesRemoved: ${JSON.stringify(t)}`),this.localStream_.updateDeviceIdInUse();let i=!1,s=!1;const n=this.localStream_.getCameraId(),a=this.localStream_.getMicrophoneId();if("default"===a){const t=this.localStream_.getMicrophoneGroupId(),i=e.filter((e=>"default"===e.deviceId&&e.kind===b))[0];i&&i.groupId!==t&&(s=!0)}if(t.forEach((({deviceId:e})=>{n.length>0&&e===n?i=!0:a.length>0&&e===a&&(s=!0)})),i&&s)return this.log_.warn(`current camera and microphone in use is lost, cameraId: ${n}, microphoneId: ${a}`),void((this.localStream_.getAudio()||this.localStream_.getVideo())&&this.localStream_.recoverCapture({video:!0,audio:!0}));i&&(this.log_.warn(`current camera in use is lost, deviceId: ${n}`),this.localStream_.getVideo()&&this.localStream_.recoverCapture({video:!0,audio:!1})),s&&(this.log_.warn(`current microphone in use is lost, deviceId: ${a}`),this.localStream_.getAudio()&&this.localStream_.recoverCapture({video:!1,audio:!0}))}}const uc=new Set;async function _c(){if(jd()||Hd())return[];const e=await navigator.mediaDevices.enumerateDevices();return e.forEach((e=>{uc.add(`${e.deviceId}_${e.kind}`)})),e}async function mc(){return(await _c()).filter((e=>e.kind!==b||"communications"!=e.deviceId)).map(((e,t)=>{let i=e.label;e.label||(i=e.kind+"_"+t);const s={label:i,deviceId:e.deviceId,kind:e.kind};return e.groupId&&(s.groupId=e.groupId),e.getCapabilities&&(s.getCapabilities=()=>e.getCapabilities()),s}))}async function pc(){return(await _c()).filter((e=>e.kind===b&&"communications"!==e.deviceId)).map(((e,t)=>{let i=e.label;e.label||(i="microphone_"+t);const s={label:i,deviceId:e.deviceId,kind:e.kind};return e.groupId&&(s.groupId=e.groupId),e.getCapabilities&&(s.getCapabilities=()=>e.getCapabilities()),s}))}async function gc(){return(await _c()).filter((e=>"audiooutput"===e.kind)).map(((e,t)=>{let i=e.label;e.label||(i="speaker_"+t);const s={label:i,deviceId:e.deviceId,kind:e.kind};return e.groupId&&(s.groupId=e.groupId),s}))}let Sc,fc,vc=new Blob(["class VolumeMeter extends AudioWorkletProcessor{constructor(){super();this.volume=0;this.intervalTime=200;this.tick=this.intervalTime;this.isStop=false;this.port.onmessage=event=>{const{data}=event;switch(data.name){case'setIntervalTime':this.intervalTime=data.intervalTime;break;case'stop':this.isStop=true;break}}}process(inputs){const input=inputs[0];if(this.isStop){return false}if(input.length>0){const firstChannel=input[0];let sum=0;let rms;for(let i=0;i{this.volume_=e.data.volume||0},this.streamSource_.connect(this.audioWorkletNode_).connect(this.destination_),this.handleAudioLevelInterval({interval:this.interval_})}catch(e){this.log_.warn("load volume meter failed, load again. error: "+e),this.initScriptProcessor()}}initScriptProcessor(){if(!this.scriptProcessorNode_)try{this.scriptProcessorNode_=this.audioCtx_.createScriptProcessor(2048,1,1),this.scriptProcessorNode_.onaudioprocess=e=>{const t=e.inputBuffer.getChannelData(0);let i=0;for(let s=0;s0&&(Tc-=1),0===Tc)&&(null===(e=Sc)||void 0===e||e.close(),Sc=null,fc=null)}resume(){var e;null===(e=Sc)||void 0===e||e.resume()}getInternalAudioLevel(){return this.volume_}getCalculatedVolume(){return this.volume_.toFixed(2)}handleAudioLevelInterval({interval:e}){var t;this.interval_=e,null===(t=this.audioWorkletNode_)||void 0===t||t.port.postMessage({name:"setIntervalTime",intervalTime:e})}}class Ec{constructor(e){this.stream_=e.stream,this.userId_=e.stream.getUserId(),this.log_=this.stream_.getLogger(),this.track_=e.track,e.gainedTrack&&(this.gainedTrack_=e.gainedTrack),this.div_=e.div,this.muted_=e.muted,this.outputDeviceId_=e.outputDeviceId,this.volume_=e.volume,this.pausedRetryCount_=5,this.emitter_=new Ma,this.initializeElement(),this.state_="NONE",this.volumeMeter_=new bc({stream:this.stream_,track:this.gainedTrack_||this.track_,log:this.log_})}get isPlaying(){return this.state_===L}initializeElement(){if(this.isAudioElementInit()){const e=new MediaStream;e.addTrack(this.gainedTrack_||this.track_);const t=document.createElement(o);t.srcObject=e,t.muted=this.muted_,t.setAttribute("id",`audio_${this.stream_.getId()}`),t.setAttribute("autoplay","autoplay"),t.setAttribute("playsinline","playsinline"),this.div_.appendChild(t),this.element_=t}this.handleEvents()}setMuted(e){this.element_&&(this.element_.muted=e,this.muted_=e)}async play(){this.outputDeviceId_&&this.element_&&await this.element_.setSinkId(this.outputDeviceId_),this.setVolume(this.volume_);try{this.element_&&await this.element_.play()}catch(e){const t=ta({key:cs,data:{media:"Audio",error:e}});if(this.log_.warn(t),t.includes("NotAllowedError"))throw new gr({code:pr.PLAY_NOT_ALLOWED,message:t})}}handleEvents(){this.handleElementEvent=this.handleElementEvent.bind(this),this.handleTrackEvent=this.handleTrackEvent.bind(this),this.element_&&(this.element_.addEventListener(v,this.handleElementEvent),this.element_.addEventListener(f,this.handleElementEvent),this.element_.addEventListener(I,this.handleElementEvent),this.element_.addEventListener(y,this.handleElementEvent)),this.track_.addEventListener(f,this.handleTrackEvent),this.track_.addEventListener(g,this.handleTrackEvent),this.track_.addEventListener(S,this.handleTrackEvent),this.track_.readyState===f&&this.handleTrackEvent({type:f}),this.track_.muted&&this.handleTrackEvent({type:g})}async handleElementEvent(e){switch(e.type){case v:this.log_.info("audio player is playing"),this.state_=L,La.emit(no,{stream:this.stream_}),this.emitter_.emit(dc,{state:this.state_,reason:v});break;case f:this.log_.info("audio player is ended"),this.state_!==V&&(this.state_=V,this.emitter_.emit(dc,{state:this.state_,reason:f}));break;case I:{this.log_.info("audio player is paused"),this.state_=O,this.emitter_.emit(dc,{state:this.state_,reason:I});const e=this.div_&&document.getElementById(this.div_.id);e||this.log_.warn(`audio player has been remove, element ID: ${this.div_.id}`);const t=Vn();this.pausedRetryCount_>0&&(ua(t)&&t<=70||!e)&&(this.resume(),this.pausedRetryCount_--),zs&&(this.interval_=kd.run((()=>{this.element_&&this.state_===O&&this.resume()}),{delay:3e3}));break}case y:if(this.element_&&this.element_.error){const e=`${zd()}/${Yn().name}/${Yn().version}`,t=await Xh.getSpeakers();let i=t[0].label;const s=t.find((e=>e.deviceId===this.outputDeviceId_));s&&(i=s.label),this.log_.error(`audio player error observed. code: ${this.element_.error.code} message: ${this.element_.error.message} deviceInfo: ${e} speaker: ${i}`),sd.uploadEvent({log:`stat-${this.stream_.getType()}-audio-${Je}-${this.element_.error.code}-${e}-${i}`,userId:this.userId_,error:this.element_.error})}}}handleTrackEvent(e){const t=e.type;switch(t){case f:this.log_.info("audio track is ended"),this.state_!==V&&(this.state_=V,this.emitter_.emit(dc,{state:this.state_,reason:f})),La.emit(Eo,{stream:this.stream_,type:t});break;case g:this.log_.info("audio track is unable to provide media output"),this.stream_.isRemote()||Ta(),this.state_!==O&&(this.state_=O,this.emitter_.emit(dc,{state:this.state_,reason:g})),La.emit(bo,{stream:this.stream_,type:t});break;case S:this.log_.info("audio track is able to provide media output"),this.state_===O&&(this.state_=L,this.emitter_.emit(dc,{state:this.state_,reason:S}))}}unbindEvents(){this.element_&&(this.element_.removeEventListener(v,this.handleElementEvent),this.element_.removeEventListener(f,this.handleElementEvent),this.element_.removeEventListener(I,this.handleElementEvent),this.element_.removeEventListener(y,this.handleElementEvent)),this.track_&&(this.track_.removeEventListener(f,this.handleTrackEvent),this.track_.removeEventListener(g,this.handleTrackEvent),this.track_.removeEventListener(S,this.handleTrackEvent))}async setSinkId(e){this.outputDeviceId_!==e&&(this.element_&&await this.element_.setSinkId(e),this.outputDeviceId_=e)}setVolume(e){this.element_&&(this.log_.info(`audioElement setVolume to : ${e}`),this.element_.volume=e)}getAudioLevel(){return this.volumeMeter_.getCalculatedVolume()}getInternalAudioLevel(){return this.volumeMeter_.getInternalAudioLevel()}stop(){this.unbindEvents(),this.element_&&(this.div_.removeChild(this.element_),this.element_.srcObject=null,this.element_=null),this.volumeMeter_&&(this.volumeMeter_.destroy(),this.volumeMeter_=null),this.interval_>0&&kd.clearTask(this.interval_)}async resume(){try{this.volumeMeter_&&this.volumeMeter_.resume(),this.element_&&await this.element_.play()}catch(e){const t=ta({key:cs,data:{media:"Audio",error:e}});if(this.log_.warn(t),t.includes("NotAllowedError"))throw new gr({code:pr.PLAY_NOT_ALLOWED,message:t})}}on(e,t){this.emitter_.on(e,t)}isAudioElementInit(){return!("15.2"===Jn||"15.3"===Jn||"15.4"===Jn)||"local"!==this.stream_.getType()||!this.muted_||(this.log_.info("audioElement is muted."),!1)}}const wc="trtc_autoplay_wrapper";let kc=!1;const Rc=()=>!!document.querySelector(`.${wc}`),Ac=`${bt}/${ya()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,Cc=`
${ya()?"其他方案?":"Any other solution?"}`,Dc=""+(ya()?`浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。${Cc}`:`Autoplay Policy: Before user interacts with the web page (clicking, touching), page will not be allowed to play media with sound. This Dialog is used to help users resume playback. ${Cc}`);class Nc{constructor(){if(this.dialogNode_=null,this.bodyPosition_="",this.content="音视频播放被浏览器拦截,请点击“恢复播放”。",ya()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!kc){const e=document.createElement("style");e.innerHTML=`.trtc_autoplay_mask{position:fixed;top:0;left:0;right:0;bottom:0;width:100vw;height:100vh;display:flex;justify-content:center;align-items:center;background:rgba(0,0,0,0.5);z-index:1500;}.trtc_autoplay_mask div:not(.trtc_autoplay_action_wrapper){display:block !important;}.${wc}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${wc} a{color:#2473E8;}.trtc_autoplay_header{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.trtc_autoplay_content{margin:8px 0;}.trtc_autoplay_action_wrapper{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.trtc_autoplay_collapse{margin-right:auto;cursor:pointer}.trtc_autoplay_question{height:100%;line-height:16px;cursor:pointer;}.trtc_autoplay_action_confirm{margin-left:8px;color:#fff;background:#2473E8;padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.trtc_autoplay_action_confirm:hover{opacity:0.9;}.trtc_autoplay_collapse,.trtc_autoplay_action_confirm,.trtc_autoplay_content,.trtc_autoplay_question{font-size:14px;}@media screen and (max-width:750px){.${wc}{width:80vw;}}`,document.head.appendChild(e),kc=!0}this.showDetail_=!1,this.isCollapseClicked_=!1,this.isQuestionClicked_=!1,this.addDiaLog()}createDiaLog(){const e=document.createElement("template");e.innerHTML=`
${location.host}
${this.content}
`.trim();const t=document.createElement("button");t.className="trtc_autoplay_action_confirm",t.innerText=ya()?"恢复播放":"Resume",t.onclick=this.onConfirm.bind(this);const i=document.createElement("div");i.className="trtc_autoplay_question",i.innerHTML='\n \n \n \n \n \n ',i.onclick=this.onQuestionClick.bind(this);const s=document.createElement("div");s.className="trtc_autoplay_collapse",s.innerText=""+(ya()?"详情 >":"Detail >"),s.onclick=this.onCollapseClick.bind(this);const n=e.content.firstChild,a=n.querySelector(".trtc_autoplay_action_wrapper");return a.appendChild(s),a.appendChild(i),a.appendChild(t),n}addDiaLog(){Rc()||(this.dialogNode_=this.createDiaLog(),document.body.appendChild(this.dialogNode_),this.dialogNode_.onclick=this.onConfirm.bind(this),this.dialogNode_.querySelector(`.${wc}`).onclick=e=>e.stopPropagation(),this.bodyPosition_=document.body.style.position,document.body.style.position="fixed",Oo.info("show autoplay dialog"),sd.uploadEvent({log:"dialog-show"}))}deleteDiaLog(){this.dialogNode_&&(document.body.removeChild(this.dialogNode_),document.body.style.position=this.bodyPosition_,this.dialogNode_=null)}onConfirm(){Oo.warn("confirm clicked, try resume stream"),La.emit(Ao),this.deleteDiaLog()}onCollapseClick(){const e=this.dialogNode_.querySelector(".trtc_autoplay_detail");e.style.visibility=""+(this.showDetail_?"hidden":"visible"),e.style.height=`${this.showDetail_?0:"fit-content"}`,this.showDetail_=!this.showDetail_,this.isCollapseClicked_||sd.uploadEvent({log:"dialog-1"}),this.isCollapseClicked_=!0}onQuestionClick(){window.open(Ac,"_blank"),this.isQuestionClicked_||sd.uploadEvent({log:"dialog-2"}),this.isQuestionClicked_=!0}}class Pc{constructor(e){this.stream_=e.stream,this.userId_=e.stream.getUserId(),this.log_=this.stream_.getLogger(),this.track_=e.track,this.div_=e.div,this.muted_=e.muted,this.objectFit_=e.objectFit,this.mirror_=e.mirror,this.emitter_=new Ma,this.initializeElement(),this.state_="NONE",this.pausedRetryCount_=5}get isPlaying(){return this.state_===L}initializeElement(){const e=new MediaStream;e.addTrack(this.track_);const t=document.createElement(r);t.srcObject=e,t.muted=!0;let i=`width: 100%; height: 100%; object-fit: ${this.objectFit_};`;this.mirror_&&(i+="transform: scaleX(-1);"),t.setAttribute("id",`video_${this.stream_.getId()}`),t.setAttribute("style",i),t.setAttribute("autoplay","autoplay"),t.setAttribute("playsinline","playsinline"),this.element_=t,"17.0"!==Jn&&"17.1"!==Jn||this.initCanvasElement(i),this.div_&&this.div_.appendChild(this.canvas_||t),this.handleEvents()}initCanvasElement(e){if(!this.track_||this.stream_.isRemote())return;const t=document.createElement("canvas"),i=()=>{var e;const i=null===(e=this.track_)||void 0===e?void 0:e.getSettings();i&&i.width&&i.height&&(t.width=i.width,t.height=i.height)};i(),t.setAttribute("style",e);const s=t.getContext("2d");this.canvasTimerId_=kd.run("raf",(()=>{this.element_&&s&&(i(),s.drawImage(this.element_,0,0,t.width,t.height))}),{backgroundTask:!1}),this.log_.warn("use canvas for playback"),this.canvas_=t}setRect({width:e,height:t}){this.element_&&(this.element_.style.width=e+"px",this.element_.style.height=t+"px")}setMirror(e){this.element_&&(this.element_.style.transform=e?"scaleX(-1)":"",this.mirror_=e)}setObjectFit(e){this.element_&&(this.element_.style.objectFit=`${e}`,this.objectFit_=e)}async play(){try{await this.element_.play()}catch(e){const t=ta({key:cs,data:{media:"Video",error:e}});if(this.log_.warn(t),t.includes("NotAllowedError"))throw new gr({code:pr.PLAY_NOT_ALLOWED,message:t})}}handleEvents(){this.handleElementEvent=this.handleElementEvent.bind(this),this.handleTrackEvent=this.handleTrackEvent.bind(this),this.element_.addEventListener(v,this.handleElementEvent),this.element_.addEventListener(f,this.handleElementEvent),this.element_.addEventListener(I,this.handleElementEvent),this.element_.addEventListener(y,this.handleElementEvent),this.element_.addEventListener(T,this.handleElementEvent),this.track_.addEventListener(f,this.handleTrackEvent),this.track_.addEventListener(g,this.handleTrackEvent),this.track_.addEventListener(S,this.handleTrackEvent),this.track_.readyState===f&&this.handleTrackEvent({type:f}),this.track_.muted&&this.handleTrackEvent({type:g})}handleElementEvent(e){switch(e.type){case v:this.log_.info("video player is playing"),this.state_=L,La.emit(so,{stream:this.stream_}),this.emitter_.emit(dc,{state:this.state_,reason:v}),this.interval_&&(kd.clearTask(this.interval_),this.interval_=null);break;case f:this.log_.info("video player is ended"),this.state_!==V&&(this.state_=V,this.emitter_.emit(dc,{state:this.state_,reason:f}));break;case I:this.log_.info("video player is paused"),this.div_&&!document.getElementById(this.div_.id)&&this.log_.warn(`video player has been remove, element ID: ${this.div_.id}`),this.state_=O,this.emitter_.emit(dc,{state:this.state_,reason:I}),this.pausedRetryCount_>0&&!Rc()&&(this.log_.info("video player auto resume when video paused"),this.resume(),this.pausedRetryCount_--),zs&&(this.interval_=kd.run((()=>{this.element_&&this.state_===O&&this.resume()}),{delay:3e3}));break;case y:if(this.element_&&this.element_.error){const e=`${zd()}/${Yn().name}/${Yn().version}`;this.log_.error(`video player error observed. code: ${this.element_.error.code} message: ${this.element_.error.message} deviceInfo: ${e}`),sd.uploadEvent({log:`stat-${this.stream_.getType()}-video-${Je}-${this.element_.error.code}-${e}`,userId:this.userId_,error:this.element_.error})}break;case T:La.emit(Io,{stream:this.stream_})}}handleTrackEvent(e){const t=e.type;switch(t){case f:this.log_.info("video track is ended"),La.emit(To,{stream:this.stream_,type:t}),this.state_!==V&&(this.state_=V,this.emitter_.emit(dc,{state:this.state_,reason:f}));break;case g:this.log_.info("video track is unable to provide media output"),this.stream_.isRemote()||Ta(),La.emit(So,{stream:this.stream_,type:t}),this.state_!==O&&(this.state_=O,this.emitter_.emit(dc,{state:this.state_,reason:g}));break;case S:this.log_.info("video track is able to provide media output"),La.emit(fo,{stream:this.stream_}),this.state_===O&&(this.state_=L,this.emitter_.emit(dc,{state:this.state_,reason:S}))}}unbindEvents(){this.element_&&(this.element_.removeEventListener(v,this.handleElementEvent),this.element_.removeEventListener(f,this.handleElementEvent),this.element_.removeEventListener(I,this.handleElementEvent),this.element_.removeEventListener(y,this.handleElementEvent),this.element_.removeEventListener(T,this.handleElementEvent)),this.track_&&(this.track_.removeEventListener(f,this.handleTrackEvent),this.track_.removeEventListener(g,this.handleTrackEvent),this.track_.removeEventListener(S,this.handleTrackEvent))}stop(){this.unbindEvents(),this.element_&&(this.element_.remove(),this.element_.srcObject=null,this.element_=null),this.interval_&&kd.clearTask(this.interval_),this.canvasTimerId_&&kd.clearTask(this.canvasTimerId_),this.canvas_&&(this.canvas_.remove(),this.canvas_=null)}resume(){return this.play()}getVideoFrame(){const e=document.createElement("canvas");e.width=this.element_.videoWidth,e.height=this.element_.videoHeight;return e.getContext("2d").drawImage(this.element_,0,0),e.toDataURL("image/png")}on(e,t){this.emitter_.on(e,t)}getElement(){return this.element_?this.element_:null}}class Mc{constructor(e,t,i){this.isUplink_=i,this.connection_=e,this.log_=t,this.seiMessageList_=[],this.smallVideoSeiMessageList_=[],this.seiPayloadType_=243,this.runningAbortMap_=new Map,this.abortMap_=new Map,this.onSEIMessage=null}get isRunning(){return!!this.runningAbortMap_.size>0}start(e,t=this.seiMessageList_){const i=e.createEncodedStreams(),s=i.readable,n=i.writable,a=new TransformStream({transform:this.isUplink_?(e,i)=>this.encodeVideoFrame(e,i,t):(t,i)=>{var s,n;return this.decodeVideoFrame(t,i,e===(null===(s=this.connection_)||void 0===s||null===(n=s.getPeerConnection())||void 0===n?void 0:n.getReceivers()[Ct]))}}),o=new AbortController;s.pipeThrough(a).pipeTo(n,{signal:o.signal}).catch((()=>{})),this.runningAbortMap_.set(e,o)}restart(e,t){this.stop(),this.start(e,t)}stop(e){var t;null===(t=this.runningAbortMap_.get(e))||void 0===t||t.abort(),this.runningAbortMap_.delete(e)}destroy(){this.stop(),this.runningAbortMap_.forEach((e=>e.abort())),this.runningAbortMap_.clear(),this.abortMap_.forEach((e=>e.abort())),this.abortMap_.clear(),this.log_=null,this.onSEIMessage=null,this.connection_=null}handleEncodedStreams(){try{const e=this.connection_.getPeerConnection();this.clearUnusedSenderOrReceiver(e),this.isUplink_?e.getSenders().forEach(((e,t)=>{if(!this.runningAbortMap_.has(e)&&!this.abortMap_.has(e))if(t===kt||t===Rt){const i=t===Rt?this.smallVideoSeiMessageList_:this.seiMessageList_;this.isRunning?this.restart(e,i):this.start(e,i)}else this.pipeSenderOrReceiver(e)})):e.getReceivers().forEach(((e,t)=>{var i;this.runningAbortMap_.has(e)||this.abortMap_.has(e)||(t!==At&&t!==Ct||(null===(i=e.track)||void 0===i?void 0:i.kind)!==r?this.pipeSenderOrReceiver(e):this.isRunning?this.restart(e):this.start(e))}))}catch(e){this.log_.warn(e)}}pipeSenderOrReceiver(e){const{readable:t,writable:i}=e.createEncodedStreams(),s=new AbortController;this.abortMap_.set(e,s),t.pipeTo(i,{signal:s.signal}).catch((()=>{}))}clearUnusedSenderOrReceiver(e){this.abortMap_.forEach(((t,i)=>{(this.isUplink_?e.getSenders():e.getReceivers()).find((e=>e===i))||(t.abort(),this.abortMap_.delete(i))}))}push(e,t){t&&t.seiPayloadType&&(this.seiPayloadType_=t.seiPayloadType),this.seiMessageList_.push(e),this.smallVideoSeiMessageList_.push(e)}hasSEI(e){const t=new DataView(e);return 1===t.getInt32(0)&&6===t.getInt8(4)}isEmptyFrame(e){return"empty"===e.type||0===e.data.byteLength}getNaluCount(e){let t=0,i=0;const s=new DataView(e);for(let n=0;n0&&!this.isEmptyFrame(e)){const t=9-this.getNaluCount(e.data);if(t<=0)return;const s=i.splice(0,t).reverse().map(this.encodeSEINalu.bind(this)),n=s.reduce(((e,t)=>e+t.dataView.byteLength),0),a=new ArrayBuffer(n+e.data.byteLength),o=new DataView(a),r=new DataView(e.data);let d=0;for(let e=0;e{this.onSEIMessage({seiPayloadType:e.seiPayloadType,data:e.seiPayload.buffer,isFromAuxiliary:i})}))}}catch(s){this.log_.warn(s)}t.enqueue(e)}encodeSEINalu(e){const t=e.byteLength,i=parseInt(t/255),s=t%255,n=[];n.push(0,0,0,1,6,this.seiPayloadType_);for(let o=0;o{},this.peerConnection_.close(),this.peerConnection_=null,e&&this.emitConnectionStateChangedEvent(ce))}getDTLSTransportState(){if(!this.peerConnection_)return"unknown";let e=null;if(this.isUplink_){if(!Ud()||0===this.peerConnection_.getSenders().length)return"unknown";e=this.peerConnection_.getSenders()[0].transport}else{if(!Vd()||0===this.peerConnection_.getReceivers().length)return"unknown";e=this.peerConnection_.getReceivers()[0].transport}return e?e.state:"unknown"}onConnectionStateChange(e){const t=this.peerConnection_.iceConnectionState,i=this.getDTLSTransportState();if(this.log_.info("onConnectionStateChange() connectionState: "+e.target.connectionState),this.log_.info(`ICE Transport state: ${t}, DTLS Transport state: ${i}`),e.target.connectionState===me&&this.emitConnectionStateChangedEvent(le),e.target.connectionState===pe||e.target.connectionState===ge){const s=`${this.isUplink_?"uplink":"downlink"} ICE/DTLS Transport connection ${e.target.connectionState}. ICE Transport state: ${t}, DTLS Transport state: ${i}`,n=new gr({message:s,code:pr.ICE_TRANSPORT_ERROR});sd.logFailedEvent({userId:this.client_.getUserId(),eventType:Ve,error:n}),this.emitConnectionStateChangedEvent(ce),this.isErrorObserved_||this.emitter_.emit(tc.ERROR,n)}e.target.connectionState!==fe&&e.target.connectionState!==ve||(this.logSelectedCandidate(),sd.logSuccessEvent({userId:this.client_.getUserId(),eventType:Ve}),this.emitConnectionStateChangedEvent(ue))}emitConnectionStateChangedEvent(e){e!==this.currentState_&&(this.currentState_===he&&e===le||(La.emit(wo,{client:this.client_,connection:this,prevState:this.currentState_,state:e}),this.emitter_.emit(tc.CONNECTION_STATE_CHANGED,{prevState:this.currentState_,state:e}),this.currentState_=e))}hitTest(e){return(0===e||"0"===e)&&this.isUplink_||e===this.tinyId_}addEventInternal(e,t){const i=this.client_.getUserId();let n={eventId:e,eventDesc:t,timestamp:s(),userId:i,tinyId:this.client_.getTinyId()};this.isUplink_||(n.remoteUserId=this.userId_,n.remoteTinyId=this.tinyId_),ed(i,n)}getPeerConnection(){return this.peerConnection_}getClient(){return this.client_}getUserId(){return this.userId_}getTinyId(){return this.tinyId_}async logSelectedCandidate(){if(!this.peerConnection_)return;const e=await this.peerConnection_.getStats();for(let[t,i]of e)if(Wd(i)){const t=e.get(i.localCandidateId),s=e.get(i.remoteCandidateId);t&&this.log_.info(`local candidate: ${t.candidateType} ${t.protocol}:${t.ip||t.address}:${t.port} ${t.networkType||""} ${"relay"===t.candidateType?"relayProtocol:"+t.relayProtocol:""}`),s&&this.log_.info(`remote candidate: ${s.candidateType} ${s.protocol}:${s.ip||s.address}:${s.port}`);break}}getCurrentState(){return this.currentState_}waitForPeerConnectionConnected(){return this.waitForPeerConnectionConnectedPromise_||(this.waitForPeerConnectionConnectedPromise_=new Promise(((e,t)=>{if(this.currentState_===ue)return e();let i=-1;const s=t=>{t.state===ue&&(clearTimeout(i),a(),e())},n=({client:e})=>{e===this.client_&&(clearTimeout(i),a(),t(new gr({code:pr.API_CALL_ABORTED,message:ta({key:Us,data:"leave room"})})))},a=()=>{La.off(Ha,n,this),this.emitter_.off(tc.CONNECTION_STATE_CHANGED,s,this)};i=setTimeout((()=>{a();let e=new gr({code:pr.API_CALL_TIMEOUT,message:"connection timeout"});t(e)}),1e4),La.on(Ha,n,this),this.emitter_.on(tc.CONNECTION_STATE_CHANGED,s,this)})),this.waitForPeerConnectionConnectedPromise_=this.waitForPeerConnectionConnectedPromise_.then((e=>(this.waitForPeerConnectionConnectedPromise_=null,e))).catch((e=>{throw this.waitForPeerConnectionConnectedPromise_=null,e}))),this.waitForPeerConnectionConnectedPromise_}getReconnectionCount(){return this.reconnectionCount_}startReconnection(){this.isReconnecting_=!0,this.emitConnectionStateChangedEvent(he),this.reconnect(),this.addEventInternal(this.isUplink_?Wr:qr,(this.isUplink_?"uplink":"downlink")+"-connection is reconnecting")}stopReconnection(){this.log_.info("stop reconnection"),this.isReconnecting_=!1,this.reconnectionCount_=0,this.clearReconnectionTimer(),this.signalChannel_.off(Fo,this.reconnect,this)}on(e,t,i){this.emitter_.on(e,t,i)}off(e,t,i){this.emitter_.off(e,t,i)}setDelay({audioDelay:e,videoDelay:t}){this.delay_={audioDelay:e,videoDelay:t}}getDelay(){return this.delay_}get isH264(){var e,t;return!(null===(e=this.peerConnection_)||void 0===e||null===(t=e.remoteDescription)||void 0===t||!t.sdp.includes("H264"))}}var Vc=new class{constructor(){this.set_=new Set,La.on(Oa,this.add,this),La.on(xa,this.add,this),La.on($a,this.delete,this),La.on(Ha,this.delete,this)}add({client:e,roomId:t}){const i=this.getKey(e.getUserId(),t||e.getRoomId(),e.getSDKAppId(),e.getUseStringRoomId());this.set_.add(i)}delete({client:e}){const t=this.getKey(e.getUserId(),e.getRoomId(),e.getSDKAppId(),e.getUseStringRoomId());this.set_.delete(t)}getKey(e,t,i,s){return`${i}_${t}_${e}_${s}`}isJoined({userId:e,roomId:t,sdkAppId:i,client:s}){return this.set_.has(this.getKey(e,t,i,s.getUseStringRoomId()))}};function Uc(e,t,i,s){if(this.useStringRoomId_){if(!(ha(e)&&/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(e)))throw new gr({code:pr.INVALID_PARAMETER,message:ta({key:ii,data:t,link:{className:s,fnName:i}})})}else{if(!(ua(e)&&/^[1-9]\d*$/.test(String(e))&&e<4294967295))throw new gr({code:pr.INVALID_PARAMETER,message:ta({key:si,data:t,link:{className:s,fnName:i}})})}}function xc(e,t,i,s){if(!/^[A-Za-z\d_-]*$/.test(e))throw new gr({code:pr.INVALID_PARAMETER,message:ta({key:Ti,data:t,link:{className:s,fnName:i}})})}var $c,Fc,Bc={TRTC:{createClient:{name:"clientConfig",required:!0,type:tt,properties:{sdkAppId:{required:!0,type:Ye,allowEmpty:!1},userId:{required:!0,type:Xe,allowEmpty:!1},userSig:{required:!0,type:Xe,allowEmpty:!1},mode:{required:!0,type:Xe,values:["rtc","live"]},useStringRoomId:{type:Ze},autoSubscribe:{type:Ze},enableAutoPlayDialog:{type:Ze},streamId:{type:Xe},userDefineRecordId:{type:Xe},pureAudioPushMode:{type:Ye,values:[1,2]},enableSEI:{type:Ze}}},createStream:{name:"streamConfig",required:!0,type:tt,properties:{userId:{type:Xe},audio:{type:Ze},video:{type:Ze},screen:{type:Ze},screenAudio:{type:Ze},microphoneId:{type:Xe},cameraId:{type:Xe},facingMode:{type:[Xe,tt]},audioSource:{instanceOf:window.MediaStreamTrack},videoSource:{instanceOf:window.MediaStreamTrack}},validate(e){if(!la(e.screen)&&e.screen&&la(e.audio)&&(e.audio=!1),!(la(e.audio)&&la(e.video)||la(e.audioSource)&&la(e.videoSource)))throw new gr({code:pr.INVALID_PARAMETER,message:ta({key:ls})});if(!la(e.screen)&&!0===e.screen&&!0===e.video)throw new gr({code:pr.INVALID_PARAMETER,message:ta({key:hs})});if(e.audio&&e.screenAudio)throw new gr({code:pr.INVALID_PARAMETER,message:ta({key:us})});if(!0!==e.screen&&!0===e.screenAudio)throw new gr({code:pr.INVALID_PARAMETER,message:ta({key:_s})});if(!la(e.screen)&&!0===e.screen&&!this.isScreenShareSupported())throw new gr({code:pr.INVALID_OPERATION,message:ta({key:ys})})}}},CLIENT:{join:{name:"options",required:!0,type:tt,properties:{roomId:{required:!0,type:[Ye,Xe],allowEmpty:!1,validate:Uc},role:{type:[Xe],values:["anchor","audience"]},privateMapKey:{type:[Xe]}},validate(e){if(this.isJoined_)throw new gr({code:pr.INVALID_OPERATION,message:ta({key:ti})});if(this.checkDestroy(),Vc.isJoined({userId:this.userId_,roomId:e.roomId,sdkAppId:this.sdkAppId_,client:this}))throw new gr({code:pr.INVALID_OPERATION,message:ta({key:Ki,data:this.userId_})})}},publish:[{name:"stream",required:!0,instanceOf:St,validate(e){if(!this.isJoined_)throw new gr({code:pr.INVALID_OPERATION,message:ta({key:di})});if("live"===this.mode_&&"audience"===this.role_)throw new gr({code:pr.INVALID_OPERATION,message:ta({key:li})});if(!e.getIsReadyToPublish())throw new gr({code:pr.INVALID_OPERATION,message:ta({key:hi})});if(this.notPublishWithoutH264Supported_)throw new gr({code:pr.NOT_SUPPORTED_H264,message:ta({key:Ss})})}},{name:"options",type:tt,defaultValue:{isAuxiliary:!1},properties:{isAuxiliary:{type:Ze,defaultValue:!1,validate(e=!1){if(e&&!$d())throw new gr({code:pr.NOT_SUPPORTED,message:ta({key:Ts})});if(this.uplinkConnection_&&(e&&this.uplinkConnection_.isAuxStreamPublished||!e&&this.uplinkConnection_.isMainStreamPublished))throw new gr({code:pr.INVALID_OPERATION,message:ta({key:ui,data:e?h:"local"})});const t=this.localScreenStream_||[...this.connections_.values()].findIndex((e=>e.getTrackState().auxiliary))>=0;if(!this.enableMultiAuxStream_&&e&&t)throw new gr({code:pr.INVALID_OPERATION,message:ta({key:$s})})}}}}],unpublish:{name:"stream",required:!0,instanceOf:St,validate(e){if(e!==this.localStream_&&e!==this.localAuxStream_){if(this.localStream_||this.localAuxStream_)throw new gr({code:pr.INVALID_PARAMETER,message:ta({key:ci})});this.log_.warn("Client currently has no published stream, please call publish() first.")}}},subscribe:[{name:"stream",required:!0,instanceOf:ft,validate(e){if(!e.getConnection())throw new gr({code:pr.INVALID_OPERATION,message:ta({key:_i})});if(this.notSubscribeWithoutH264Supported_)throw new gr({code:pr.NOT_SUPPORTED_H264,message:ta({key:fs})})}},{name:"options",type:tt,properties:{audio:{type:Ze},video:{type:Ze},smallVideo:{type:Ze}},validate({audio:e,video:t,smallVideo:i}){if(!1===e&&!1===t&&(la(i)||!1===i))throw new gr({code:pr.INVALID_OPERATION,message:ta({key:Cs})})}}],unsubscribe:{name:"stream",required:!0,instanceOf:ft,validate(e){if(!e.getConnection())throw new gr({code:pr.INVALID_OPERATION,message:ta({key:_i})})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(){if("live"!==this.mode_)throw new gr({code:pr.INVALID_PARAMETER,message:ta({key:pi})});if(!this.isJoined_)throw new gr({code:pr.INVALID_OPERATION,message:ta({key:gi})})}},startPublishCDNStream:{name:"options",required:!1,properties:{streamId:{type:Xe,validate:xc},streamType:{type:Xe,values:["main","auxiliary"]},appId:{type:Ye,allowEmpty:!1},bizId:{type:Ye,allowEmpty:!1},url:{type:Xe,allowEmpty:!1}},validate(){if(this.isDestroyed_)throw new gr({code:pr.INVALID_OPERATION,message:ta({key:Qi,data:{funName:"startPublishCDNStream"}})})}},startMixTranscode:{name:"config",required:!0,type:tt,properties:{mode:{type:Xe,values:["preset-layout","manual"]},streamId:{type:Xe,validate:xc},videoWidth:{type:Ye,notLessThanZero:!0},videoHeight:{type:Ye,notLessThanZero:!0},videoBitrate:{type:Ye,notLessThanZero:!0,allowEmpty:!1},videoFramerate:{type:Ye,validate(e,t,i,s){if(e<=0||e>30)throw new gr({code:pr.INVALID_PARAMETER,message:ta({key:ts,link:{className:s,fnName:i}})})}},videoGOP:{type:Ye,validate(e,t,i,s){if(e<1||e>8)throw new gr({code:pr.INVALID_PARAMETER,message:ta({key:is,link:{className:s,fnName:i}})})}},audioSampleRate:{type:Ye,notLessThanZero:!0},audioBitrate:{type:Ye,validate(e,t,i,s){if(e<32||e>192)throw new gr({code:pr.INVALID_PARAMETER,message:ta({key:ss,link:{className:s,fnName:i}})})}},audioChannels:{type:Ye,values:[1,2]},backgroundColor:{type:Ye},backgroundImage:{type:Xe},mixUsers:{required:!0,type:et,arrayItem:{require:!0,type:tt,properties:{userId:{required:!0,type:Xe},roomId:{type:[Xe,Ye],validate:Uc},pureAudio:{type:Ze},width:{type:Ye,notLessThanZero:!0},height:{type:Ye,notLessThanZero:!0},locationX:{type:Ye,notLessThanZero:!0},locationY:{type:Ye,notLessThanZero:!0},zOrder:{type:Ye},streamType:{type:Xe,values:["main","auxiliary"]},renderMode:{type:Ye,values:[0,1,2,4]}}}}},validate(e,t,i,s,n){let a=0,o=0;const r=e.mixUsers,d=[];if(r.forEach(((e,t)=>{if(d.push(e.userId),!e.pureAudio){if(!e.zOrder||e.zOrder<1||e.zOrder>15)throw new gr({code:pr.INVALID_PARAMETER,message:ta({key:ns,data:`config.mixUsers[${t}].zOrder`,link:{className:s,fnName:i}})});e.width+e.locationX>a&&(a=e.width+e.locationX),e.height+e.locationY>o&&(o=e.height+e.locationY)}})),d.indexOf(this.getUserId())<0)throw new gr({code:pr.INVALID_PARAMETER,message:ta({key:as,link:{className:s,fnName:i}})});if(e.videoWidth1e3)throw new gr({code:pr.INVALID_PARAMETER,message:ta({key:Ms,data:e.byteLength})});if(0===e.byteLength)throw new gr({code:pr.INVALID_PARAMETER,message:ta({key:Ps})});if(!this.uplinkConnection_||!this.localStream_)throw new gr({code:pr.INVALID_PARAMETER,message:ta({key:Ls})});if(!this.localStream_.hasVideo())throw new gr({code:pr.INVALID_OPERATION,message:ta({key:Os})});const t=this.uplinkConnection_.isH264;if(!t)throw new gr({code:pr.NOT_SUPPORTED,message:ta({key:Ds,data:t})})}},{name:"options",type:tt,properties:{seiPayloadType:{type:Ye,values:[5,243]}}}]},LOCAL_STREAM:{switchDevice:[{name:"type",required:!0,type:Xe,values:[o,r]},{name:"deviceId",required:!0,type:Xe,validate(){if(this.screen_&&!this.audio_||this.audioSource_||this.videoSource_)throw new gr({code:pr.INVALID_OPERATION,message:ta({key:Mi})});if(this.publishState_===at)throw new gr({code:pr.INVALID_OPERATION,message:ta({key:Li})});if(!Fd())throw new gr({code:pr.NOT_SUPPORTED,message:ta({key:Is})})}}],setAudioCaptureVolume:{name:"volume",type:Ye}},STREAM:{play:[{name:"elementId",required:!0,type:[Xe,"HTMLDivElement"],validate(e,t,i){if(ha(e)){const s=document.getElementById(e);if(!s)throw new gr({code:pr.INVALID_PARAMETER,message:ta({key:rs,data:{key:t,fnName:i}})});if(!(s instanceof HTMLDivElement))throw new gr({code:pr.INVALID_PARAMETER,message:ta({key:ds,data:{key:t,fnName:i,type:Sa(s)}})})}}},{name:"options",type:tt,properties:{objectFit:{type:Xe,values:["contain","cover","fill"]},muted:{type:Ze},mirror:{type:Ze}}}],addTrack:{name:j,instanceOf:window.MediaStreamTrack,validate(e){if(this.isAddingTrack_)throw new gr({code:pr.INVALID_OPERATION,message:ta({key:Ui})});if(this.isRemovingTrack_)throw new gr({code:pr.INVALID_OPERATION,message:ta({key:xi})});if(this.publishState_===at)throw new gr({code:pr.INVALID_OPERATION,message:ta({key:$i})});const t=this.getMediaStream();if(!t)throw new gr({code:pr.INVALID_OPERATION,message:ta({key:Fi})});if(e.kind===o&&t.getAudioTracks().length>0||e.kind===r&&t.getVideoTracks().length>0)throw new gr({code:pr.INVALID_OPERATION,message:ta({key:Bi})});if(!xd()&&!Ud())throw new gr({code:pr.NOT_SUPPORTED,message:ta({key:vs,data:F})})}},removeTrack:{name:j,instanceOf:window.MediaStreamTrack,validate(e){if(this.isAddingTrack_)throw new gr({code:pr.INVALID_OPERATION,message:ta({key:ji})});if(this.isRemovingTrack_)throw new gr({code:pr.INVALID_OPERATION,message:ta({key:Ji})});if(this.publishState_===at)throw new gr({code:pr.INVALID_OPERATION,message:ta({key:Wi})});const t=this.getMediaStream();if(!t)throw new gr({code:pr.INVALID_OPERATION,message:ta({key:Fi})});if(-1===t.getTracks().indexOf(e))throw new gr({code:pr.INVALID_PARAMETER,message:ta({key:Gi})});if(!xd()){if(1===t.getTracks().length)throw new gr({code:pr.INVALID_OPERATION,message:ta({key:zi})});if(e.kind===o)throw new gr({code:pr.INVALID_PARAMETER,message:ta({key:Hi})});if(!Ud())throw new gr({code:pr.NOT_SUPPORTED,message:ta({key:vs,data:B})})}}},replaceTrack:{name:j,instanceOf:window.MediaStreamTrack,validate(e){const t=this.getMediaStream();if(!t)throw new gr({code:pr.INVALID_OPERATION,message:ta({key:Vi})});if(this.publishState_===at)throw new gr({code:pr.INVALID_OPERATION,message:ta({key:Oi})});if(e.kind===o&&t.getAudioTracks().length<=0||e.kind===r&&t.getVideoTracks().length<=0)throw new gr({code:pr.INVALID_PARAMETER,message:ta({key:qi,data:e})});if(!Fd())throw new gr({code:pr.NOT_SUPPORTED,message:ta({key:vs,data:H})})}}}};function Hc(...e){return function(t,i,s){const n=s.value;return s.value=function(...t){return Jc.call(this,e,t,i,this.name_),n.apply(this,t)},s}}function jc(...e){return function(t,i,s){const n=s.value;return s.value=async function(...t){return Jc.call(this,e,t,i,this.name_),n.apply(this,t)},s}}function Jc(e,t,i,s){try{for(let n=0;ne.toLowerCase())).includes(Sa(t)))throw new gr({code:pr.INVALID_PARAMETER,message:ta({key:xt,data:{key:i,rule:e,fnName:s,value:t},link:{className:n,fnName:s}})})}else if(!la(e.type)&&Sa(t)!==e.type)throw new gr({code:pr.INVALID_PARAMETER,message:ta({key:xt,data:{key:i,rule:e,fnName:s,value:t},link:{className:n,fnName:s}})});if(!1===e.allowEmpty){const a=ua(t)&&(0===t||Number.isNaN(t)),o=ha(t)&&""===t.trim();if(a||o)throw new gr({code:pr.INVALID_PARAMETER,message:ta({key:$t,data:{key:i,rule:e,fnName:s,value:t},link:{className:n,fnName:s}})})}if(e.notLessThanZero&&ua(t)&&t<0)throw new gr({code:pr.INVALID_PARAMETER,message:ta({key:es,data:{key:i,rule:e,fnName:s,value:t},link:{className:n,fnName:s}})});if(ha(e.instanceOf)){if(!t||t.name_!==e.instanceOf)throw new gr({code:pr.INVALID_PARAMETER,message:ta({key:Ft,data:{key:i,rule:e,fnName:s,value:t},link:{className:n,fnName:s}})})}else if(ca(e.instanceOf)&&!(t instanceof e.instanceOf))throw new gr({code:pr.INVALID_PARAMETER,message:ta({key:Ft,data:{key:i,rule:e,fnName:s,value:t},link:{className:n,fnName:s}})});if(e.values&&!e.values.includes(t))throw new gr({code:pr.INVALID_PARAMETER,message:ta({key:Bt,data:{key:i,rule:e,fnName:s,value:t},link:{className:n,fnName:s}})});const{properties:a}=e;oa(a)&&ma(t)&&Object.keys(a).forEach((e=>{Wc.call(this,{rule:a[e],value:t&&t[e],key:`${i}.${e}`,fnName:s,className:n})}));const{arrayItem:o}=e;oa(o)&&pa(t)&&t.forEach(((e,t)=>{Wc.call(this,{rule:o,value:e,key:`${i}[${t}]`,fnName:s,className:n})})),ca(e.validate)&&e.validate.call(this,t,i,s,n,this)}function Gc(e={retries:5,timeout:2e3}){return function(t,i,s){const n=No({retryFunction:s.value,settings:e,onError:e.onError,onRetrying:e.onRetrying,onRetryFailed:e.onRetryFailed});return s.value=function(...e){return n.apply(this,e)},s}}const zc={msg_user_info:0,uint32_video_avg_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_avg_bitrate:0,uint32_video_block_time:0,uint32_video_play_time:0,uint32_audio_block_time:0,uint32_audio_play_time:0,uint32_audio_play_db:0,uint32_avg_down_loss:0,uint32_stream_type:0,uint32_video_render_first:0,uint32_video_block_count:0,uint32_audio_block_count:0,uint32_audio_bitrate:0,uint32_video_black_screen_subjective:0,uint32_audio_recv_bitrate:0,uint32_video_external_block_time:0};class qc{constructor(e){this.str_identifier=String(e.userId),this.uint64_tinyid=Number(e.tinyId),this.uint32_role=e.role}}let Kc=($c=Gc({timeout:500,retries:3}),Fc=class{constructor(e){this.frameWorkType_=e.frameWorkType||30,this.component_=e.component||0,this.client_=e.client,this.keyPrefix_="key_point",this.storageKey_=`${this.keyPrefix_}_${this.client_.getUserId()}`,this.log_=Oo.createLogger({id:"kpm|"+this.client_.getUserId(),userId:this.client_.getUserId(),sdkAppId:this.client_.getSDKAppId()}),Object.getOwnPropertyNames(this.__proto__).forEach((e=>{e.startsWith("handle")&&ca(this[e])&&(this[e]=function({fn:e,context:t}){return async function(...i){try{return await e.apply(t||this,i)}catch(s){Oo.error(`${e.name}() error observed `+s)}}}({fn:this[e],context:this}))})),this.initData(),this.installEvents(),this.intervalId_=kd.run(Pt,this.setStorage.bind(this),{delay:2e4})}initData(){var e;this.firstPublishedUserList_=[],this.networkQuality_={totalUplinkRTT:0,totalUplinkLoss:0,count:0,totalDownlinkRTTAndLossMap:new Map},this.basicInfo={string_sdk_version:"4.15.19",uint32_os_type:15,string_device_name:"",string_http_user_agent:navigator.userAgent,string_os_version:"",string_domain:location.host,uint32_avg_rtt:0,uint32_avg_up_loss:0,uint32_scene:"live"===(null===(e=this.client_)||void 0===e?void 0:e.getMode())?1:0,uint32_joining_duration:0,uint32_networkType:st[aa()],uint32_framework:this.frameWorkType_,uint32_component:this.component_},this.pathJoinRoom_={uint64_start_time:0,uint64_init_audio_start_time:0,uint64_init_audio_end_time:0,uint64_init_camera_start_time:0,uint64_init_camera_end_time:0,uint64_send_request_acc_ip_cmd_start_time:0,uint64_send_request_acc_ip_cmd_end_time:0,uint64_send_request_enter_room_cmd_start_time:0,uint64_send_request_enter_room_cmd_end_time:0,uint64_send_first_video_frame_time:0,uint64_recv_userlist_time:0,uint64_end_time:0,int32_init_audio_ret:0,int32_init_camera_ret:0,int32_send_request_acc_ip_cmd_ret:0,int32_send_request_enter_room_cmd_ret:0,int32_end_ret:0},this.pathLeaveRoom_={uint64_start_time:0,uint64_send_request_exit_room_cmd_start_time:0,uint64_send_request_exit_room_cmd_end_time:0,uint64_end_time:0,int32_send_request_exit_room_cmd_ret:0,int32_end_ret:0},this.pathMainVideoMap_=new Map,this.pathMainAudioMap_=new Map,this.pathAuxiliaryMap_=new Map,this.localStreamStats_={totalVideoBitrate:0,totalVideoFPS:0,totalVideoHeight:0,totalVideoWidth:0,totalAudioLevel:0,videoCount:0,audioLevelCount:0,publishStartTime:0,statsToReport:{uint32_audio_capture_db:0,uint32_video_big_capture_fps:0,uint32_video_big_bitrate:0,uint32_video_big_resolution:0}},this.remoteStreamStatsMap_=new Map}installEvents(){La.on(Oa,this.handleJoinStart,this),La.on(Ga,this.handleWSStart,this),La.on(za,this.handleWSEnd,this),La.on(Va,this.handleJoinSendCMD,this),La.on(Ua,this.handleJoinReceivedCMDResponce,this),La.on(xa,this.handleJoinSuccess,this),La.on($a,this.handleJoinFailed,this),La.on(Ja,this.handleReceivedPublishUserList,this),La.on(wo,this.handleConnectionStateChanged,this),La.on(Fa,this.handleLeaveStart,this),La.on(Ha,this.handleLeaveSuccess,this),La.on(Ba,this.handleLeaveSendCMD,this),La.on(ko,this.handleSendSubscribeCMD,this),La.on(so,this.handleVideoPlaying,this),La.on(no,this.handleAudioPlaying,this),La.on(Ro,this.handleNetworkQuality,this),La.on(ja,this.handleHeartbeatStats,this),La.on(oo,this.handleRemoteStreamAdded,this),La.on(ro,this.handleRemoteStreamSubscribeStart,this),La.on(co,this.handleRemoteStreamSubscribed,this),La.on(uo,this.handleRemoteStreamRemoved,this),La.on(Io,this.handleVideoLoadedData,this),La.on(vo,this.handlePlayStream,this),La.on(Wa,this.handlePublishStart,this),La.on(mo,this.handleLocalStreamInitStart,this),La.on(po,this.handleLocalStreamInitEnd,this),La.on(go,this.handleLocalStreamInitFailed,this)}uninstallEvents(){La.off(Oa,this.handleJoinStart,this),La.off(Ga,this.handleWSStart,this),La.off(za,this.handleWSEnd,this),La.off(Va,this.handleJoinSendCMD,this),La.off(Ua,this.handleJoinReceivedCMDResponce,this),La.off(Ja,this.handleReceivedPublishUserList,this),La.off(wo,this.handleConnectionStateChanged,this),La.off(Fa,this.handleLeaveStart,this),La.off(Ha,this.handleLeaveSuccess,this),La.off(xa,this.handleJoinSuccess,this),La.off($a,this.handleJoinFailed,this),La.off(Ba,this.handleLeaveSendCMD,this),La.off(ko,this.handleSendSubscribeCMD,this),La.off(so,this.handleVideoPlaying,this),La.off(no,this.handleAudioPlaying,this),La.off(Ro,this.handleNetworkQuality,this),La.off(ja,this.handleHeartbeatStats,this),La.off(oo,this.handleRemoteStreamAdded,this),La.off(ro,this.handleRemoteStreamSubscribeStart,this),La.off(co,this.handleRemoteStreamSubscribed,this),La.off(uo,this.handleRemoteStreamRemoved,this),La.off(Io,this.handleVideoLoadedData,this),La.off(vo,this.handlePlayStream,this),La.off(Wa,this.handlePublishStart,this),La.off(mo,this.handleLocalStreamInitStart,this),La.off(po,this.handleLocalStreamInitEnd,this),La.off(go,this.handleLocalStreamInitFailed,this)}destroy(){this.uninstallEvents(),kd.clearTask(this.intervalId_),this.client_=null}handleJoinStart(e){this.hitTest(e.client)&&0===this.pathJoinRoom_.uint64_start_time&&(this.pathJoinRoom_.uint64_start_time=Date.now(),this.checkStorage())}handleWSStart({client:e}){this.hitTest(e)&&0===this.pathJoinRoom_.uint64_send_request_acc_ip_cmd_start_time&&(this.pathJoinRoom_.uint64_send_request_acc_ip_cmd_start_time=Date.now())}handleWSEnd({client:e,error:t}){this.hitTest(e)&&0===this.pathJoinRoom_.uint64_send_request_acc_ip_cmd_end_time&&(this.pathJoinRoom_.uint64_send_request_acc_ip_cmd_end_time=Date.now(),t&&(this.pathJoinRoom_.int32_send_request_acc_ip_cmd_ret=t instanceof gr?Number(t.getExtraCode()||t.getCode()):pr.UNKNOWN,this.pathJoinRoom_.int32_end_ret=2))}handleJoinSendCMD(e){this.hitTest(e.client)&&0===this.pathJoinRoom_.uint64_send_request_enter_room_cmd_start_time&&(this.pathJoinRoom_.uint64_send_request_enter_room_cmd_start_time=Date.now())}handleJoinReceivedCMDResponce(e){this.hitTest(e.client)&&0===this.pathJoinRoom_.uint64_send_request_enter_room_cmd_end_time&&(this.pathJoinRoom_.uint64_send_request_enter_room_cmd_end_time=Date.now(),this.pathJoinRoom_.int32_send_request_enter_room_cmd_ret=e.code,0!==e.code&&(this.pathJoinRoom_.int32_end_ret=3))}handleJoinSuccess(e){this.hitTest(e.client)&&0===this.pathJoinRoom_.uint64_end_time&&(this.pathJoinRoom_.uint64_end_time=Date.now(),this.pathJoinRoom_.int32_end_ret=0)}handleJoinFailed({client:e}){this.hitTest(e)&&(this.pathJoinRoom_.uint64_end_time=Date.now(),0===this.pathJoinRoom_.int32_end_ret&&(this.pathJoinRoom_.int32_end_ret=3),this.prepareReport(),this.report())}handleReceivedPublishUserList(e){this.hitTest(e.client)&&0===this.pathJoinRoom_.uint64_recv_userlist_time&&(this.pathJoinRoom_.uint64_recv_userlist_time=Date.now(),this.firstPublishedUserList_=e.data.data&&e.data.data.userList||[])}handleConnectionStateChanged({client:e,state:t,connection:i}){if(this.hitTest(e)&&t===ue){this.client_.getUplinkConnection()===i&&0===this.pathJoinRoom_.uint64_send_first_video_frame_time&&this.localStreamStats_.publishStartTime>this.pathJoinRoom_.uint64_end_time&&this.localStreamStats_.publishStartTime-this.pathJoinRoom_.uint64_end_time<=100&&(this.pathJoinRoom_.uint64_send_first_video_frame_time=Date.now());const e=this.pathMainVideoMap_.get(`${i.getUserId()}_${re}`);e&&0===e.statsToReport.uint64_pc_connected_time&&(e.statsToReport.uint64_pc_connected_time=Date.now())}}handleLeaveStart(e){this.hitTest(e.client)&&(this.pathLeaveRoom_.uint64_start_time=Date.now())}handleLeaveSuccess(e){this.hitTest(e.client)&&0===this.pathLeaveRoom_.uint64_end_time&&(this.pathLeaveRoom_.uint64_end_time=Date.now(),0!==this.pathJoinRoom_.uint64_end_time?this.basicInfo.uint32_joining_duration=this.pathLeaveRoom_.uint64_end_time-this.pathJoinRoom_.uint64_end_time:this.log_.warn("pathJoinRoom endTime is 0"),this.report())}handleLeaveSendCMD(e){this.hitTest(e.client)&&(this.pathLeaveRoom_.uint64_send_request_exit_room_cmd_start_time=Date.now(),this.pathLeaveRoom_.uint64_send_request_exit_room_cmd_end_time=Date.now())}handleRemoteStreamAdded({client:e,stream:t}){if(this.hitTest(e)){const e=t.getUserId(),i=t.getType(),s=`${e}_${i}`,n=this.remoteStreamStatsMap_.get(s);if(n)n.stream=t;else{const n={userId:e,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:{...zc},stream:t};n.statsToReport.msg_user_info=new qc({userId:e,tinyId:t.getTinyId(),role:ie}),n.statsToReport.uint32_stream_type=i===re?2:7,this.remoteStreamStatsMap_.set(s,n)}}}handleRemoteStreamSubscribeStart({client:e,stream:t}){if(this.hitTest(e)){const e=`${t.getUserId()}_${t.getType()}`,i=this.remoteStreamStatsMap_.get(e);i&&0===i.subscribeStartTime&&(i.subscribeStartTime=Date.now())}}handleSendSubscribeCMD(e){if(this.hitTest(e.client)){const t=new qc(e),i=Date.now(),s=`${e.userId}_${re}`;e.trackState.video&&e.subscribeState.video&&!this.pathMainVideoMap_.has(s)&&this.pathMainVideoMap_.set(s,{statsToReport:{msg_user_info:t,uint64_start_enter_time:this.pathJoinRoom_.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0,uint64_pc_connected_time:0},userId:e.userId,sendSubscribeCMDTime:i}),e.trackState.audio&&e.subscribeState.audio&&!this.pathMainAudioMap_.has(s)&&this.pathMainAudioMap_.set(s,{statsToReport:{msg_user_info:t,uint64_start_enter_time:this.pathJoinRoom_.uint64_start_time,uint64_play_first_frame_time:0},userId:e.userId,sendSubscribeCMDTime:i});const n=`${e.userId}_${de}`;e.trackState.auxiliary&&e.subscribeState.auxiliary&&!this.pathAuxiliaryMap_.has(n)&&this.pathAuxiliaryMap_.set(n,{sendSubscribeCMDTime:i})}}handleRemoteStreamSubscribed({client:e,stream:t}){if(this.hitTest(e)){const e=`${t.getUserId()}_${t.getType()}`,i=this.remoteStreamStatsMap_.get(e);i&&0===i.subscribedTime&&(i.subscribedTime=Date.now(),i.stream=t)}}handleRemoteStreamRemoved({client:e,stream:t}){if(this.hitTest(e)){const e=t.getUserId(),i=t.getType(),s=this.remoteStreamStatsMap_.get(`${e}_${i}`);s&&(s.stream=null)}}handlePlayStream({stream:e}){if(!e.isRemote()||!e.getConnection()||!this.hitTest(e.getConnection().getClient()))return;const t=`${e.getConnection().getUserId()}_${e.getType()}`;if(this.remoteStreamStatsMap_.has(t)){const e=this.remoteStreamStatsMap_.get(t);0===e.playStreamTime&&(e.playStreamTime=Date.now())}}handleVideoLoadedData({stream:e}){if(!e.isRemote()||!e.getConnection()||!this.hitTest(e.getConnection().getClient()))return;const t=`${e.getConnection().getUserId()}_${e.getType()}`;if(this.pathMainVideoMap_.has(t)){const e=this.pathMainVideoMap_.get(t);0===e.statsToReport.uint64_combine_first_frame_time&&(e.statsToReport.uint64_combine_first_frame_time=Date.now())}}handleVideoPlaying({stream:e}){if(!e.isRemote()||!e.getConnection()||!this.hitTest(e.getConnection().getClient()))return;const t=`${e.getConnection().getUserId()}_${e.getType()}`,i=Date.now();if(this.pathMainVideoMap_.has(t)){const e=this.pathMainVideoMap_.get(t);if(0===e.statsToReport.uint64_render_first_frame_time&&(e.statsToReport.uint64_render_first_frame_time=i),this.remoteStreamStatsMap_.has(t)){const{statsToReport:s,playStreamTime:n,subscribedTime:a}=this.remoteStreamStatsMap_.get(t);0===s.uint32_video_render_first&&n-a<=100&&(s.uint32_video_render_first=i-e.sendSubscribeCMDTime)}}if(e.getType()===de&&this.pathAuxiliaryMap_.has(t)&&this.remoteStreamStatsMap_.has(t)){const{statsToReport:e,playStreamTime:s,subscribedTime:n}=this.remoteStreamStatsMap_.get(t);0===e.uint32_video_render_first&&s-n<=100&&(e.uint32_video_render_first=i-this.pathAuxiliaryMap_.get(t).sendSubscribeCMDTime)}}handleAudioPlaying(e){if(!e.stream.isRemote()||!e.stream.getConnection()||!this.hitTest(e.stream.getConnection().getClient()))return;const t=`${e.stream.getConnection().getUserId()}_${e.stream.getType()}`;if(this.pathMainAudioMap_.has(t)){const e=this.pathMainAudioMap_.get(t);0===e.statsToReport.uint64_play_first_frame_time&&(e.statsToReport.uint64_play_first_frame_time=Date.now())}}handleNetworkQuality(e){this.hitTest(e.client)&&(this.networkQuality_.totalUplinkLoss+=e.uplinkLoss,this.networkQuality_.totalUplinkRTT+=e.uplinkRTT,this.networkQuality_.count++,e.downlinkLossAndRTTMap.forEach((({rtt:e,loss:t,userId:i})=>{const s=this.networkQuality_.totalDownlinkRTTAndLossMap.get(i);s?(s.totalRTT+=e,s.totalLoss+=t,s.count++):this.networkQuality_.totalDownlinkRTTAndLossMap.set(i,{totalRTT:e,totalLoss:t,count:1})})))}handleHeartbeatStats(e){if(this.hitTest(e.client)){const{msg_up_stream_info:t,msg_down_stream_info:i}=e.stats;if(t.msg_video_status[0]){const{uint32_video_codec_bitrate:e,uint32_video_enc_fps:i,uint32_video_width:s,uint32_video_height:n}=t.msg_video_status[0];this.localStreamStats_.totalVideoBitrate+=e,this.localStreamStats_.totalVideoFPS+=i,this.localStreamStats_.totalVideoWidth+=s,this.localStreamStats_.totalVideoHeight+=n,this.localStreamStats_.videoCount++}if(t.msg_audio_status){const e=t.msg_audio_status.audioLevel;Math.floor(100*e)>0&&(this.localStreamStats_.totalAudioLevel+=e,this.localStreamStats_.audioLevelCount++)}i.forEach((e=>{const{msg_user_info:t,msg_audio_status:i,msg_video_status:s}=e,n=t.str_identifier;if(s.forEach((e=>{const t=2===e.uint32_video_stream_type,i=7===e.uint32_video_stream_type,s=`${n}_${t?re:de}`;if(this.remoteStreamStatsMap_.has(s)){var a,o;const n=this.remoteStreamStatsMap_.get(s);(t&&null!==(a=n.stream)&&void 0!==a&&a.isMainVideoSubscribed||i&&null!==(o=n.stream)&&void 0!==o&&o.isAuxVideoSubscribed)&&(n.totalVideoFPS+=e.uint32_video_receive_fps,n.totalVideoBitrate+=e.uint32_video_codec_bitrate,n.videoCount++,0===n.statsToReport.uint32_video_width&&(n.statsToReport.uint32_video_width=e.uint32_video_width),0===n.statsToReport.uint32_video_height&&(n.statsToReport.uint32_video_height=e.uint32_video_height))}})),i){const e=`${n}_${re}`;if(this.remoteStreamStatsMap_.has(e)){var a;const t=this.remoteStreamStatsMap_.get(e);null!==(a=t.stream)&&void 0!==a&&a.isMainAudioSubscribed&&(t.totalAudioBitrate+=i.uint32_audio_codec_bitrate,t.audioCount++,Math.floor(100*i.audioLevel)>0&&(t.totalAudioLevel+=i.audioLevel,t.audioLevelCount++))}}}))}}handlePublishStart({client:e}){this.hitTest(e)&&0===this.localStreamStats_.publishStartTime&&(this.localStreamStats_.publishStartTime=Date.now())}handleLocalStreamInitStart({audio:e,video:t}){e&&0===this.pathJoinRoom_.uint64_init_audio_start_time&&(this.pathJoinRoom_.uint64_init_audio_start_time=Date.now()),t&&0===this.pathJoinRoom_.uint64_init_camera_start_time&&(this.pathJoinRoom_.uint64_init_camera_start_time=Date.now())}handleLocalStreamInitEnd({audio:e,video:t}){e&&0===this.pathJoinRoom_.uint64_init_audio_end_time&&(this.pathJoinRoom_.uint64_init_audio_end_time=Date.now()),t&&0===this.pathJoinRoom_.uint64_init_camera_end_time&&(this.pathJoinRoom_.uint64_init_camera_end_time=Date.now())}handleLocalStreamInitFailed({audio:e,video:t,error:i}){const s=i instanceof gr?i.getExtraCode()||i.getCode():{NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5}[i.name]||pr.UNKNOWN;e&&0===this.pathJoinRoom_.uint64_init_audio_end_time&&(this.pathJoinRoom_.int32_init_audio_ret=s,this.pathJoinRoom_.uint64_init_audio_end_time=Date.now()),t&&0===this.pathJoinRoom_.uint64_init_camera_end_time&&(this.pathJoinRoom_.int32_init_camera_ret=s,this.pathJoinRoom_.uint64_init_camera_end_time=Date.now())}hasVideoFlag(e){return this.firstPublishedUserList_.findIndex((t=>t.userId===e&&1&t.flag))>=0}hasAudioFlag(e){return this.firstPublishedUserList_.findIndex((t=>t.userId===e&&8&t.flag))>=0}hasAuxFlag(e){return this.firstPublishedUserList_.findIndex((t=>t.userId===e&&4&t.flag))>=0}hitTest(e){return e===this.client_}async checkStorage(){try{const e=Rd.getItem(this.storageKey_);e&&(await this.upload(e),Rd.deleteItem(this.storageKey_))}catch(e){this.log_.warn(e)}}setStorage(){this.prepareReport();const e=this.getReportData();0!==e.msg_path_enter_room.uint64_start_time&&Rd.setItem(this.storageKey_,e)}prepareReport(){if(this.networkQuality_.count>0&&(this.basicInfo.uint32_avg_rtt=Math.floor(this.networkQuality_.totalUplinkRTT/this.networkQuality_.count),this.basicInfo.uint32_avg_up_loss=Math.floor(this.networkQuality_.totalUplinkLoss/this.networkQuality_.count)),this.localStreamStats_.videoCount>0){this.localStreamStats_.statsToReport.uint32_video_big_capture_fps=Math.floor(this.localStreamStats_.totalVideoFPS/this.localStreamStats_.videoCount),this.localStreamStats_.statsToReport.uint32_video_big_bitrate=Math.floor(this.localStreamStats_.totalVideoBitrate/this.localStreamStats_.videoCount);const e=Math.floor(this.localStreamStats_.totalVideoWidth/this.localStreamStats_.videoCount),t=Math.floor(this.localStreamStats_.totalVideoHeight/this.localStreamStats_.videoCount);this.localStreamStats_.statsToReport.uint32_video_big_resolution=e<<16|t}this.localStreamStats_.audioLevelCount>0&&(this.localStreamStats_.statsToReport.uint32_audio_capture_db=Math.floor(this.localStreamStats_.totalAudioLevel/this.localStreamStats_.audioLevelCount*100)),this.remoteStreamStatsMap_.forEach(((e,t)=>{const i=e.userId;if(this.networkQuality_.totalDownlinkRTTAndLossMap.has(i)){const{totalLoss:t,count:s}=this.networkQuality_.totalDownlinkRTTAndLossMap.get(i);e.statsToReport.uint32_avg_down_loss=Math.floor(t/s)}e.videoCount>0&&(e.statsToReport.uint32_video_avg_fps=Math.floor(e.totalVideoFPS/e.videoCount),e.statsToReport.uint32_video_avg_bitrate=Math.floor(e.totalVideoBitrate/e.videoCount)),e.audioCount>0&&(e.statsToReport.uint32_audio_recv_bitrate=e.statsToReport.uint32_audio_bitrate=Math.floor(e.totalAudioBitrate/e.audioCount)),e.audioLevelCount>0&&(e.statsToReport.uint32_audio_play_db=Math.floor(e.totalAudioLevel/e.audioLevelCount*100));const s=this.client_.getCallDurationCalculator();s&&(e.statsToReport.uint32_audio_play_time=s.getDuration(t,o),e.statsToReport.uint32_video_play_time=s.getDuration(t,r)),e.statsToReport.uint32_video_render_first=Math.min(e.statsToReport.uint32_video_render_first,5e3);const n=this.client_.getBadCaseDetector();if(n){const{dataFreeze:i,count:s}=n.getDataFreezeDuration(t),{renderFreeze:a}=n.getRenderFreezeDuration(t);e.statsToReport.uint32_video_block_count=s,e.statsToReport.uint32_video_block_time=Math.min(i,e.statsToReport.uint32_video_play_time),e.statsToReport.uint32_video_external_block_time=Math.min(a,e.statsToReport.uint32_video_play_time),n.isBlackStream(t)&&0===e.statsToReport.uint32_video_avg_fps?e.statsToReport.uint32_video_black_screen_subjective=1:e.statsToReport.uint32_video_black_screen_subjective=0}(0===e.subscribeStartTime||e.subscribeStartTime-e.streamAddedTime>100||0===e.playStreamTime)&&(this.pathMainAudioMap_.delete(t),this.pathMainVideoMap_.delete(t),e.statsToReport.uint32_video_render_first=0)})),this.pathMainAudioMap_.forEach(((e,t)=>{this.hasAudioFlag(e.userId)?e.statsToReport.uint64_play_first_frame_time-e.statsToReport.uint64_start_enter_time>5e3&&(e.statsToReport.uint64_play_first_frame_time=e.statsToReport.uint64_start_enter_time+5e3):this.pathMainAudioMap_.delete(t)})),this.pathMainVideoMap_.forEach(((e,t)=>{this.hasVideoFlag(e.userId)?e.statsToReport.uint64_render_first_frame_time-e.statsToReport.uint64_start_enter_time>5e3&&(e.statsToReport.uint64_render_first_frame_time=e.statsToReport.uint64_start_enter_time+5e3):this.pathMainVideoMap_.delete(t)})),this.pathJoinRoom_.uint64_end_time-this.pathJoinRoom_.uint64_start_time>5e3&&(this.pathJoinRoom_.uint64_end_time=this.pathJoinRoom_.uint64_start_time+5e3)}getReportData(){const e=this.client_.getSignalInfo();return{uint32_sdk_app_id:Number(this.client_.getSDKAppId()),msg_user_info:new qc({userId:this.client_.getUserId(),tinyId:this.client_.getTinyId(),role:"anchor"===this.client_.getRole()?ie:se}),msg_basic_info:this.basicInfo,uint32_acc_ip:Ia(e.relayIp),uint32_client_ip:Ia(e.clientIp,"small"),uint32_acc_port:0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*2**31),msg_path_enter_room:this.pathJoinRoom_,msg_path_exit_room:this.pathLeaveRoom_,msg_path_recv_video:[...this.pathMainVideoMap_.values()].map((e=>e.statsToReport)),msg_quality_statistics:[...this.remoteStreamStatsMap_.values()].map((e=>e.statsToReport)),str_room_name:String(this.client_.getRoomId()),msg_path_recv_audio:[...this.pathMainAudioMap_.values()].map((e=>e.statsToReport)),uint32_info_client_ip:Ia(e.clientIp,"small"),error_code:[],msg_local_statistics:this.localStreamStats_.statsToReport,msg_function_state:Qc.getStateArray()}}async report(){try{const e=this.getReportData();await this.upload(e),Rd.deleteItem(this.storageKey_),Qc.clearStateArray(),this.initData()}catch(e){this.log_.warn(e)}}async upload(e){if(Kn||0===e.msg_path_enter_room.uint64_start_time||[It,yt,Tt].findIndex((e=>e===location.host))>=0)return;const t=Number(this.client_.getSDKAppId()),i=na(t,Y),s=await Da({url:i,body:JSON.stringify(e)});if("ok"!==s.data)throw`key point upload failed: ${s.data}`}},e(Fc.prototype,"upload",[$c],Object.getOwnPropertyDescriptor(Fc.prototype,"upload"),Fc.prototype),Fc);class Qc{static stateMap=new Map;static handleFunctionState({className:e,fnName:t,params:i}){var s,n,a,o;if(Kn||[It,yt,Tt].findIndex((e=>e===location.host))>=0)return;let r,d=[];if(e)switch(t){case"createClient":null!==(s=i[0])&&void 0!==s&&s.mode&&d.push(`${e}.${t}.${i[0].mode}`),null!==(n=i[0])&&void 0!==n&&n.useStringRoomId?d.push(`${e}.${t}.stringRoomId`):d.push(`${e}.${t}.intRoomId`),null!==(a=i[0])&&void 0!==a&&a.autoSubscribe?d.push(`${e}.${t}.autoSubscribe`):d.push(`${e}.${t}.manualSubscribe`);break;case"publish":null!==(o=i[1])&&void 0!==o&&o.isAuxiliary?d.push(`${e}.${t}.isAuxiliary`):d.push(`${e}.${t}`);break;case"setAudioProfile":case"setVideoProfile":case"setScreenProfile":case"setVideoContentHint":ha(i[0])&&d.push(`${e}.${t}.${i[0]}`);break;default:d.push(`${e}.${t}`)}else d.push(t);for(let c=0;c{let t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)})),this.audioOutputDeviceId_=0,this.audioVolume_=1,this.emitter_=ka(new Ma,this.name_),this.connectionState_=ce,this.installEvents(),la(e.mirror)||this.log_.warn(`TRTC.createStream "mirror" option was deprecated since v4.12.1,please use localStream.play to set up preview mirror. refer to ${bt}/en/LocalStream.html#play. TRTC.createStream 接口的 mirror 选项从 v4.12.1 开始被废弃,请使用 localStream.play 设置本地流预览镜像,参考文档:${bt}/zh-cn/LocalStream.html#play。`)}installEvents(){La.on(Ao,this.restartPlayback,this)}uninstallEvents(){La.off(Ao,this.restartPlayback,this)}getType(){return this.type_}getLogger(){return this.log_}get isSubscribed(){return this.type_===re&&this.connection_.isMainStreamSubscribed||this.type_===de&&this.connection_.isAuxStreamSubscribed}get isMainVideoSubscribed(){const e=this.getSubscribedState();return this.type_===re&&e&&e.video}get isMainAudioSubscribed(){const e=this.getSubscribedState();return this.type_===re&&e&&e.audio}get isAuxVideoSubscribed(){const e=this.getSubscribedState();return this.type_===de&&e&&e.auxiliary}get isSmallVideoSubscribed(){const e=this.getSubscribedState();return this.type_===re&&e&&e.smallVideo}emitConnectionStateChanged(e){e.state!==this.connectionState_&&(e.state!==ce&&this.isRemote_&&!this.isSubscribed||(this.emitter_.emit(ac,e),this.connectionState_=e.state))}setConnection(e){this.connection_!==e&&(e instanceof Oc?(null!==this.connection_&&this.connection_.off(tc.CONNECTION_STATE_CHANGED,this.emitConnectionStateChanged,this),e.on(tc.CONNECTION_STATE_CHANGED,this.emitConnectionStateChanged,this)):null===e&&this.connection_.off(tc.CONNECTION_STATE_CHANGED,this.emitConnectionStateChanged,this),this.connection_=e)}getConnection(){return this.connection_}async play(e,t){if(this.log_.info(`stream ${this.isPlaying_?"update":"start to"} play with elementId: ${e} and options: ${JSON.stringify(t)}.`),this.isPlaying_){if(t&&!la(t.muted)&&(this.muted_=t.muted),t&&!la(t.objectFit)&&(this.objectFit_=t.objectFit),this.isScreenShare()?this.mirror_=!1:t&&!la(t.mirror)&&(this.mirror_=t.mirror),this.audioPlayer_&&this.audioPlayer_.setMuted(this.muted_),this.videoPlayer_&&(this.videoPlayer_.setObjectFit(this.objectFit_),this.videoPlayer_.setMirror(this.mirror_)),this.elementId_!==e){let t=e;ha(e)&&(t=document.getElementById(e)),t.appendChild(this.div_),this.elementId_=e}return}this.isPlaying_=!0;const i=document.createElement("div");i.setAttribute("id",`player_${this.id_}`),i.setAttribute("style","width: 100%; height: 100%; position: relative; background-color: black; overflow: hidden;");let s=e;ha(e)&&(s=document.getElementById(e)),s.appendChild(i),this.elementId_=e,this.div_=i,this.isRemote_||(this.muted_=!0),t&&!la(t.muted)&&(this.muted_=t.muted),this.isScreenShare()&&(this.objectFit_="contain"),t&&!la(t.objectFit)&&(this.objectFit_=t.objectFit),this.isScreenShare()?this.mirror_=!1:(this.isRemote_||(this.mirror_=!0),t&&!la(t.mirror)&&(this.mirror_=t.mirror)),La.emit(vo,{stream:this}),await Promise.all([this.playAudio(),this.playVideo()]),La.emit(to,{stream:this})}async playAudio(){if(!this.hasAudio()||this.isRemote_&&!this.isMainAudioSubscribed)return;const e=this.getAudioTrack();if(!this.audioPlayer_&&e){var t;this.log_.info("create AudioPlayer and play"),this.audioPlayer_=new Ec({stream:this,track:e,gainedTrack:null===(t=this.gain_)||void 0===t?void 0:t.audioTrack,div:this.div_,muted:this.muted_,outputDeviceId:this.audioOutputDeviceId_,volume:this.audioVolume_}),this.audioPlayer_.on(dc,(e=>{const t={type:o,state:e.state,reason:e.reason};La.emit(io,{stream:this,...t}),this.emitter_.emit(sc,t)}));try{await this.audioPlayer_.play()}catch(i){throw this.client_&&this.client_.getEnableAutoPlayDialog()&&new Nc,this.emitter_.emit(rc,i),i}}}async playVideo(){if(!this.hasVideo()||this.isRemote_&&!this.isMainVideoSubscribed&&!this.isAuxVideoSubscribed&&!this.isSmallVideoSubscribed)return;const e=this.getVideoTrack();if(!this.videoPlayer_&&e){La.emit(yo,{stream:this}),this.log_.info("create VideoPlayer and play"),this.videoPlayer_=new Pc({stream:this,track:e,div:this.div_,muted:this.muted_,objectFit:this.objectFit_,mirror:this.mirror_}),this.videoPlayer_.on(dc,(e=>{const t={type:r,state:e.state,reason:e.reason};La.emit(io,{stream:this,...t}),this.emitter_.emit(sc,t)}));try{await this.videoPlayer_.play()}catch(t){throw this.client_&&this.client_.getEnableAutoPlayDialog()&&new Nc,this.emitter_.emit(rc,t),t}}}stopAudio(){this.audioPlayer_&&(this.log_.info("stop AudioPlayer"),this.audioPlayer_.stop(),this.audioPlayer_=null)}stopVideo(){this.videoPlayer_&&(this.log_.info("stop VideoPlayer"),this.videoPlayer_.stop(),this.videoPlayer_=null)}restartPlayback(){this.audioPlayer_&&!this.audioPlayer_.isPlaying&&this.restartAudio(),this.videoPlayer_&&!this.videoPlayer_.isPlaying&&this.restartVideo()}restartAudio(){this.isPlaying_&&(this.stopAudio(),this.playAudio().catch((e=>{})))}restartVideo(){this.isPlaying_&&(this.stopVideo(),this.playVideo().catch((e=>{})))}stop(){this.isPlaying_&&(this.isPlaying_=!1,this.stopAudio(),this.stopVideo(),this.div_.parentNode.removeChild(this.div_))}async resume(){this.isPlaying_&&(this.log_.info("resume"),this.audioPlayer_&&await this.audioPlayer_.resume(),this.videoPlayer_&&await this.videoPlayer_.resume())}close(){this.log_.info("close stream"),this.isPlaying_&&this.stop(),this.isRemote_||(this.mediaStream_&&(this.mediaStream_.preventEvent=1,this.mediaStream_.getTracks().forEach((e=>{e.stop()})),this.mediaStream_=null),this.uninstallEvents())}muteAudio(){return this.addRemoteEvent(!0,o),this.doEnableTrack(o,!1)}muteVideo(){return this.addRemoteEvent(!0,r),this.doEnableTrack(r,!1)}unmuteAudio(){return this.addRemoteEvent(!1,o),this.doEnableTrack(o,!0)}unmuteVideo(){return this.addRemoteEvent(!1,r),this.doEnableTrack(r,!0)}addRemoteEvent(e,t){if(this.isRemote_&&this.client_){const i=this.client_.getUserId();let s,n=`${e?g:S} remote ${t}`;s=t===o?e?Mr:Or:e?Pr:Lr,ed(i,{eventId:s,eventDesc:n,timestamp:(new Date).getTime(),userId:i,tinyId:this.client_.getTinyId(),remoteUserId:this.userId_,remoteTinyId:this.connection_.getTinyId()})}}doEnableTrack(e,t){let i=!1;return e===o?this.mediaStream_.getAudioTracks().forEach((e=>{i=!0,e.enabled=t})):this.mediaStream_.getVideoTracks().forEach((e=>{i=!0,e.enabled=t})),i}getId(){return this.id_}getUserId(){return this.userId_}getTinyId(){return this.connection_?this.connection_.getTinyId():""}isPlaying(){return this.isPlaying_}async setAudioOutput(e){this.log_.info(`setAudioOutput ${e}`),this.audioOutputDeviceId_=e,this.audioPlayer_&&await this.audioPlayer_.setSinkId(e);const t=await gc();this.log_.info(`speakers: ${JSON.stringify(t)}`)}setAudioVolume(e){this.audioVolume_=e,this.log_.info(`setAudioVolume to ${e}`),this.audioPlayer_&&this.audioPlayer_.setVolume(e)}getAudioLevel(){let e=0;return this.audioPlayer_&&(e=this.audioPlayer_.getAudioLevel()),e}getInternalAudioLevel(){let e=0;return this.audioPlayer_&&(e=this.audioPlayer_.getInternalAudioLevel()),e}hasAudio(){if(this.isRemote_){if(!this.connection_)return!1;const e=this.connection_.getTrackState();return this.type_===re&&e.audio}return!!this.getAudioTrack()}hasVideo(){if(this.isRemote_){if(!this.connection_)return!1;const e=this.connection_.getTrackState();return this.type_===de?e.auxiliary:e.video}return!!this.getVideoTrack()}getSubscribedState(){return this.isRemote_&&this.connection_?this.connection_.getSubscribeState():null}getAudioTrack(){let e=null;if(this.mediaStream_){const t=this.mediaStream_.getAudioTracks();t.length>0&&(e=t[0])}return e}getVideoTrack(){let e=null;if(this.mediaStream_){const t=this.mediaStream_.getVideoTracks();t.length>0&&(e=t[0])}return e}getVideoFrame(){return this.videoPlayer_?this.videoPlayer_.getVideoFrame():null}getMediaStream(){return this.mediaStream_}setMediaStream(e){e!==this.mediaStream_&&(this.mediaStream_&&this.mediaStream_.getTracks().forEach((e=>e.stop())),this.mediaStream_=e)}updateVideoPlayingState(e){this.isPlaying_&&(e?(this.log_.info("playing state updated, play video"),this.playVideo().catch((e=>{}))):(this.log_.info("playing state updated, stop video"),this.stopVideo()))}updateAudioPlayingState(e){this.isPlaying_&&(e?(this.log_.info("playing state updated, play audio"),this.playAudio().catch((e=>{}))):(this.log_.info("playing state updated, stop audio"),this.stopAudio()))}on(e,t,i){this.emitter_.on(e,t,i)}off(e,t,i){"*"===e?this.emitter_.removeAllListeners():this.emitter_.off(e,t,i)}isRemote(){return this.isRemote_}isScreenShare(){return!this.isRemote_&&this.screen_||this.isRemote_&&this.getType()===h}getDiv(){return this.div_}getObjectFit(){return this.objectFit_}getMuted(){return this.muted_}getClient(){return this.client_}},e(tl.prototype,"play",[Yc],Object.getOwnPropertyDescriptor(tl.prototype,"play"),tl.prototype),e(tl.prototype,"setAudioOutput",[Zc],Object.getOwnPropertyDescriptor(tl.prototype,"setAudioOutput"),tl.prototype),e(tl.prototype,"getVideoFrame",[el],Object.getOwnPropertyDescriptor(tl.prototype,"getVideoFrame"),tl.prototype),tl);class sl extends il{constructor(e){const t={isRemote:!0,type:e.type};super({...e,...t}),this.name_=ft,this.isStreamAddedEventEmitted_=!1,this.isAbleToCallSubscription_=!0}installEvents(){super.installEvents(),La.on(co,this.handleStreamSubscribed,this),La.on(lo,this.handleStreamUnsubscribed,this)}uninstallEvents(){super.uninstallEvents(),La.off(co,this.handleStreamSubscribed,this),La.off(lo,this.handleStreamUnsubscribed,this)}handleStreamSubscribed(e){e.client===this.client_&&e.stream===this&&this.connection_.getCurrentState()===ue&&this.emitConnectionStateChanged({prevState:ce,state:ue})}handleStreamUnsubscribed(e){e.client===this.client_&&e.stream===this&&this.emitConnectionStateChanged({prevState:ue,state:ce})}getType(){return super.getType()}getIsAbleToCallSubscription(){return this.isAbleToCallSubscription_}setIsAbleToCallSubscription(e){this.isAbleToCallSubscription_=e}setIsStreamAddedEventEmitted(e){this.isStreamAddedEventEmitted_=e}getIsStreamAddedEventEmitted(){return this.isStreamAddedEventEmitted_}getAudioTrack(){if(!this.connection_)return null;return this.connection_.getTrackState().audio?super.getAudioTrack():null}getVideoTrack(){if(!this.connection_)return null;const e=this.connection_.getTrackState();return(this.type_!==re||e.video)&&(this.type_!==de||e.auxiliary)?super.getVideoTrack():null}close(){super.close()}}class nl{constructor(e){this.client_=e.client,this.subscribedStreams_=new Map,this.unsubscribedStreams_=new Map,this.subscriptedOptions_=new Map,this.autoRecoveryFlags_=new Map}get isEnabled(){return"webrtc"!==this.client_.getEnv()}async recover(e){const t=e.getUserId(),i=e.getType();if(!this.hasAutoRecoveryFlag(t,i))return;const s=this.getUnsubscribedStream(t,i)?"unsubscribe":"subscribe";try{Oo.warn(`recover() try to recover subscription [${s}][${t}][${i}]`),"subscribe"===s?await this.recoverSubscription(t,e):await this.recoverUnsubscription(t,e),sd.logSuccessEvent({userId:this.client_.getUserId(),eventType:Be}),Oo.warn(`recover() recover successfully [${s}][${t}][${i}]`)}catch(n){Oo.error(`recover() recover failed [${s}][${t}][${i}]`,n),sd.logFailedEvent({userId:this.client_.getUserId(),eventType:Be,error:n})}this.deleteAutoRecoveryFlag(t,i)}async recoverSubscription(e,t){const i=this.getOptions(e,t.getType()),s=this.getSubscribedStream(e,t.getType());if(!i||!s)return;const{isAudioMuted:n,isVideoMuted:a}=this.getStreamMuteState(s);this.mergeStream(s,t),this.recoverPlayingState(s),n&&s.doEnableTrack(o,!1),a&&s.doEnableTrack(r,!1)}async recoverUnsubscription(e,t){const i=this.getUnsubscribedStream(e,t.getType());i&&this.mergeStream(i,t)}getStreamMuteState(e){const t={isAudioMuted:!1,isVideoMuted:!1},i=e.getMediaStream();return i&&(t.isAudioMuted=i.getAudioTracks().map((e=>e.enabled)).includes(!1),t.isVideoMuted=i.getVideoTracks().map((e=>e.enabled)).includes(!1)),t}recoverPlayingState(e){const t=e.isPlaying(),i=e.getDiv();if(t&&i){const t=i.parentNode;e.stop(),e.play(t,{objectFit:e.getObjectFit(),muted:e.getMuted()})}}mergeStream(e,t){const i=t.getConnection(),s=t.getMediaStream();e.setConnection(i),i.setRemoteStream(s.id,e),e.setMediaStream(s),e.updateAudioPlayingState(t.hasAudio()),e.updateVideoPlayingState(t.hasVideo())}addSubscriptionRecord(e,t,i){const s=t.getType();if(this.subscribedStreams_.has(e))this.subscribedStreams_.get(e).set(s,t);else{const i=new Map;i.set(t.getType(),t),this.subscribedStreams_.set(e,i)}if(this.subscriptedOptions_.has(e))this.subscriptedOptions_.get(e).set(s,i);else{const s=new Map;s.set(t.getType(),i),this.subscriptedOptions_.set(e,s)}this.deleteUnsubscriptionRecord(e,s)}addUnsubscriptionRecord(e,t){if(this.unsubscribedStreams_.has(e))this.unsubscribedStreams_.get(e).set(t.getType(),t);else{const i=new Map;i.set(t.getType(),t),this.unsubscribedStreams_.set(e,i)}this.deleteSubscriptionRecord(e,t.getType())}getSubscribedStream(e,t){return this.subscribedStreams_.has(e)&&this.subscribedStreams_.get(e).has(t)?this.subscribedStreams_.get(e).get(t):null}getOptions(e,t){return this.subscriptedOptions_.has(e)&&this.subscriptedOptions_.get(e).has(t)?this.subscriptedOptions_.get(e).get(t):null}getUnsubscribedStream(e,t){return this.unsubscribedStreams_.has(e)&&this.unsubscribedStreams_.get(e).has(t)?this.unsubscribedStreams_.get(e).get(t):null}deleteSubscriptionRecord(e,t){this.subscribedStreams_.has(e)&&this.subscribedStreams_.get(e).delete(t),this.subscriptedOptions_.has(e)&&this.subscriptedOptions_.get(e).delete(t)}deleteUnsubscriptionRecord(e,t){this.unsubscribedStreams_.has(e)&&this.unsubscribedStreams_.get(e).delete(t)}markAllStream(){for(const[e,t]of[...this.subscribedStreams_.entries()])for(const[i]of[...t.entries()])this.setAutoRecoveryFlag(e,i);for(const[e,t]of[...this.unsubscribedStreams_.entries()])for(const[i]of[...t.entries()])this.setAutoRecoveryFlag(e,i)}setAutoRecoveryFlag(e,t){if(Oo.info(`setAutoRecoveryFlag() mark [${e}][${t}]`),this.autoRecoveryFlags_.has(e))this.autoRecoveryFlags_.get(e).set(t);else{const i=new Map;i.set(t),this.autoRecoveryFlags_.set(e,i)}}hasAutoRecoveryFlag(e,t){return!!this.isEnabled&&(this.autoRecoveryFlags_.has(e)&&this.autoRecoveryFlags_.get(e).has(t))}deleteAutoRecoveryFlag(e,t){this.autoRecoveryFlags_.has(e)&&this.autoRecoveryFlags_.get(e).delete(t)}delete(e){this.unsubscribedStreams_.delete(e),this.subscribedStreams_.delete(e),this.subscriptedOptions_.delete(e),this.autoRecoveryFlags_.delete(e)}}class al{constructor(e){this.player_=e,this.canvas_=document.createElement(a),this.canvasCtx_=this.canvas_.getContext("2d")}setCanvasRect(e,t){this.canvas_.width=e,this.canvas_.height=t}drawVideoToCanvas(){const e=this.player_.getElement(),t=e.videoHeight,i=e.videoWidth,s=i*this.canvas_.height/(t*this.canvas_.width);if(s>1.05||s<.95){let e=i*t/(this.canvas_.width*this.canvas_.height);this.setCanvasRect(i/Math.sqrt(e),t/Math.sqrt(e))}this.canvasCtx_.drawImage(e,0,0,this.canvas_.width,this.canvas_.height)}generateVideoTrackFromCanvasCapture(e){return this.canvas_.captureStream(e).getVideoTracks()[0]}generateStreamFromTrack(e){const t=new MediaStream;return t.addTrack(e),t}destroy(){this.player_.stop(),this.canvas_.width=0,this.canvas_.height=0,this.canvas_=null,this.canvasCtx_=null}get canvas(){return this.canvas_}get canvasCtx(){return this.canvasCtx_}get canDrawVideoToCanvas(){if(this.player_){const e=this.player_.getElement();if(e)return e.readyState===e.HAVE_ENOUGH_DATA}return!1}}let ol=new Blob(['let t,e,a,i;onmessage=function(n){const{action:h,data:s}=n.data;switch(h){case"render":a=s.canvas,t=a.width,e=a.height,i=a.getContext("2d"),function(t,e){const n=new TransformStream({async transform(t,e){const n=t.displayWidth,h=t.displayHeight,s=n*a.height/(h*a.width);if(s>1.05||s<.95){const t=n*h/(a.width*a.height);a.width=n/Math.sqrt(t),a.height=h/Math.sqrt(t)}i.drawImage(t,0,0,a.width,a.height);const o=new VideoFrame(a,{timestamp:t.timestamp});t.close(),e.enqueue(o)}});t.pipeThrough(n).pipeTo(e)}(s.readable,s.writable)}}'],{type:"application/javascript"});class rl{constructor(e){const{videoTrack:t}=e;this.width=void 0,this.height=void 0,this.canvas=document.createElement("canvas"),this.offscreen=null,this.smallGenerator=new MediaStreamTrackGenerator({kind:"video"}),this.smallWritable=this.smallGenerator.writable,this.bigProcessor=new MediaStreamTrackProcessor({track:t}),this.bigReadable=this.bigProcessor.readable,this.initWorker()}initWorker(){try{this.worker=new Worker(URL.createObjectURL(ol)),Oo.info("init worker processor success")}catch(e){Oo.warn(`init worker processor failed. ${e.error}`)}}setCanvasRect(e,t){this.width=e,this.height=t,this.canvas.width=e,this.canvas.height=t,this.offscreen=this.canvas.transferControlToOffscreen(),this.worker.postMessage({action:"render",data:{canvas:this.offscreen,readable:this.bigReadable,writable:this.smallWritable}},[this.offscreen,this.bigReadable,this.smallWritable])}generatorVideoTrack(){const e=new MediaStream([this.smallGenerator]);return null==e?void 0:e.getTracks()[0]}destroy(){this.worker.terminate()}}class dl{constructor(e){this.localStream_=e,this.player_=null,this.processor_=null,this.initOffscreenSuccess_=!1}async initialize(){var e;if(function(){var e,t,i;return(null===(e=window)||void 0===e?void 0:e.OffscreenCanvas)&&(null===(t=window)||void 0===t?void 0:t.MediaStreamTrackProcessor)&&(null===(i=window)||void 0===i?void 0:i.MediaStreamTrackGenerator)}()&&(null===(e=navigator)||void 0===e?void 0:e.hardwareConcurrency)>=6)try{await this.initOffscreen(),this.initOffscreenSuccess_=!0,Oo.info("Initialize VideoGenerator successfully!")}catch(t){this.initCanvas()}else this.initCanvas()}generateSmallVideoTrack(e){const{height:t,width:i,frameRate:s}=e,n=this.getSmallVideoProfile(i,t);let a;return this.initOffscreenSuccess_?(this.processor_.setCanvasRect(n.width,n.height),a=this.processor_.generatorVideoTrack()):(this.processor_.setCanvasRect(n.width,n.height),this.player_.setRect({width:n.width,height:n.height}),a=this.processor_.generateVideoTrackFromCanvasCapture(s),this.interval_=kd.run("raf",this.render.bind(this),{fps:s})),a}render(){this.processor_.canDrawVideoToCanvas&&this.processor_.drawVideoToCanvas()}destroy(){kd.clearTask(this.interval_),this.processor_&&this.processor_.destroy()}initOffscreen(){this.processor_=new rl({videoTrack:this.localStream_.getVideoTrack()})}initCanvas(){this.player_=new Pc({stream:this.localStream_,track:this.localStream_.getVideoTrack(),muted:!0,objectFit:"cover",mirror:!1}),this.player_.play().then((()=>{Oo.info("VideoGenerator: play local video success")})).catch((()=>{Oo.error("VideoGenerator: Failed to play local video")})),this.processor_=new al(this.player_)}getSmallVideoProfile(e,t){const i=this.localStream_.getVideoTrack();let s,n=this.localStream_.getVideoProfile();if(Zd){const e=i.getSettings();e&&e.width&&e.height&&(n.width=e.width,n.height=e.height)}const a=n.width*n.height,o=e*t;Oo.info(`big stream resolution: ${n.width}*${n.height} small stream resolution: ${e}*${t} `),s=a>o?a/o:a/19200;return{width:parseInt(n.width/Math.sqrt(s)),height:parseInt(n.height/Math.sqrt(s))}}}const cl=new Map;const ll=No({retryFunction:async function(e){if(Hd())return;const t=await function(e){return{audio:hl(e),video:ul(e)}}(e);let i,s;Oo.info("getUserMedia with constraints: "+JSON.stringify(t)),t.audio&&(i=await Xh.getMicrophones(),Oo.info(`microphones: ${Ca(i,["deviceId","label"])}`)),t.video&&(s=await Xh.getCameras(),Oo.info(`cameras: ${Ca(s,["deviceId","label"])}`));try{return await navigator.mediaDevices.getUserMedia(t)}catch(o){var n,a;if("NotFoundError"===o.name){if(s&&0===s.length)throw new gr({code:pr.DEVICE_NOT_FOUND,message:ta({key:Es})});if(i&&0===i.length)throw new gr({code:pr.DEVICE_NOT_FOUND,message:ta({key:bs})})}if(t.audio&&(null===(n=i)||void 0===n?void 0:n.length)>0){const t=i.find((t=>t.deviceId===e.microphoneId));t&&t.getCapabilities&&Oo.warn(Ca(t.getCapabilities(),Ot))}if(t.video&&(null===(a=s)||void 0===a?void 0:a.length)>0){const t=s.find((t=>t.deviceId===e.cameraId));t&&t.getCapabilities&&Oo.warn(Ca(t.getCapabilities(),Ot))}throw new gr({code:pr.INITIALIZE_FAILED,name:o.name,message:o.message,constraint:o.constraint})}},settings:{retries:3,timeout:500},onError:(e,t,i,s,n)=>{const a=n+1;Oo.warn(`getUserMedia error: ${e}`),"NotReadableError"===e.name||"OverconstrainedError"===e.name?(1===n&&s[0].video?(s[0].maxResoution=!1,s[0].frameRate=s[0].frameRate>10?10:5):2===a?s[0].useDeviceIdOnly=!0:3!==a||s[0].useExact||(s[0].useTrueAsConstraint=!0),e.message.includes("deviceId")&&s[0].retryWhenExactFailed&&(s[0].useExact=!1),t()):i(e)},onRetrying:e=>{Oo.warn(`getUserMedia retrying [${e}/3]`)},onRetryFailed:()=>{sd.uploadEvent({log:"stat-getUserMedia-retry-failed"})},onRetrySuccess:e=>{sd.uploadEvent({log:"stat-getUserMedia-retry-success-"+e})}});function hl(e){if(!e.audio)return!1;if(e.useTrueAsConstraint)return!0;const t={};return!id(e.microphoneId)&&(t.deviceId=e.useExact?{exact:e.microphoneId}:e.microphoneId,e.useDeviceIdOnly)?t:(ua(e.channelCount)&&e.channelCount>1&&(t.channelCount=e.channelCount),_a(e.echoCancellation)&&!e.echoCancellation&&(t.echoCancellation=!1),_a(e.noiseSuppression)&&!e.noiseSuppression&&(t.noiseSuppression=!1),_a(e.autoGainControl)&&!e.autoGainControl&&(t.autoGainControl=!1),!!id(t)||t)}function ul(e){if(!e.video)return!1;if(e.useTrueAsConstraint)return!0;const{maxResoution:t=!0}=e,i={};return e.facingMode?i.facingMode=e.facingMode:e.cameraId&&(i.deviceId=e.useExact?{exact:e.cameraId}:e.cameraId),e.useDeviceIdOnly&&!id(i)?i:(e.width&&(i.width={ideal:e.width},t&&!Ks&&(i.width.max=e.width)),e.height&&(i.height={ideal:e.height},t&&!Ks&&(i.height.max=e.height)),Ks&&Tn&&e.width&&e.height&&e.width*e.height<101376&&(i.width=e.width,i.height=e.height),e.frameRate&&(i.frameRate=e.frameRate),!!id(i)||i)}function _l(e){let t={echoCancellation:e.echoCancellation,autoGainControl:e.autoGainControl,noiseSuppression:e.noiseSuppression,sampleRate:e.sampleRate,channelCount:e.channelCount};return la(e.microphoneId)||(t.deviceId=e.microphoneId),{audio:t,video:!1}}function ml(e){let t={systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},i={width:Bn?{max:e.width}:{ideal:e.width,max:e.width},height:Bn?{max:e.height}:{ideal:e.height,max:e.height},frameRate:e.frameRate,displaySurface:"monitor"};return t.video=i,la(e.audioConstraints)||(t.audio=e.audioConstraints),t}const pl=new Map([["120p",{width:160,height:120,frameRate:15,bitrate:200}],["120p_2",{width:160,height:120,frameRate:15,bitrate:100}],["180p",{width:320,height:180,frameRate:15,bitrate:350}],["180p_2",{width:320,height:180,frameRate:15,bitrate:150}],["240p",{width:320,height:240,frameRate:15,bitrate:400}],["240p_2",{width:320,height:240,frameRate:15,bitrate:200}],["360p",{width:640,height:360,frameRate:15,bitrate:800}],["360p_2",{width:640,height:360,frameRate:15,bitrate:400}],["480p",{width:640,height:480,frameRate:15,bitrate:900}],["480p_2",{width:640,height:480,frameRate:15,bitrate:500}],["720p",{width:1280,height:720,frameRate:15,bitrate:1500}],["1080p",{width:1920,height:1080,frameRate:15,bitrate:2e3}],["1440p",{width:2560,height:1440,frameRate:30,bitrate:4860}],["4K",{width:3840,height:2160,frameRate:30,bitrate:9e3}]]),gl=new Map([["480p",{width:640,height:480,frameRate:5,bitrate:900}],["480p_2",{width:640,height:480,frameRate:30,bitrate:1e3}],["720p",{width:1280,height:720,frameRate:5,bitrate:1200}],["720p_2",{width:1280,height:720,frameRate:30,bitrate:3e3}],["1080p",{width:1920,height:1080,frameRate:5,bitrate:1600}],["1080p_2",{width:1920,height:1080,frameRate:30,bitrate:4e3}]]),Sl=new Map([["standard",{sampleRate:48e3,channelCount:1,bitrate:40}],["standard-stereo",{sampleRate:48e3,channelCount:2,bitrate:64}],["high",{sampleRate:48e3,channelCount:1,bitrate:128}],["high-stereo",{sampleRate:48e3,channelCount:2,bitrate:192}]]);var fl,vl,Il,yl,Tl,bl,El,wl,kl,Rl,Al,Cl;const Dl=new Map;let Nl=(fl=Xc(St),vl=Xc(St),Il=Xc(St),yl=Xc(St),Tl=jc(...Bc.LOCAL_STREAM.switchDevice),bl=jc(Bc.STREAM.addTrack),El=jc(Bc.STREAM.removeTrack),wl=jc(Bc.STREAM.replaceTrack),kl=Gc({retries:10,timeout:3e3,onRetryFailed(e){sd.logFailedEvent({userId:this.client_?this.client_.getUserId():this.userId_,eventType:Fe,error:e}),this.emitter_.emit(rc,new gr({code:pr.DEVICE_AUTO_RECOVER_FAILED,message:e.message}))}}),Rl=Hc(Bc.LOCAL_STREAM.setAudioCaptureVolume),Al=Xc(St),e((Cl=class extends il{get scaleResolutionDownBy(){const e=this.getVideoTrack();if(!e||!Zd)return 1;const t=e.getSettings();return t.width===this.videoProfile_.width&&t.height===this.videoProfile_.height?1:null!==(i=window.screen)&&void 0!==i&&null!==(s=i.orientation)&&void 0!==s&&null!==(n=s.type)&&void 0!==n&&n.includes("portrait")&&this.videoProfile_.width>this.videoProfile_.height&&t.height>t.width?Math.max(t.width/this.videoProfile_.height,t.height/this.videoProfile_.width,1):Math.max(t.width/this.videoProfile_.width,t.height/this.videoProfile_.height,1);var i,s,n}constructor(e){super({...e,isRemote:!1,type:"local"}),this.name_=St,this.client_=null,this.video_=e.video,this.audio_=e.audio,this.cameraId_=e.cameraId,this.cameraGroupId_="",this.facingMode_=e.facingMode,this.microphoneId_=e.microphoneId,this.microphoneGroupId_="",this.microphoneLabel_="",this.videoSource_=e.videoSource,this.audioSource_=e.audioSource,this.screen_=e.screen,this.screenAudio_=e.screenAudio,this.audioProfile_={echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40},this.screenAudio_&&(this.audioProfile_.echoCancellation=!0,this.audioProfile_.autoGainControl=!1,this.audioProfile_.noiseSuppression=!1),_a(e.echoCancellation)&&(this.audioProfile_.echoCancellation=e.echoCancellation),_a(e.autoGainControl)&&(this.audioProfile_.autoGainControl=e.autoGainControl),_a(e.noiseSuppression)&&(this.audioProfile_.noiseSuppression=e.noiseSuppression),this.videoProfile_=pl.get("480p_2"),this.screenProfile_=gl.get("1080p"),this.videoSetting_=null,this.muteState_={video:!1,audio:!1,auxVideo:!1},this.beautyStatus_=!1,this.prevAudioRecoverTime_=0,this.prevVideoRecoverTime_=0,this.isAudioRecovering_=!1,this.isVideoRecovering_=!1,this.initState(),this.canvas_=null,this.canvasInterval_=null,this.canvasTrack_=null,this.gain_={audioTrack:null,source:null,gainNode:null},this.captureVolume_=100,this.enableAutoRecoverCapture_=!!la(e.enableAutoRecoverCapture)||e.enableAutoRecoverCapture,this.enableAutoRecoverOther_=!_a(e.enableAutoRecoverOther)||e.enableAutoRecoverOther,this.log_.info(`stream created: ${this.id_} autoRecover: ${this.enableAutoRecoverCapture_}`),this.isAIDenoiser=!1}initState(){this.isAddingTrack_=!1,this.isRemovingTrack_=!1,this.setIsReadyToPublish(!1),this.setPublishState(nt)}installEvents(){super.installEvents(),La.on(To,this.onVideoTrackStopped,this),La.on(So,this.onVideoTrackStopped,this),La.on(Eo,this.onAudioTrackStopped,this),La.on(bo,this.onAudioTrackStopped,this)}uninstallEvents(){super.uninstallEvents(),La.off(To,this.onVideoTrackStopped,this),La.off(So,this.onVideoTrackStopped,this),La.off(Eo,this.onAudioTrackStopped,this),La.off(bo,this.onAudioTrackStopped,this)}initialize(){return new Promise(((e,t)=>{if(jd())t(new gr({code:pr.INVALID_OPERATION,message:ta({key:ms})}));else{if(la(this.audio_)){const t=new MediaStream;return la(this.audioSource_)||(t.addTrack(this.audioSource_),this.updateAudioPlayingState(!0)),la(this.videoSource_)||(t.addTrack(this.videoSource_),this.updateVideoPlayingState(!0)),this.setMediaStream(t),sd.logSuccessEvent({userId:this.client_?this.client_.getUserId():this.userId_,eventType:Ue,kind:"custom"}),this.setIsReadyToPublish(!0),e()}this.screen_?(this.log_.info("initialize stream audio: "+this.audio_+" screenAudio: "+this.screenAudio_+" screen: "+this.screen_),async function(e){if(Hd())return;let t=null;if(xn&&$n<74||Bn){const i=ml(e);Oo.info("getDisplayMedia with constraints: "+JSON.stringify(i));let s=await navigator.mediaDevices.getDisplayMedia(i);if(e.screenAudio)return Oo.warn("Your browser not support capture system audio"),s;if(e.audio){const i=_l(e);return Oo.info("getUserMedia with constraints: "+JSON.stringify(i)),t=await navigator.mediaDevices.getUserMedia(i),s.addTrack(t.getAudioTracks()[0]),s}return s}if(e.screenAudio){e.audioConstraints={echoCancellation:e.echoCancellation,autoGainControl:e.autoGainControl,noiseSuppression:e.noiseSuppression,sampleRate:44100};const t=ml(e);return Oo.info("getDisplayMedia with constraints: "+JSON.stringify(t)),await navigator.mediaDevices.getDisplayMedia(t)}{const i=ml(e);Oo.info("getDisplayMedia with constraints: "+JSON.stringify(i));let s=await navigator.mediaDevices.getDisplayMedia(i);if(e.audio){const i=_l(e);return Oo.info("getUserMedia with constraints: "+JSON.stringify(i)),t=await navigator.mediaDevices.getUserMedia(i),s.addTrack(t.getAudioTracks()[0]),s}return s}}({audio:this.audio_,screenAudio:this.screenAudio_,microphoneId:this.microphoneId_,width:this.screenProfile_.width,height:this.screenProfile_.height,frameRate:this.screenProfile_.frameRate,sampleRate:this.audioProfile_.sampleRate,channelCount:this.audioProfile_.channelCount,autoGainControl:this.audioProfile_.autoGainControl,noiseSuppression:this.audioProfile_.noiseSuppression,echoCancellation:this.audioProfile_.echoCancellation}).then((t=>{this.setMediaStream(t),this.updateAudioPlayingState(this.audio_||this.screenAudio_),this.updateVideoPlayingState(!0);const i=this.getVideoTrack();return i.applyConstraints&&i.applyConstraints({frameRate:{min:this.screenProfile_.frameRate,ideal:this.screenProfile_.frameRate},width:this.screenProfile_.width,height:this.screenProfile_.height}).catch((e=>{this.warn(`screen applyConstraints failed: ${e}`)})),this.listenForScreenSharingStopped(i),this.setVideoContentHint(w),this.updateDeviceIdInUse(),this.setIsReadyToPublish(!0),this.log_.info(JSON.stringify(i.getSettings())),sd.logSuccessEvent({userId:this.client_?this.client_.getUserId():this.userId_,eventType:Ue,kind:"getDisplayMedia"}),e()})).catch((e=>{sd.logFailedEvent({userId:this.client_?this.client_.getUserId():this.userId_,eventType:Ue,kind:"getDisplayMedia",error:e}),this.log_.error("getDisplayMedia error observed "+e),t(e instanceof gr?e:new gr({code:pr.INITIALIZE_FAILED,name:e.name,message:e.message}))}))):(La.emit(mo,{stream:this,audio:this.audio_,video:this.video_}),this.log_.info("initialize stream audio: "+this.audio_+" video: "+this.video_),ll({audio:this.audio_,video:this.video_,facingMode:this.facingMode_,cameraId:this.cameraId_,microphoneId:this.microphoneId_,width:this.videoProfile_.width,height:this.videoProfile_.height,frameRate:this.videoProfile_.frameRate,sampleRate:this.audioProfile_.sampleRate,channelCount:this.audioProfile_.channelCount,autoGainControl:this.audioProfile_.autoGainControl,noiseSuppression:this.audioProfile_.noiseSuppression,echoCancellation:this.audioProfile_.echoCancellation,useExact:!0,retryWhenExactFailed:!0}).then((t=>(La.emit(po,{stream:this,audio:this.audio_,video:this.video_}),this.setMediaStream(t),t.getTracks().forEach((e=>{if(Zd){const t=e.getSettings();this.log_.debug(`${e.kind} settings: ${JSON.stringify(t)}`),e.kind===r&&(this.videoSetting_=t)}ec&&this.log_.info(`${e.kind} capabilities: ${Ca(e.getCapabilities(),Ot)}`)})),this.updateAudioPlayingState(this.audio_),this.updateVideoPlayingState(this.video_),this.updateDeviceIdInUse(),this.log_.info("gotStream hasAudio: "+this.hasAudio()+" hasVideo: "+this.hasVideo()),this.setIsReadyToPublish(!0),sd.logSuccessEvent({userId:this.client_?this.client_.getUserId():this.userId_,eventType:Ue,kind:"getUserMedia"}),e()))).catch((e=>{La.emit(go,{stream:this,audio:this.audio_,video:this.video_,error:e}),sd.logFailedEvent({userId:this.client_?this.client_.getUserId():this.userId_,eventType:Ue,kind:"getUserMedia",error:e}),this.log_.error("getUserMedia error observed "+e),t(e)})))}}))}listenForScreenSharingStopped(e){e.addEventListener("ended",(e=>{this.log_.info("screen sharing was stopped because the video track is ended"),this.emitter_.emit(nc)}))}muteAudio(){const e=super.muteAudio();return e&&(this.log_.info("localStream mute audio"),this.sendMutedFlag(o,!0)),e}muteVideo(){const e=super.muteVideo();return e&&(this.log_.info("localStream mute video"),this.sendMutedFlag(r,!0)),e}unmuteAudio(){const e=super.unmuteAudio();return e&&(this.log_.info("localStream unmute audio"),this.sendMutedFlag(o,!1)),e}unmuteVideo(){const e=super.unmuteVideo();return e&&(this.log_.info("localStream unmute video"),this.sendMutedFlag(r,!1)),e}sendMutedFlag(e,t){this.setMuteState(e,t);const i=this.getConnection();if(i){i.sendMutedFlag(this.muteState_,this);const n=i.getUserId(),a=i.getTinyId();let r,d=`${t?g:S} local ${e} track`;r=e===o?t?yr:br:t?Tr:Er,ed(n,{eventId:r,eventDesc:d,timestamp:s(),userId:n,tinyId:a})}}setMuteState(e,t){this.muteState_[e]=t,this.log_.info(`set ${e} muted state: [${t?"mute":"unmute"}]`)}async setAudioProfile(e){let t;"object"==typeof e?t=e:(t=Sl.get(e),void 0===t&&(t=Sl.get("standard"))),this.log_.info("setAudioProfile: "+JSON.stringify(t));const i=this.getAudioTrack();i&&await i.applyConstraints(t);const s=this.audioProfile_.bitrate!==t.bitrate;this.audioProfile_={...this.audioProfile_,...t},s&&this.connection_&&(await this.connection_.setBandwidth({bandwidth:this.audioProfile_.bitrate,type:o}),this.connection_.sendMediaSettings(this))}async setVideoProfile(e){var t;if(this.connection_&&!Bd())throw new gr({code:pr.NOT_SUPPORTED,message:ta({key:gs})});let i;if(oa(e)?i={...this.videoProfile_,...e}:ha(e)&&(i=pl.get(e),la(i)&&(i=pl.get("480p_2"))),null!==(t=this.client_)&&void 0!==t&&t.get2k4kFlag()){!(1===this.client_.get2k4kFlag())&&!this.screen_&&i.height*i.width>=3686400?(i.width=1920,i.height=1080,this.log_.warn(Mt)):Qc.handleFunctionState({fnName:"2K_4K"})}i&&i.width*i.height>921600&&qn&&(i.width=1280,i.height=720,this.log_.warn("reset to 1280 * 720 on iOS 13~14")),this.log_.info("setVideoProfile "+JSON.stringify(i));const s=this.getVideoTrack();s&&await s.applyConstraints(i);const n=this.videoProfile_.bitrate!==i.bitrate;this.videoProfile_=i,n&&this.connection_&&(await this.connection_.setBandwidth({bandwidth:i.bitrate,type:r,videoType:l}),this.connection_.sendMediaSettings(this))}getVideoBitrate(){return this.screen_?this.screenProfile_.bitrate:this.videoProfile_.bitrate}getAudioBitrate(){return this.audioProfile_.bitrate}setScreenProfile(e){let t=e;ha(e)&&(t=gl.get(e)||gl.get("1080p")),this.log_.info("setScreenProfile "+JSON.stringify(e)),this.screenProfile_=t}getVideoProfile(){return this.screen_?this.screenProfile_:this.videoProfile_}getAudioProfile(){return this.audioProfile_}setVideoContentHint(e){const t=this.getVideoTrack();t&&"contentHint"in t&&(this.log_.info("set video track contentHint to: "+e),t.contentHint=e,t.contentHint!==e&&this.log_.warn("Invalid video track contentHint: "+e))}async switchDevice(e,t){if(!this.mediaStream_||this.cameraId_===t||this.facingMode_===t)return;const i=e===o,n=e===r;if(i&&t===this.microphoneId_){if("default"!==t)return;if(await async function(e,t){const i=(await pc()).find((e=>"default"===e.deviceId));return(null==i?void 0:i.groupId)===e&&i.label===t}(this.microphoneGroupId_,this.microphoneLabel_))return}if(this.setIsReadyToPublish(!1),this.log_.info("switchDevice "+e+" to: "+t),i){const e=this.getAudioTrack(),t=this.getMicrophoneTrackMixed();e&&e.stop(),t&&t.stop()}if(n){const e=this.getVideoTrack();if(e&&e.stop(),An){const e=this.getAudioTrack();e&&(this.log_.info("stop audio track first in huawei env"),e.stop())}}try{const e=await ll({audio:i||An,video:n,facingMode:t===m||t===p?t:void 0,cameraId:n?t:this.cameraId_,microphoneId:i?t:this.microphoneId_,width:this.videoProfile_.width,height:this.videoProfile_.height,frameRate:this.videoProfile_.frameRate,sampleRate:this.audioProfile_.sampleRate,channelCount:this.audioProfile_.channelCount,autoGainControl:this.audioProfile_.autoGainControl,noiseSuppression:this.audioProfile_.noiseSuppression,echoCancellation:this.audioProfile_.echoCancellation,useExact:!0,retryWhenExactFailed:!1});let a=null;if(i){const t=e.getAudioTracks()[0];if(t&&this.isAudioTrackMixed()){const e=this.getAudioTrack(),i=Xh.AudioMixerPlugin.getAudioTrackMap();a=await Xh.AudioMixerPlugin.mix({targetTrack:t,sourceList:i.get(e.id).sourceList,trackList:i.get(e.id).trackList})}else a=t}else{a=e.getVideoTracks()[0],a&&this.isVideoTrackBeautified()&&(a=await this.generateBeautyTrack(a));const t=e.getAudioTracks()[0];t&&An&&await this.replaceTrack(t)}await this.replaceTrack(a),this.updateDeviceIdInUse();const o=this.getConnection();if(o){const e=o.getUserId(),t=o.getTinyId();let n=Ar,a="switch camera";i&&(n=Cr,a="switch microphone"),ed(e,{eventId:n,eventDesc:a,timestamp:s(),userId:e,tinyId:t})}this.log_.info(`switch ${i?"microphone":"camera"} success `),i&&(this.audio_=!0),n&&(this.video_=!0,t!==p&&t!==m||(this.facingMode_=t)),this.setIsReadyToPublish(!0)}catch(a){throw this.log_.error(a),i?this.recoverCapture({audio:!0,video:!1,microphoneId:this.microphoneId_}):this.recoverCapture({audio:!1,video:!0,cameraId:this.cameraId_,facingMode:this.facingMode_}),a}}async addTrack(e){try{if(e.kind===r&&Zd){const t=e.getSettings();!this.videoSetting_||t.width===this.videoSetting_.width&&t.height===this.videoSetting_.height||this.log_.warn(`video resolution of the track (${t.width} x ${t.height}) shall be kept the same as the previous: ${this.videoSetting_.width} x ${this.videoSetting_.height}. It may cause abnormal Cloud Recording.`)}this.isAddingTrack_=!0,this.keepMuteState(e),this.mediaStream_.addTrack(e);const t=this.getConnection();if(t){let i=null;e.kind===r&&(zn||Gn)&&ga(e)&&(i=this.getCanvasTrack()),await t.addTrack(i||e,this)}e.kind===o?(this.audio_=!0,this.updateAudioPlayingState(!0),100!==this.captureVolume_&&this.setAudioCaptureVolume(this.captureVolume_)):(this.video_=!0,this.updateVideoPlayingState(!0)),this.isAddingTrack_=!1}catch(t){throw this.mediaStream_.removeTrack(e),this.isAddingTrack_=!1,t}}async removeTrack(e){try{this.isRemovingTrack_=!0;const t=this.getConnection();t&&(e.kind===r&&(zn||Gn)&&this.canvasTrack_?(await t.removeTrack(this.canvasTrack_,this),this.clearCanvas()):e.kind===o&&this.gain_.audioTrack?await t.removeTrack(this.gain_.audioTrack,this):await t.removeTrack(e,this)),this.mediaStream_.removeTrack(e),e.kind===o?(this.audio_=!1,this.updateAudioPlayingState(!1),this.stopGainNode()):(this.video_=!1,this.updateVideoPlayingState(!1)),this.isRemovingTrack_=!1}catch(t){throw this.isRemovingTrack_=!1,t}}async replaceTrack(e){if(e.kind===r&&Zd){const t=e.getSettings();!this.videoSetting_||t.width===this.videoSetting_.width&&t.height===this.videoSetting_.height||this.log_.warn(`video resolution of the track (${t.width} x ${t.height}) shall be kept the same as the previous: ${this.videoSetting_.width} x ${this.videoSetting_.height}. It may cause abnormal Cloud Recording.`)}this.keepMuteState(e);const t=this.mediaStream_;if(e.kind===o){if(t.removeTrack(t.getAudioTracks()[0]),t.addTrack(e),super.restartAudio(),this.gain_.gainNode)return void this.reconnectGainNode(e)}else t.removeTrack(t.getVideoTracks()[0]),t.addTrack(e),super.restartVideo();const i=this.getConnection();if(i){if(e.kind===r&&(zn||Gn)&&this.canvasTrack_)return;await i.replaceTrack(e,this)}}async recoverCapture(e){if(!this.mediaStream_||!this.enableAutoRecoverCapture_||e.audio&&!e.video&&this.isAudioRecovering_||e.video&&!e.audio&&this.isVideoRecovering_)return;e.audio&&(this.isAudioRecovering_=!0),e.video&&(this.isVideoRecovering_=!0),this.log_.warn("recoverCapture() trying "+JSON.stringify(e));let t=this.audio_&&e.audio,i=this.video_&&e.video;try{const a=await Xh.getCameras(),d=await Xh.getMicrophones();if(i&&0===a.length&&(i=!1,this.log_.warn("recoverCapture() video flag is true, but no camera detected, set video to false")),t&&0===d.length&&(t=!1,this.log_.warn("recoverCapture() audio flag is true, but no microphone detected, set audio to false")),!t&&!i)return e.audio&&(this.isAudioRecovering_=!1),e.video&&(this.isVideoRecovering_=!1),void this.log_.warn("recoverCapture() both audio and video are false, aborted");const c=e&&a.findIndex((({deviceId:t})=>t===e.cameraId))>=0,l=e&&d.findIndex((({deviceId:t})=>t===e.microphoneId))>=0;var s,n;if(t)null===(s=this.getAudioTrack())||void 0===s||s.stop();if(i)null===(n=this.getVideoTrack())||void 0===n||n.stop();const h=(await ll({audio:t,video:i,cameraId:c?e.cameraId:void 0,microphoneId:l?e.microphoneId:void 0,facingMode:this.facingMode_,width:this.videoProfile_.width,height:this.videoProfile_.height,frameRate:this.videoProfile_.frameRate,sampleRate:this.audioProfile_.sampleRate,channelCount:this.audioProfile_.channelCount,autoGainControl:this.audioProfile_.autoGainControl,noiseSuppression:this.audioProfile_.noiseSuppression,echoCancellation:this.audioProfile_.echoCancellation})).getTracks();for(let e=0;e{if(e.kind===o&&this.isAudioTrackMixed()){const e=this.getMicrophoneTrackMixed();if(e){const{deviceId:t,groupId:i}=e.getSettings();t&&(this.microphoneId_=t,this.microphoneGroupId_=i,this.microphoneLabel_=e.label)}return}if(e.kind===r&&this.isVideoTrackBeautified()){const e=this.getBeautyOriginTrack();if(e){const{deviceId:t,groupId:i}=e.getSettings();t&&(this.cameraId_=t,this.cameraGroupId_=i)}return}const{deviceId:t,groupId:i}=e.getSettings();t&&(e.kind===o?(this.microphoneId_=t,this.microphoneGroupId_=i,this.microphoneLabel_=e.label):e.kind!==r||this.screen_||(this.cameraId_=t,this.cameraGroupId_=i))}))}const e=this.mediaStream_.getAudioTracks(),t=this.mediaStream_.getVideoTracks();e&&0===e.length&&(this.microphoneId_="",this.microphoneGroupId_=""),t&&0===t.length&&(this.cameraId_="",this.cameraGroupId_="")}isAudioTrackMixed(){if(Xh.AudioMixerPlugin){const e=Xh.AudioMixerPlugin.getAudioTrackMap(),t=this.getAudioTrack();if(e&&t&&e.has(t.id))return!0}return!1}getMicrophoneTrackMixed(){if(Xh.AudioMixerPlugin){const e=Xh.AudioMixerPlugin.getAudioTrackMap(),t=this.getAudioTrack();if(e&&t&&e.has(t.id)){const i=e.get(t.id);return i.hasMicrophone?i.microphoneTrack:null}}return null}isVideoTrackBeautified(){if(Xh.beautyTrackMap){const e=Xh.beautyTrackMap,t=this.getVideoTrack();if(t&&e.has(t.id))return!0}return!1}getBeautyOriginTrack(){if(Xh.beautyTrackMap){const e=Xh.beautyTrackMap,t=this.getVideoTrack();if(t&&e.has(t.id)){const i=e.get(t.id);if(i.originTrack)return i.originTrack}}return null}async generateBeautyTrack(e){let t=null;const i=this.getVideoTrack(),s=Xh.beautyTrackMap.get(i.id),n=s.param;if(s.type)switch(s.type){case"beauty":t=s.pluginInstance.generateBeautyTrack(e);break;case"virtual":t=await s.pluginInstance.generateVirtualTrack({videoTrack:e,type:n.type,img:n.img});break;case"mixed":t=await s.pluginInstance.generateMixedTrack({videoTrack:e,type:n.type,img:n.img})}else t=s.pluginInstance.generateBeautyTrack(e);return s.pluginInstance.deleteSource(i.id),this.log_.info(`regenerate beauty track, track id = ${e.id}`),t}getScreen(){return this.screen_}hasScreenTrack(){if(this.screen_)return!0;const e=this.getVideoTrack();return!!e&&(e.contentHint===w||e.contentHint===k)}getVideo(){return this.video_}getAudio(){return this.audio_}getCameraId(){return this.cameraId_}getMicrophoneId(){return this.microphoneId_}getMicrophoneGroupId(){return this.microphoneGroupId_}getIsReadyToPublish(){return this.isReadyToPublish_}setIsReadyToPublish(e){this.isReadyToPublish_=e}setPublishState(e){this.publishState_=e}setBeautyStatus(e){this.beautyStatus_=!!e}getBeautyStatus(){return this.beautyStatus_}syncMuteState(){const e=this.getAudioTrack(),t=this.getVideoTrack();if(e){const t=!e.enabled;this.setMuteState(o,t)}if(t){const e=!t.enabled;this.setMuteState(r,e)}this.connection_&&this.connection_.sendMutedFlag(this.muteState_,this)}keepMuteState(e){e instanceof window.MediaStreamTrack&&this.muteState_[e.kind]&&(e.enabled=!1,this.log_.warn(`prev ${e.kind} track is muted, keep mute state`))}async onVideoTrackStopped({stream:e,type:t}){!(e===this&&this.video_&&this.cameraId_&&function(e){var t;if(e instanceof CanvasCaptureMediaStreamTrack)return!1;if(!(e instanceof window.MediaStreamTrack))return!1;const i=e.label.toLocaleLowerCase();if(i.includes("camera")||i.includes("webcam"))return!0;const s=`${null===(t=e.getSettings())||void 0===t?void 0:t.deviceId}_${E}`;return!!uc.has(s)}(this.getVideoTrack()))||this.isVideoRecovering_||t===g&&Tn&&Bn||(Date.now()-this.prevVideoRecoverTime_<2e3?setTimeout((()=>this.onVideoTrackStopped({stream:e,type:t})),2e3):t===g?setTimeout((()=>{const e=this.getVideoTrack();null!=e&&e.muted&&"visible"===document.visibilityState&&this.recoverVideoCapture(t)}),5e3):this.recoverVideoCapture(t))}async onAudioTrackStopped({stream:e,type:t}){e!==this||!this.audio_||!this.microphoneId_||this.isAudioRecovering_||t===g&&Tn&&Bn||(Date.now()-this.prevAudioRecoverTime_<2e3?setTimeout((()=>this.onAudioTrackStopped({stream:e,type:t})),2e3):t===g?setTimeout((()=>{const e=this.getAudioTrack();null!=e&&e.muted&&"visible"===document.visibilityState&&this.recoverAudioCapture(t)}),5e3):this.recoverAudioCapture(t))}async recoverAudioCapture(e){this.prevAudioRecoverTime_=Date.now(),sd.uploadEvent({log:`stat-local-audio-${e}`,userId:this.userId_}),this.recoverCapture({audio:!0,video:!1,microphoneId:await this.getRecoverCaptureDeviceId(!1)})}async recoverVideoCapture(e){this.prevVideoRecoverTime_=Date.now(),sd.uploadEvent({log:`stat-local-video-${e}`,userId:this.userId_}),this.recoverCapture({audio:!1,video:!0,cameraId:await this.getRecoverCaptureDeviceId(!0)})}async getRecoverCaptureDeviceId(e=!0){let t=e?this.cameraId_:this.microphoneId_;if(t&&this.enableAutoRecoverOther_){Dl.has(t)?Dl.set(t,Dl.get(t)+1):Dl.set(t,1);const i=Dl.get(t);if(i>=3){const s=e?(await Xh.getCameras()).find((e=>!Dl.has(e.deviceId))):(await Xh.getMicrophones()).find((e=>!Dl.has(e.deviceId)));s&&(this.log_.warn(`${e?"camera":"mic"} ${t} capture fail ${i} times, change new ${s.deviceId}`),t=s.deviceId)}}return t}setAudioVolume(e){super.setAudioVolume(e)}clearCanvas(){this.canvasInterval_&&(kd.clearTask(this.canvasInterval_),this.canvasInterval_=null,this.canvas_=null,this.canvasTrack_=null)}getCanvasTrack(){if(this.canvasTrack_)return this.canvasTrack_;this.log_.info("gen canvas track");const e=this.getVideoTrack(),{width:t,height:i,frameRate:s}=e.getSettings();this.canvas_=document.createElement("canvas");const n=this.canvas_.getContext("2d");this.canvas_.width=t,this.canvas_.height=i,this.canvasInterval_=kd.run("raf",(()=>{if(this.hasVideo()){const e=this.getVideoTrack().getSettings();e.width===this.canvas_.width&&e.height===this.canvas_.height||(this.canvas_.width=e.width,this.canvas_.height=e.height)}this.videoPlayer_&&this.videoPlayer_.element_&&n.drawImage(this.videoPlayer_.element_,0,0,this.canvas_.width,this.canvas_.height)}),{fps:Math.max(15,s)});const a=this.canvas_.captureStream();return this.canvasTrack_=a.getVideoTracks()[0],this.canvasTrack_}setClient(e,t){e&&(this.log_.setUserId(e.getUserId()),this.log_.setSdkAppId(e.getSDKAppId()),t||this.syncMuteState()),this.client_=e}setAudioCaptureVolume(e=100){if(!this.hasAudio()||e<0||!Fd())return!1;if(this.captureVolume_===e)return!0;this.captureVolume_=e,this.log_.info("setCaptureVolume "+e),e/=100;const t=Ea();if(this.gain_.gainNode)this.gain_.gainNode.gain.value=e;else{var i;const s=new MediaStream;s.addTrack(this.getAudioTrack());const n=t.createMediaStreamDestination(),a=t.createMediaStreamSource(s),o=t.createGain();o.gain.value=e,a.connect(o),o.connect(n);const r=n.stream.getAudioTracks()[0],d=e=>this.log_.info(`gained audio track ${e}`);r.onmute=()=>d("muted"),r.onunmute=()=>d("unmuted"),r.onended=()=>d("ended"),this.gain_={source:a,audioTrack:r,gainNode:o},null===(i=this.connection_)||void 0===i||i.replaceTrack(r),super.restartAudio()}return!0}getGainedTrack(){return this.gain_.audioTrack}reconnectGainNode(e){this.log_.warn("reconnect gain node");const t=new MediaStream;t.addTrack(e);const i=Ea().createMediaStreamSource(t);i.connect(this.gain_.gainNode),this.gain_.source.disconnect(),this.gain_.source=i}stopGainNode(){const{audioTrack:e,source:t,gainNode:i}=this.gain_;i&&(t.disconnect(),i.disconnect(),e.onmute=null,e.onunmute=null,e.onended=null,e.stop(),this.gain_={source:null,gainNode:null,audioTrack:null}),this.captureVolume_=100}close(){this.setIsReadyToPublish(!1),this.stopGainNode(),super.close()}setIsAIDenoiser(e){this.isAIDenoiser=e}}).prototype,"setAudioProfile",[fl],Object.getOwnPropertyDescriptor(Cl.prototype,"setAudioProfile"),Cl.prototype),e(Cl.prototype,"setVideoProfile",[vl],Object.getOwnPropertyDescriptor(Cl.prototype,"setVideoProfile"),Cl.prototype),e(Cl.prototype,"setScreenProfile",[Il],Object.getOwnPropertyDescriptor(Cl.prototype,"setScreenProfile"),Cl.prototype),e(Cl.prototype,"setVideoContentHint",[yl],Object.getOwnPropertyDescriptor(Cl.prototype,"setVideoContentHint"),Cl.prototype),e(Cl.prototype,"switchDevice",[Tl],Object.getOwnPropertyDescriptor(Cl.prototype,"switchDevice"),Cl.prototype),e(Cl.prototype,"addTrack",[bl],Object.getOwnPropertyDescriptor(Cl.prototype,"addTrack"),Cl.prototype),e(Cl.prototype,"removeTrack",[El],Object.getOwnPropertyDescriptor(Cl.prototype,"removeTrack"),Cl.prototype),e(Cl.prototype,"replaceTrack",[wl],Object.getOwnPropertyDescriptor(Cl.prototype,"replaceTrack"),Cl.prototype),e(Cl.prototype,"recoverCapture",[kl],Object.getOwnPropertyDescriptor(Cl.prototype,"recoverCapture"),Cl.prototype),e(Cl.prototype,"setAudioCaptureVolume",[Rl,Al],Object.getOwnPropertyDescriptor(Cl.prototype,"setAudioCaptureVolume"),Cl.prototype),Cl);var Pl,Ml;const Ll={voiceActivityDetection:!1};let Ol=(Pl=Gc({retries:1,timeout:0,onRetrying(e){this.log_.warn(`connection timeout, retrying [${e}]`)},onError(e,t,i){e.message.includes("timeout")?(this.reset(),this.initialize(),t()):i(e)}}),e((Ml=class extends Oc{constructor(e){super(e),this.localStream_=null,this.exchangeSDPTimeout_=-1,this.localAuxStream_=null,this.publishingStream_=null,this.isPublishingAuxStream_=!1,this.smallGenerator_=null,this.isSDPExchanging_=!1,this.ssrc_={audio:0,video:0,small:0,auxiliary:0},this.mediaSettings_={videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0},this.mixedAudioTrack_=null}get isMainStreamPublished(){return!!this.localStream_}get isAuxStreamPublished(){return!!this.localAuxStream_}get publishState(){const e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this.peerConnection_){const a=this.peerConnection_.getSenders();var t,i,s,n;if(a)if(xd())e.audio=!(null===(t=a[0])||void 0===t||!t.track),e.bigVideo=!(null===(i=a[1])||void 0===i||!i.track),e.smallVideo=!(null===(s=a[2])||void 0===s||!s.track),e.auxVideo=!(null===(n=a[3])||void 0===n||!n.track);else a.forEach((t=>{t.track&&(t.track.kind===o?e.audio=!0:(e.bigVideo=!0,this.smallGenerator_&&(e.smallVideo=!0)))}))}return e}initialize(){super.initialize(),this.installEvents()}reset(){this.isReconnecting_&&this.stopReconnection(),this.closePeerConnection(),this.uninstallEvents(),this.clearExchangeSDPTimeout(),this.localStream_&&this.localStream_.clearCanvas()}close(){super.close(),this.reset(),this.emitConnectionStateChangedEvent(ce),this.smallGenerator_&&(this.smallGenerator_.destroy(),this.smallGenerator_=null)}installEvents(){this.emitter_.on(tc.ERROR,this.handleError,this),this.emitter_.on(tc.CONNECTION_STATE_CHANGED,this.handleConnectionStateChange,this)}uninstallEvents(){this.emitter_.off(tc.ERROR,this.handleError,this),this.emitter_.off(tc.CONNECTION_STATE_CHANGED,this.handleConnectionStateChange,this)}async publish(e,t){var i;this.publishingStream_=e,this.isPublishingAuxStream_=t;let s=null;e.getVideoTrack()&&!t&&this.client_.getIsEnableSmallStream()&&(this.smallGenerator_=new dl(e),await this.smallGenerator_.initialize(),s=this.smallGenerator_.generateSmallVideoTrack(this.client_.smallStreamConfig_));const n=e.getVideoProfile();if(this.client_.get2k4kFlag()){!(1===this.client_.get2k4kFlag())&&!e.getScreen()&&n.height*n.width>=3686400&&(n.width=1920,n.height=1080,this.log_.warn(Mt),await e.setVideoProfile(n))}return qs&&115===Vn()&&n.width*n.height<=230400&&(this.log_.warn("fallback video to 480p"),await e.setVideoProfile("480p_2")),this.updateMediaSettings(e,t),$d()?zs&&11===Wn?await this.publishByAddTrack(e,s):await this.publishByTransceiver(e,s,t):await this.publishByAddTrack(e,s),this.publishingStream_=null,this.isPublishingAuxStream_=!1,t?this.localAuxStream_=e:this.localStream_=e,null===(i=this.sei_)||void 0===i||i.handleEncodedStreams(),e}async publishByTransceiver(e,t,i){this.log_.info("publish by transceiver");const s=e.getMediaStream(),n=e.getAudioTrack(),a=e.getVideoTrack();let d=null;(zn||Gn)&&ga(a)&&(d=e.getCanvasTrack());const u=this.peerConnection_.getTransceivers();if(0===u.length)this.peerConnection_.addTransceiver(n||o,{direction:x,streams:[s]}),this.peerConnection_.addTransceiver(i?r:d||a||r,{direction:x,streams:[s]}),this.peerConnection_.addTransceiver(t||r,{direction:x,streams:[s]}),this.peerConnection_.addTransceiver(i?d||a:r,{direction:x,streams:[s]}),await this.connect();else{const s=[];if(n&&(u[0].sender.track?(this.mixAudioTrack(u[0].sender.track,n),await u[0].sender.replaceTrack(this.mixedAudioTrack_)):(await u[0].sender.replaceTrack(n),s.push(0)),await this.setBandwidth({bandwidth:e.getAudioBitrate(),type:o})),a){const n=i?3:1;await u[n].sender.replaceTrack(d||a),await this.setBandwidth({bandwidth:e.getVideoBitrate(),type:r,videoType:i?h:l,scaleResolutionDownBy:i?1:e.scaleResolutionDownBy}),s.push(n),t&&(await u[2].sender.replaceTrack(t),await this.setBandwidth({bandwidth:this.client_.smallStreamConfig.bitrate,type:r,videoType:c}),s.push(2))}await this.setTransceiverDirection(x,s),await this.doPublishChange()}}async publishByAddTrack(e,t){this.log_.info("publish by addtrack");const i=e.getMediaStream(),s=e.getAudioTrack(),n=e.getVideoTrack();if(s&&this.peerConnection_.addTrack(s,i),n&&(this.peerConnection_.addTrack(n,i),t)){const e=new MediaStream;e.addTrack(t),this.peerConnection_.addTrack(t,e)}await this.connect()}async unpublish(e){if(!xd())return this.doUnpublish();const t=e.getAudioTrack(),i=e===this.localAuxStream_,s=[];if(this.peerConnection_){const e=this.peerConnection_.getSenders();t&&(this.mixedAudioTrack_?(this.log_.info("has mixed audioTrack, use another audioTrack"),await e[0].replaceTrack(i?this.localStream_.getAudioTrack():this.localAuxStream_.getAudioTrack()),this.destroyMixedAudioTrack()):(await e[0].replaceTrack(null),s.push(0))),i?(await e[3].replaceTrack(null),this.localAuxStream_=null,this.mediaSettings_={...this.mediaSettings_,auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0},s.push(3)):(await e[1].replaceTrack(null),await e[2].replaceTrack(null),this.localStream_=null,this.mediaSettings_={...this.mediaSettings_,videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0},s.push(1,2))}this.localStream_||this.localAuxStream_?(await this.setTransceiverDirection(U,s),await this.doPublishChange()):await this.doUnpublish()}async doPublishChange(){const e={state:this.publishState,constraintConfig:this.mediaSettings_},t=await this.signalChannel_.sendWaitForResponse({command:Qo,data:e,responseCommand:qo.PUBLISH_STATE_CHANGE_RESULT});this.checkPublishResultCode(t.data.code,t.data.message)}doUnpublish(){return this.signalChannel_.sendWaitForResponse({command:ir,commandDesc:"unpublish",responseCommand:qo.UNPUBLISH_RESULT}).then((()=>{this.close()})).catch((()=>{this.close()}))}updateMediaSettings(e,t){this.localAuxStream_&&e===this.localAuxStream_&&(t=!0);const{detail:{isH264EncodeSupported:i,isVp8EncodeSupported:s}}=this.client_.getSystemResult();if(i?this.mediaSettings_.videoCodec="H264":s&&(this.mediaSettings_.videoCodec="VP8"),Zd){const i=e.getMediaStream();null==i||i.getTracks().forEach((i=>{const s=i.getSettings();if(i.kind===o){let t=1;s.channelCount&&(t=s.channelCount),this.mediaSettings_.audioChannel=t,this.mediaSettings_.audioBps=1e3*e.getAudioBitrate(),this.mediaSettings_.audioFs=s.sampleRate}else if(i.kind===r){if(t)return this.mediaSettings_.auxVideoWidth=s.width,this.mediaSettings_.auxVideoHeight=s.height,this.mediaSettings_.auxVideoFps=s.frameRate,void(this.mediaSettings_.auxVideoBps=1e3*e.getVideoBitrate());this.client_.getIsEnableSmallStream()&&(this.mediaSettings_.smallVideoWidth=this.client_.smallStreamConfig.width,this.mediaSettings_.smallVideoHeight=this.client_.smallStreamConfig.height,this.mediaSettings_.smallVideoFps=this.client_.smallStreamConfig.frameRate,this.mediaSettings_.smallVideoBps=1e3*this.client_.smallStreamConfig.bitrate),this.mediaSettings_.videoWidth=s.width,this.mediaSettings_.videoHeight=s.height,this.mediaSettings_.videoFps=s.frameRate,this.mediaSettings_.videoBps=1e3*e.getVideoBitrate()}}))}else this.updateMediaSettingsFromProfile(e);this.log_.info("updateMediaSettings: "+JSON.stringify(this.mediaSettings_))}updateMediaSettingsFromProfile(e){if(e){if(e.hasAudio()){const t=e.getAudioProfile();this.mediaSettings_.audioChannel=t.channelCount,this.mediaSettings_.audioBps=1e3*t.bitrate,this.mediaSettings_.audioFs=t.sampleRate}if(e.hasVideo()){const t=e.getVideoProfile();this.mediaSettings_.videoWidth=t.width,this.mediaSettings_.videoHeight=t.height,this.mediaSettings_.videoFps=t.frameRate,this.mediaSettings_.videoBps=1e3*t.bitrate}}}sendMediaSettings(e){this.updateMediaSettings(e),this.signalChannel_.sendWaitForResponse({command:mr,data:this.mediaSettings_,responseCommand:qo.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this.log_.warn(e.data.message)})).catch(this.log_.warn)}async addTrack(e,t){var i;if(!this.peerConnection_)return;const n=t===this.localAuxStream_;this.log_.info(`is adding ${e.kind} track to current published local ${n?h:R} stream`),null===(i=this.sei_)||void 0===i||i.handleEncodedStreams(),xd()?await this.addTrackByTransceiver(e,t):await this.addTrackBySender(e),ed(this.userId_,{eventId:e.kind===o?fr:Sr,eventDesc:`add ${e.kind} track to current published stream`,timestamp:s(),userId:this.userId_,tinyId:this.tinyId_})}async addTrackByTransceiver(e,t){const i=t===this.localAuxStream_,s=this.peerConnection_.getTransceivers();if(e.kind===o)s[0].sender.track?(this.mixAudioTrack(s[0].sender.track,e),await s[0].sender.replaceTrack(this.mixedAudioTrack_)):await s[0].sender.replaceTrack(e);else{const t=i?3:1;if(await s[t].sender.replaceTrack(e),1===t&&this.client_.getIsEnableSmallStream()){this.smallGenerator_=new dl(this.localStream_),await this.smallGenerator_.initialize();let e=this.smallGenerator_.generateSmallVideoTrack(this.client_.smallStreamConfig_);await s[2].sender.replaceTrack(e)}s[t].direction===U&&await this.setTransceiverDirection(x,[t])}this.updateMediaSettings(t,i),await this.doPublishChange()}async addTrackBySender(e){xd()&&this.peerConnection_.getTransceivers().findIndex((e=>"stopped"===e.direction))>=0&&(this.log_.warn("transceiver is stopping, negotiate sdp first"),await this.updateOffer(it.REMOVE,e));const t=this.peerConnection_.getSenders().find((t=>t.track&&t.track.kind===e.kind));if(t){this.log_.warn("sender already exists, remove sender first");const e=t.track;this.removeSender(t),await this.updateOffer(it.REMOVE,e)}const i=this.localStream_.getMediaStream();if(this.peerConnection_.addTrack(e,i),e.kind===r&&this.client_.getIsEnableSmallStream()){this.smallGenerator_=new dl(this.localStream_),await this.smallGenerator_.initialize();let e=this.smallGenerator_.generateSmallVideoTrack(this.client_.smallStreamConfig_);const t=new MediaStream;t.addTrack(e),this.peerConnection_.addTrack(e,t)}await this.updateOffer(it.ADD,e)}isNeedToResetOfferOrder(){if("plan-b"===this.sdpSemantics_||!this.peerConnection_||!this.peerConnection_.localDescription)return!1;const e=this.peerConnection_.localDescription.sdp,t=Sd(e);for(let i=0;it.sender&&t.sender.track===e.track))),this.peerConnection_.removeTrack(e),t&&ca(t.stop)&&(this.log_.info("stop transceiver"),t.stop())}async removeTrack(e,t){this.peerConnection_&&(this.log_.info(`is removing ${e.kind} track from current published local ${t===this.localAuxStream_?h:R} stream`),xd()?await this.removeTrackByTransceiver(e,t):await this.removeTrackBySender(e),ed(this.userId_,{eventId:e.kind===o?Ir:vr,eventDesc:`remove ${e.kind} track from current published stream`,timestamp:s(),userId:this.userId_,tinyId:this.tinyId_}))}async removeTrackByTransceiver(e,t){const i=t===this.localAuxStream_,s=this.peerConnection_.getTransceivers();if(e.kind===o)this.mixedAudioTrack_?(await s[0].sender.replaceTrack(i?this.localStream_.getAudioTrack():this.localAuxStream_.getAudioTrack()),this.destroyMixedAudioTrack()):await s[0].sender.replaceTrack(null);else{const e=i?3:1;await s[e].sender.replaceTrack(null),1===e&&this.smallGenerator_&&(this.smallGenerator_.destroy(),this.smallGenerator_=null,await s[2].sender.replaceTrack(null)),await this.setTransceiverDirection(U,[e])}this.updateMediaSettings(t,i),await this.doPublishChange()}async setTransceiverDirection(e,t){if(!Ks)return;let i=!1,s=!1;this.log_.info(`setting transceiver ${t.join(",")} direction to ${e}`);const n=this.peerConnection_.getTransceivers();if(t.forEach((t=>{n[t].direction!==e&&(n[t].direction=e,i=!0)})),i){this.log_.info("updating offer");const e=await this.peerConnection_.createOffer();await this.peerConnection_.setLocalDescription(e)}let a=-1;const o=this.peerConnection_.remoteDescription.sdp.split("\r\n").map((i=>{if(i.match(new RegExp(`a=(${U}|${$}|${x})`))&&a++,t.includes(a)){if(e===U&&i.includes(`a=${$}`))return s=!0,`a=${e}`;if(e===x&&i.includes(`a=${U}`))return s=!0,`a=${$}`}return i})).join("\r\n");s&&(this.log_.info("updating answer"),await this.peerConnection_.setRemoteDescription({type:"answer",sdp:o}))}async removeTrackBySender(e){var t;if(e.kind===r&&this.isNeedToResetOfferOrder())return this.reset(),this.initialize(),null===(t=this.localStream_.getMediaStream())||void 0===t||t.removeTrack(e),void(await this.publish(this.localStream_));const i=this.peerConnection_.getSenders().find((t=>t.track===e));i&&(this.removeSender(i),e.kind===r&&this.smallGenerator_&&(this.smallGenerator_.destroy(),this.smallGenerator_=null,this.peerConnection_.getSenders().forEach((e=>{e.track&&e.track.kind===r&&this.removeSender(e)})))),await this.updateOffer(it.REMOVE,e)}async replaceTrack(e,t){var i;const n=null===(i=this.peerConnection_)||void 0===i?void 0:i.getSenders();if(!n||0===n.length)throw new gr({code:pr.INVALID_OPERATION,message:ta({key:Oi})});const a=t===this.localAuxStream_;var d,c;if(this.log_.info(`is replacing ${e.kind} track to current published local ${a?h:R} stream`),e.kind===o&&n[0])if(this.mixedAudioTrack_&&null!==(d=this.localStream_)&&void 0!==d&&d.hasAudio()&&null!==(c=this.localAuxStream_)&&void 0!==c&&c.hasAudio()){this.destroyMixedAudioTrack();const t=a?this.localStream_.getAudioTrack():this.localAuxStream_.getAudioTrack();this.mixAudioTrack(e,t),await n[0].replaceTrack(this.mixedAudioTrack_)}else await n[0].replaceTrack(e);if(e.kind===r){if(t===this.localStream_&&n[1]&&(await n[1].replaceTrack(e),this.smallGenerator_&&n[2])){this.log_.info("replacing smallVideo"),this.smallGenerator_.destroy(),this.smallGenerator_=new dl(this.localStream_),await this.smallGenerator_.initialize();const e=this.smallGenerator_.generateSmallVideoTrack(this.client_.smallStreamConfig_);await n[2].replaceTrack(e)}t===this.localAuxStream_&&n[3]&&await n[3].replaceTrack(e)}ed(this.userId_,{eventId:e.kind===o?Nr:Dr,eventDesc:`replace ${e.kind} track from current published stream`,timestamp:s(),userId:this.userId_,tinyId:this.tinyId_})}async updateOffer(e,t){try{const i=await this.peerConnection_.createOffer(Ll);Ks&&(i.sdp=this.setSDPDirection(i.sdp,"sendrecv")),await this.peerConnection_.setLocalDescription(i);const s=this.updateMediaSettings(this.localStream_||this.localAuxStream_),n={action:e,trackId:t.id,kind:t.kind===r?"bigVideo":t.kind,type:"offer",sdp:this.peerConnection_.localDescription.sdp,constraintConfig:s,state:this.publishState};this.log_.info("createOffer success, sending updated offer to remote server"),this.log_.debug("updatedOffer: "+n.sdp);const a=await this.signalChannel_.sendWaitForResponse({command:Ko,data:n,responseCommand:qo.UPDATE_OFFER_RESULT,timeout:1e4,commandDesc:"update offer"}),{code:o,message:d}=a.data;0!==o&&this.checkPublishResultCode(o,d),await this.acceptAnswer(a.data.data),this.updateSSRC(i.sdp),sd.logSuccessEvent({userId:this.client_.getUserId(),eventType:Le,kind:"offer"})}catch(i){throw this.log_.error(i),sd.logFailedEvent({userId:this.client_.getUserId(),eventType:Le,kind:"offer",error:i}),i}}async setBandwidth({bandwidth:e,type:t,videoType:i="",sdp:s,scaleResolutionDownBy:n=1}){if(!Bd()&&s)return t===r?this.updateVideoBandwidthRestriction(s,e,i):this.updateAudioBandwidthRestriction(s,e);let a=null;if($d()){let e=0;t===r&&(e=i===c?2:i===h?3:1),a=this.peerConnection_.getSenders()[e]}else a=this.peerConnection_.getSenders().find((e=>e.track&&e.track.kind===t));if(a){const d=a.getParameters();d.encodings&&0!==d.encodings.length||(d.encodings=[{}]),"unlimited"===e?delete d.encodings[0].maxBitrate:d.encodings[0].maxBitrate=1e3*e,n>1&&(this.log_.warn(`${i} scaleResolutionDownBy ${n}`),d.encodings[0].scaleResolutionDownBy=n);try{return await a.setParameters(d),this.log_.info(i+t+" bandwidth was set to "+e+" kbps"),s}catch(o){if(this.log_.info("failed to set bandwidth by setting maxBitrate: "+o),s)return t===r?this.updateVideoBandwidthRestriction(s,e,i):this.updateAudioBandwidthRestriction(s,e)}}return s}updateVideoBandwidthRestriction(e,t,i){let s="AS";Ks&&(s="TIAS",t*=1e3);let n=0,a=-1;return i===c?n=1:i===h&&(n=2),e=e.replace(/m=video (.*)\r\nc=IN (.*)\r\n/g,(e=>(a++,a===n?`${e}b=${s}:${t}\r\n`:e)))}updateAudioBandwidthRestriction(e,t){let i="AS";return Ks&&(i="TIAS",t*=1e3),e=e.replace(/m=audio (.*)\r\nc=IN (.*)\r\n/,"m=audio $1\r\nc=IN $2\r\nb="+i+":"+t+"\r\n")}removeBandwidthRestriction(e){return e.replace(/b=AS:.*\r\n/,"").replace(/b=TIAS:.*\r\n/,"")}removeVideoOrientation(e){return e.replace(/urn:3gpp:video-orientation/,"")}async connect(){try{await this.exchangeSDP(),await this.waitForPeerConnectionConnected()}catch(e){throw this.closePeerConnection(!0),e}}async exchangeSDP(){try{this.isSDPExchanging_=!0,await this.createOffer(),this.log_.info("createOffer success, sending offer to remote server"),await this.doExchangeSDP(),this.isSDPExchanging_=!1}catch(e){throw this.isSDPExchanging_=!1,e}}async createOffer(){try{const e=await this.peerConnection_.createOffer(Ll);await this.peerConnection_.setLocalDescription(e),this.updateSSRC(e.sdp),sd.logSuccessEvent({userId:this.client_.getUserId(),eventType:Le,kind:"offer"})}catch(e){throw sd.logFailedEvent({userId:this.client_.getUserId(),eventType:Le,kind:"offer",error:e}),e}}doExchangeSDP(){return new Promise(((e,t)=>{this.exchangeSDPTimeout_=setTimeout((()=>{this.signalChannel_.off(qo.PUBLISH_RESULT,i),this.clearExchangeSDPTimeout();const e=new gr({code:pr.API_CALL_TIMEOUT,message:ta({key:Gt})});t(e)}),1e4);const i=async i=>{try{this.clearExchangeSDPTimeout();const{code:t,message:s}=i.data;0===t?(await this.acceptAnswer(i.data.data),e()):this.checkPublishResultCode(t,s)}catch(s){t(s)}},s={type:this.peerConnection_.localDescription.type,sdp:this.removeVideoOrientation(this.peerConnection_.localDescription.sdp),screen:(this.publishingStream_||this.localStream_).hasScreenTrack(),state:this.publishState,constraintConfig:this.mediaSettings_};this.signalChannel_.once(qo.PUBLISH_RESULT,i),this.log_.debug("sending sdp offer: "+s.sdp),this.signalChannel_.send(tr,s)}))}setSDPDirection(e,t,i="all"){const s=Sd(e);return s.media.forEach((e=>{"all"!==i&&e.type!==i||(e.direction=t)})),fd(s)}async acceptAnswer(e){try{let t=this.removeVideoOrientation(e.sdp);const i=this.publishingStream_||this.localStream_;if(i){const e=i.getVideoBitrate(),s=i.getAudioBitrate();if(e){const s=this.isPublishingAuxStream_?h:l;t=await this.setBandwidth({sdp:t,videoType:s,type:r,bandwidth:e,scaleResolutionDownBy:this.isPublishingAuxStream_?1:i.scaleResolutionDownBy})}s&&(t=await this.setBandwidth({bandwidth:s,type:o,sdp:t}))}if(this.client_.getIsEnableSmallStream()){const e=this.client_.smallStreamConfig;t=await this.setBandwidth({bandwidth:e.bitrate,type:r,videoType:c,sdp:t})}const s={type:e.type,sdp:t};await this.peerConnection_.setRemoteDescription(s),this.log_.debug("accepted answer: "+t),sd.logSuccessEvent({userId:this.client_.getUserId(),eventType:Oe,kind:"answer"})}catch(t){throw sd.logFailedEvent({userId:this.client_.getUserId(),eventType:Oe,kind:"answer",error:t}),this.log_.error("failed to accept remote answer "+t),t}}sendMutedFlag(e,t){if(t===this.localAuxStream_)return;const i={audio:e.audio,bigVideo:e.video,auxVideo:e.auxVideo};this.log_.info(`send muted state: ${JSON.stringify(i)}`),this.signalChannel_.send(er,i)}getIsReconnecting(){return this.isReconnecting_}async reconnect(){if(-1===this.reconnectionTimer_){if(this.reconnectionCount_>=30){this.log_.warn("SDK has tried reconnect uplink for 30 times, but all failed, please check your network"),this.stopReconnection();const e=new gr({code:pr.UPLINK_RECONNECTION_FAILED,message:ta({key:Kt})});return sd.logFailedEvent({userId:this.client_.getUserId(),eventType:Ne,error:e}),this.addEventInternal(zr,"uplink-connection reconnect fail"),this.emitConnectionStateChangedEvent(ce),void this.emitter_.emit(tc.ERROR,e)}if(this.signalChannel_.getCurrentState()!==Wo)return this.log_.warn("reconnect() signal channel is not connected, suspend reconnection until signal is connected"),void this.signalChannel_.once(Fo,this.reconnect,this);this.reconnectionCount_++;try{this.log_.warn(`reconnect() try to reconnect uplink [${this.reconnectionCount_}/30]`);const e=da(this.reconnectionCount_);if(this.reconnectionTimer_=setTimeout((()=>{this.log_.warn(`reconnect() uplink reconnect timeout(${e/1e3}s), try again`),this.clearReconnectionTimer(),this.reconnect()}),e),this.isSDPExchanging_||this.peerConnection_&&this.peerConnection_.connectionState===me)return;await this.signalChannel_.sendWaitForResponse({command:ir,responseCommand:qo.UNPUBLISH_RESULT,enableLog:!1}),this.reset(),this.initialize(),this.localStream_&&await this.publish(this.localStream_),this.localAuxStream_&&await this.publish(this.localAuxStream_,!0),sd.logSuccessEvent({userId:this.client_.getUserId(),eventType:Ne}),this.log_.warn("reconnect() uplink reconnect successfully"),this.addEventInternal(Gr,"uplink-connection reconnect success"),this.stopReconnection(),this.localStream_.syncMuteState()}catch(e){}}else this.log_.warn("reconnect() uplink is reconnecting, ignore current reconnection")}clearExchangeSDPTimeout(){-1!==this.exchangeSDPTimeout_&&(clearTimeout(this.exchangeSDPTimeout_),this.exchangeSDPTimeout_=-1)}clearReconnectionTimer(){-1!==this.reconnectionTimer_&&(clearTimeout(this.reconnectionTimer_),this.reconnectionTimer_=-1)}handleError(e){e.getCode()===pr.ICE_TRANSPORT_ERROR&&(this.isFirstConnection_&&(this.isFirstConnection_=!1,sd.logFailedEvent({userId:this.client_.getUserId(),eventType:De,error:e})),this.isReconnecting_||this.startReconnection())}handleConnectionStateChange(e){e.state===ue&&this.isFirstConnection_&&(this.isFirstConnection_=!1,sd.logSuccessEvent({userId:this.client_.getUserId(),eventType:De}),this.addEventInternal(Fr,"uplink-connection is connected"))}updateSSRC(e){try{Sd(e).media.forEach(((e,t)=>{if(e.type===o){const t=e.ssrcs[0];t&&(this.ssrc_.audio=t.id)}else{if("plan-b"===this.sdpSemantics_)return void e.ssrcGroups.forEach(((e,t)=>{const i=Number(e.ssrcs.split(" ")[0]);0===t?this.ssrc_.video=i:1===t&&(this.ssrc_.small=i)}));const i=e.ssrcs[0];if(!i)return;switch(t){case 1:this.ssrc_.video=i.id;break;case 2:this.ssrc_.small=i.id;break;case 3:this.ssrc_.auxiliary=i.id}}}))}catch(t){}}getVideoTrackId(e=r){if(this.peerConnection_){const t=this.peerConnection_.getSenders();if(e===r&&t[1]&&t[1].track)return t[1].track.id;if(e===c&&t[2]&&t[2].track)return t[2].track.id;if(e===h&&t[3]&&t[3].track)return t[3].track.id}if(this.localStream_&&e===r){const e=this.localStream_.getVideoTrack();if(e)return e.id}if(this.localAuxStream_&&e===h){const e=this.localAuxStream_.getVideoTrack();if(e)return e.id}return""}getSSRC(){return this.ssrc_}checkPublishResultCode(e,t){if(0!==e)throw 1028===e?(this.log_.error(Fs.NOT_SUPPORTED_H264ENCODE),new gr({code:pr.NOT_SUPPORTED_H264,message:ta({key:Ss})})):new gr({code:pr.UNKNOWN,message:ta({key:ws,data:{signalResponse:qo.PUBLISH_RESULT,code:e,message:t}})})}getLocalStream(){return this.localStream_}sendSEI(e,t){this.sei_.push(e,t)}mixAudioTrack(e,t){this.log_.info("mix audio track"),this.mixedAudioTrack_=function(e){const t=ba(),i=t.createMediaStreamDestination(),s=[];e.forEach((e=>{const n=new MediaStream;n.addTrack(e);const a=t.createMediaStreamSource(n);a.connect(i),s.push(a)}));const n=i.stream.getAudioTracks()[0];return cl.set(n,{destination:i,track:n,mediaStreamSourceList:s}),n}([e,t])}destroyMixedAudioTrack(){this.mixedAudioTrack_&&(this.log_.info("destroy audio track"),function(e){if(cl.has(e)){const{destination:t,track:i,mediaStreamSourceList:s}=cl.get(e);i.stop(),t.disconnect(),s.forEach((e=>{e.disconnect()})),cl.delete(e)}}(this.mixedAudioTrack_),this.mixedAudioTrack_=null)}}).prototype,"publish",[Pl],Object.getOwnPropertyDescriptor(Ml.prototype,"publish"),Ml.prototype),Ml);const Vl=new WeakMap;function Ul(){return function(e,t,i){const s=i.value,n=({fn:e,args:t,context:i,resolve:s,reject:a})=>{e.apply(i,t).then(s,a).finally((()=>{const e=Vl.get(i);e&&(e.shift(),e[0]&&n({...e[0]}))}))};return i.value=function(...e){return new Promise(((i,a)=>{if(Vl.has(this)){const o=Vl.get(this),r=o.length;o.push({fn:s,args:e,context:this,resolve:i,reject:a,name:t}),0===r&&n({fn:s,args:e,context:this,resolve:i,reject:a})}else Vl.set(this,[{fn:s,args:e,context:this,resolve:i,reject:a,name:t}]),n({fn:s,args:e,context:this,resolve:i,reject:a})}))},i}}var xl,$l,Fl,Bl,Hl;let jl=(xl=Ul(),$l=Gc({retries:1,timeout:0,onRetrying(e){this.log_.warn(`connection timeout, retrying [${e}]`)},onError(e,t,i){e.message.includes("timeout")?t():i(e)}}),Fl=Ul(),Bl=function(e=1e4){return function(t,i,s){const n=s.value;return s.value=function(...t){return new Promise(((s,a)=>{const o=setTimeout((()=>a(new Error(`${i} timeout`))),e);n.apply(this,t).then(s,a).finally((()=>{clearTimeout(o)}))}))},s}}(),e((Hl=class extends Oc{constructor(e){super(e),this.remoteStreams_=new Map,this.autoSubscribe=e.autoSubscribe,this.trackState_={audio:e.trackState.audio,video:e.trackState.video,auxiliary:e.trackState.auxiliary,smallVideo:e.trackState.smallVideo},this.ssrc_={audio:0,video:0,auxiliary:0},this.subscribeState_={audio:e.autoSubscribe,video:e.autoSubscribe,auxiliary:e.autoSubscribe,smallVideo:!1},this.isSDPExchanging_=!1,this.installEvents()}getMixUserList(){return this.mixUserList_?this.mixUserList_.map((({userId:e,flag:t})=>({userId:e,hasAudio:!!(8&t),hasVideo:!!(1&t),hasAuxiliary:!!(4&t)}))):void 0}setMixUserList(e){(!this.mixUserList_||pa(this.mixUserList_)&&!function(e,t){if(t.length===e.length){for(const i of t){const t=e.find((e=>e.userId===i.userId));if(!t||t.flag!==i.flag)return!1}return!0}return!1}(this.mixUserList_,e))&&(this.mixUserList_=e,this.emitter_.emit(tc.STREAM_UPDATED,{stream:this.getMainStream()}))}get isMainStreamSubscribed(){return(this.subscribeState_.audio||this.subscribeState_.video||this.subscribeState_.smallVideo)&&(this.trackState_.audio||this.trackState_.video||this.trackState_.smallVideo)}get isAuxStreamSubscribed(){return this.subscribeState_.auxiliary&&this.trackState_.auxiliary}get isSmallStreamSubscribed(){return this.subscribeState_.smallVideo&&this.trackState_.smallVideo}get isBigStreamSubscribed(){return this.subscribeState_.video&&this.trackState_.video}isStreamUnpublished(e){return e.getType()===R?!this.trackState_.audio&&!this.trackState_.video:!this.trackState_.auxiliary}initialize(){super.initialize(),this.peerConnection_.ontrack=this.onTrack.bind(this)}close(){var e,t,i;super.close(),this.trackState_.audio=!1,this.trackState_.video=!1,this.trackState_.smallVideo=!1,this.trackState_.auxiliary=!1,this.emitConnectionStateChangedEvent(ce),e=this,t=({fn:e,args:t,resolve:i,reject:s,name:n})=>{if("subscribe"===n){if(!this.client_.getIsJoined())return s(new gr({code:pr.API_CALL_ABORTED,message:ta({key:xs,data:{message:"leave room",stream:t[0]}})}));if(this.isStreamUnpublished(t[0]))return s(new gr({code:pr.API_CALL_ABORTED,message:ta({key:xs,data:{message:`remote user ${this.userId_} unpublished stream`,stream:t[0]}})}))}else if("unsubscribe"===n)return i();i()},null===(i=Vl.get(e))||void 0===i||i.forEach(t),Vl.delete(e),this.remoteStreams_.forEach((e=>{const t=e;t.setConnection(null),t.uninstallEvents(),t.getIsStreamAddedEventEmitted()&&this.emitter_.emit(tc.STREAM_REMOVED,{stream:t})})),this.remoteStreams_.clear(),this.uninstallEvents()}installEvents(){La.on(ao,this.onRemoteStreamUpdate,this),this.emitter_.on(tc.ERROR,(e=>{e.getCode()===pr.ICE_TRANSPORT_ERROR&&(this.isFirstConnection_&&(this.isFirstConnection_=!1,sd.logFailedEvent({userId:this.client_.getUserId(),eventType:Pe,error:e})),this.isReconnecting_||this.startReconnection())})),this.emitter_.on(tc.CONNECTION_STATE_CHANGED,(e=>{e.state===ue&&this.isFirstConnection_&&(this.isFirstConnection_=!1,sd.logSuccessEvent({userId:this.client_.getUserId(),eventType:Pe}),this.addEventInternal(Br,"downlink-connection is connected"))}))}uninstallEvents(){La.removeListener(ao,this.onRemoteStreamUpdate,this)}onRemoteStreamUpdate(e){if(this.hitTest(e.tinyId)&&e.client===this.client_){this.updateTrackState(e.action,e.kind);const t=e.kind===h?ae:ne,i=this.remoteStreams_.get(t);if(!i)return;e.action===it.ADD?this.handleRemoteAddTrack(e.kind,i):this.handleRemoteRemoveTrack(e.kind,i)}}handleRemoteAddTrack(e,t){this.log_.info(`remote add ${e} track`),e===o?t.updateAudioPlayingState(this.subscribeState_.audio):t.updateVideoPlayingState(e===h?this.subscribeState_.auxiliary:this.subscribeState_.video||this.subscribeState_.smallVideo),t.getIsStreamAddedEventEmitted()?this.emitter_.emit(tc.STREAM_UPDATED,{stream:t}):(this.emitter_.emit(tc.STREAM_ADDED,{stream:t}),this.currentState_===ue&&t.emitConnectionStateChanged({prevState:ce,state:ue}))}handleRemoteRemoveTrack(e,t){t.getIsStreamAddedEventEmitted()&&(this.log_.info(`remote remove ${e} track`),e===h||!this.trackState_.audio&&!this.trackState_.video?(this.log_.info(`remote stream ${t.getType()} removed`),this.currentState_===ue&&t.emitConnectionStateChanged({prevState:ue,state:ce}),this.emitter_.emit(tc.STREAM_REMOVED,{stream:t})):(e===o?t.updateAudioPlayingState(!1):(e!==_||this.isSmallStreamSubscribed)&&t.updateVideoPlayingState(!1),this.emitter_.emit(tc.STREAM_UPDATED,{stream:t})))}updateTrackState(e,t){const i=e===it.ADD;switch(t){case o:this.trackState_.audio=i;break;case r:this.trackState_.video=i;break;case h:this.trackState_.auxiliary=i;break;case _:this.trackState_.smallVideo=i}this.log_.info(`trackState updated: ${JSON.stringify(this.trackState_)}`)}onTrack(e){const t=e.streams[0],i=e.track;if(this.log_.info(`ontrack() kind: ${i.kind} id: ${i.id} streamId: ${t.id}`),"unified-plan"===this.sdpSemantics_){const e=function(e){let t=ad.parse(e),i={audio:[],video:[]};return t.media.forEach((e=>{if(e.ssrcs){let t=e.ssrcs[0].id>>16&255;if(e.type===o)i.audio.push(ne);else if(e.type==r){const e=t===oe?ne:ae;i.video.push(e)}}})),i}(this.peerConnection_.remoteDescription.sdp);if(i.kind===o){if(0===e.audio.length||t.id!==ne)return void this.log_.debug("skip this invalid audio track")}else if(-1===e.video.indexOf(t.id))return void this.log_.debug(`skip this invalid video track: ${i.id} msid: ${t.id}`)}sd.logEvent({eventType:"ontrack",kind:i.kind});let s=!1,n=this.remoteStreams_.get(t.id);const a=t.id===ne?re:de;if(la(n)&&(n=new sl({type:a,userId:this.userId_,client:this.client_}),n.setConnection(this),this.remoteStreams_.set(t.id,n),s=!0),n.setMediaStream(t),i.kind===o?n.updateAudioPlayingState(this.subscribeState_.audio):a===re?n.updateVideoPlayingState(this.subscribeState_.video||this.subscribeState_.smallVideo):n.updateVideoPlayingState(this.subscribeState_.auxiliary),a===de&&!this.trackState_.auxiliary)return;if(a===re&&!this.trackState_.audio&&!this.trackState_.video)return;const d=this.client_.getSubscriptionManager();d&&d.hasAutoRecoveryFlag(this.userId_,a)||(s?this.emitter_.emit(tc.STREAM_ADDED,{stream:n}):this.emitter_.emit(tc.STREAM_UPDATED,{stream:n}))}addRRTRLine(e){const t=e.split("\r\n"),i=new Map;t.forEach(((e,s)=>{/^a=rtcp-fb:/.test(e)&&t[s+1]&&!/^a=rtcp-fb:/.test(t[s+1])&&e.match(/^a=rtcp-fb:\d+/)&&i.set(s+1,e.match(/^a=rtcp-fb:\d+/)[0]+" rrtr")}));const s=[...i];for(let n=0;n{e.type===r&&e.fmtp.forEach((e=>{e.config+=";sps-pps-idr-in-keyframe=1"}))})),fd(t)}removeSDESDescription(e){const t=["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"],i=Sd(e);return i.media.forEach((e=>{e.ext=e.ext.filter((e=>!t.includes(e.uri)))})),fd(i)}isSubscriptionStateNotChanged(e,t){return e.getType()===re?(null==t?void 0:t.audio)===this.subscribeState_.audio&&(null==t?void 0:t.video)===this.subscribeState_.video&&this.isSubscribeSmall(t):e.getType()===de?!la(t.video)&&this.subscribeState_.auxiliary===t.video:void 0}isSubscribeSmall(e){return la(e.smallVideo)&&!this.subscribeState_.smallVideo}async subscribe(e,t){try{var i,s;const{emitEvent:n=!0}=t,a=e.getType();if((null===(i=this.peerConnection_)||void 0===i?void 0:i.connectionState)!==_e&&(null===(s=this.peerConnection_)||void 0===s?void 0:s.connectionState)!==me||await this.waitForPeerConnectionConnected(),this.isSubscriptionStateNotChanged(e,t))return this.peerConnection_||(this.initialize(),await this.connect()),n&&la(t.smallVideo)&&this.emitter_.emit(tc.STREAM_SUBSCRIBED,{stream:e,result:!0}),e;if(a===R?(la(t.audio)||(this.subscribeState_.audio=t.audio),la(t.video)||(this.subscribeState_.video=t.video),this.subscribeState_.smallVideo=(null==t?void 0:t.smallVideo)||!1,this.addEventInternal(this.subscribeState_.audio?wr:Rr,this.subscribeState_.audio?"subscribe audio":"unsubscribe audio"),this.addEventInternal(this.subscribeState_.video?wr:Rr,this.subscribeState_.video?"subscribe video":"unsubscribe video"),this.addEventInternal(this.subscribeState_.smallVideo?Xr:Yr,this.subscribeState_.smallVideo?"subscribe smallVideo":"unsubscribe smallVideo")):la(t.video)||(this.subscribeState_.auxiliary=t.video),this.log_.info(`subscribe ${a} stream with options ${JSON.stringify(t)} current state: ${JSON.stringify(this.subscribeState_)}`),this.peerConnection_||this.isSDPExchanging_){let t=ze;this.isMainStreamSubscribed||this.isAuxStreamSubscribed||(t=Ge),await this.sendSubscription(t),a===R?(e.updateAudioPlayingState(this.subscribeState_.audio),e.updateVideoPlayingState(this.subscribeState_.video||this.subscribeState_.smallVideo)):e.updateVideoPlayingState(this.subscribeState_.auxiliary)}else this.initialize(),await this.connect();return n&&this.emitter_.emit(tc.STREAM_SUBSCRIBED,{stream:e,result:!0}),e}catch(n){if(this.client_.getIsJoined()&&this.isStreamUnpublished(e))throw this.log_.warn(`${n.message} ${JSON.stringify(this.trackState_)}`),new gr({code:pr.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId_} unpublished stream`});throw n}}async unsubscribe(e){const t=e.getType();if(t===R){if(!this.isMainStreamSubscribed)return this.log_.info("main stream already unsubscribed"),e;this.subscribeState_.audio=!1,this.subscribeState_.video=!1,this.subscribeState_.smallVideo=!1}else{if(!this.isAuxStreamSubscribed)return this.log_.info("auxiliary stream already unsubscribed"),e;this.subscribeState_.auxiliary=!1}let i=Ge;if((t===re&&this.isAuxStreamSubscribed||t===de&&this.isMainStreamSubscribed)&&(i=ze),this.log_.info(`unsubscribe ${t} stream with ${JSON.stringify(this.subscribeState_)}`),await this.sendSubscription(i),e.updateVideoPlayingState(!1),e.updateAudioPlayingState(!1),i===Ge){const t=e.getMediaStream();t&&t.getTracks().forEach((e=>t.removeTrack(e))),this.closePeerConnection(),this.emitConnectionStateChangedEvent(ce)}return this.addEventInternal(Rr,"unsubscribe audio"),this.addEventInternal(kr,"unsubscribe video"),e}sendSubscription(e){let t={srcTinyId:this.tinyId_,srcUserId:this.userId_},i=nr,s=qo.UNSUBSCRIBE_RESULT;return e===ze&&(t={audio:this.subscribeState_.audio,bigVideo:this.subscribeState_.video,auxVideo:this.subscribeState_.auxiliary,smallVideo:this.subscribeState_.smallVideo,srcTinyId:this.tinyId_},i=ar,s=qo.SUBSCRIBE_CHANGE_RESULT),this.signalChannel_.sendWaitForResponse({command:i,data:t,responseCommand:s,timeout:1e4}).then((({data:t})=>{if(0!==t.code){const i=new gr({code:t.code,message:ta({key:Wt,data:{type:e,message:t.message}})});throw this.log_.error(i),i}}))}async connect(){try{await this.exchangeSDP(),await this.waitForPeerConnectionConnected()}catch(e){throw this.closePeerConnection(!0),e}}async exchangeSDP(){try{this.isSDPExchanging_=!0,await this.createOffer(),this.log_.info("createOffer success, sending offer to remote server");const{type:e,sdp:t}=this.peerConnection_.localDescription,i={type:e,sdp:t,srcUserId:this.userId_,srcTinyId:this.tinyId_,audio:this.subscribeState_.audio,bigVideo:this.subscribeState_.video,auxVideo:this.subscribeState_.auxiliary,smallVideo:this.subscribeState_.smallVideo};La.emit(ko,{client:this.client_,connection:this,userId:this.userId_,tinyId:this.tinyId_,role:ie,subscribeState:this.subscribeState_,trackState:this.trackState_});const s=await this.signalChannel_.sendWaitForResponse({command:sr,commandDesc:"exchange sdp",data:i,responseCommand:qo.SUBSCRIBE_RESULT,timeout:1e4});if(!this.peerConnection_){const e=new gr({code:pr.INVALID_OPERATION,message:ta({key:As})});throw this.log_.warn(e),e}await this.onSubscribeResult(s),this.isSDPExchanging_=!1}catch(e){throw this.isSDPExchanging_=!1,e}}async createOffer(){const e={voiceActivityDetection:!1};$d()&&"unified-plan"===this.sdpSemantics_?(this.peerConnection_.addTransceiver(o,{direction:"recvonly"}),this.peerConnection_.addTransceiver(r,{direction:"recvonly"}),this.peerConnection_.addTransceiver(r,{direction:"recvonly"})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);const t=await this.peerConnection_.createOffer(e),{isH264DecodeSupported:i}=await Pd();i||(this.log_.warn("remove h264 desc from sdp"),t.sdp=function(e){const t=Sd(e);return t.media.forEach((e=>{if(e.type===r){const t=new Set;e.rtp.forEach((({payload:e,codec:i})=>"H264"===i&&t.add(e))),e.fmtp.forEach((({payload:e,config:i})=>{const s=i.match(/apt=(\d+)/);s&&s[1]&&t.has(Number(s[1]))&&t.add(e)}));const i=({payload:e})=>!t.has(e);e.rtp=e.rtp.filter(i),e.rtcpFb=e.rtcpFb.filter(i),e.fmtp=e.fmtp.filter(i),e.payloads=e.payloads.split(" ").filter((e=>!t.has(Number(e)))).join(" ")}})),fd(t)}(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=function(e){const t=Sd(e);return t.media.forEach((e=>{e.type===o&&e.fmtp.forEach((e=>{e.config+=";sprop-stereo=1;stereo=1"}))})),fd(t)}(t.sdp),"unified-plan"===this.sdpSemantics_&&(t.sdp=this.removeSDESDescription(t.sdp)),await this.peerConnection_.setLocalDescription(t)}async onSubscribeResult(e){let{code:t,message:i=""}=e&&e.data||{},{type:s,sdp:n}=e&&e.data&&e.data.data||{};if(77393===t)throw this.log_.error(Fs.NOT_SUPPORTED_H264DECODE),new gr({code:pr.NOT_SUPPORTED_H264,message:ta({key:fs})});try{if(0!==t)throw new gr({code:t,message:ta({key:qt,data:{errMsg:i}})});this.log_.debug("accept remote answer: "+n),await this.peerConnection_.setRemoteDescription({type:s,sdp:n}),this.sei_&&(this.sei_.handleEncodedStreams(),this.sei_.onSEIMessage=e=>{this.emitter_.emit(tc.SEI_MESSAGE,{...e,userId:this.userId_})}),this.updateSSRC(n)}catch(a){throw this.log_.error(a),a}}updateSSRC(e){try{Sd(e).media.forEach((e=>{if(e.type===o){const t=e.ssrcs.find((e=>e.value.includes(ne)));t&&(this.ssrc_.audio=t.id)}else{const t=e.ssrcs.find((e=>e.value.includes(ne))),i=e.ssrcs.find((e=>e.value.includes(ae)));t&&(this.ssrc_.video=t.id),i&&(this.ssrc_.auxiliary=i.id)}}))}catch(t){}}setRemoteStream(e,t){this.remoteStreams_.set(e,t)}getSubscribeState(){return this.subscribeState_}getTrackState(){return this.trackState_}getSSRC(){return this.ssrc_}getMainStream(){return this.remoteStreams_.get(ne)}getAuxStream(){return this.remoteStreams_.get(ae)}getMainStreamVideoTrackId(){const e=this.getMainStream();if(e){const t=e.getVideoTrack();if(t)return t.id}return""}getAuxStreamVideoTrackId(){const e=this.getAuxStream();if(e){const t=e.getVideoTrack();if(t)return t.id}return""}async reconnect(){if(-1!==this.reconnectionTimer_)return void this.log_.warn("reconnect() downlink is reconnecting, ignore current reconnection");if(this.reconnectionCount_>=30){this.log_.warn(`SDK has tried reconnect downlink [${this.userId_}] for 30 times, but all failed, please check your network`),this.stopReconnection();const e=new gr({code:pr.DOWNLINK_RECONNECTION_FAILED,message:ta({key:zt})});return sd.logFailedEvent({userId:this.client_.getUserId(),eventType:Me,error:e}),this.addEventInternal(Qr,"downlink-connection reconnect fail"),this.emitConnectionStateChangedEvent(ce),void this.emitter_.emit(tc.ERROR,e)}if(this.signalChannel_.getCurrentState()!==Wo)return this.log_.warn("reconnect() signal channel is not connected, suspend reconnection until signal is connected"),void this.signalChannel_.once(Fo,this.reconnect,this);this.reconnectionCount_++,this.log_.warn(`reconnect() try to reconnect downlink [${this.reconnectionCount_}/30]`);const e=da(this.reconnectionCount_);if(this.reconnectionTimer_=setTimeout((()=>{this.log_.warn(`reconnect() downlink [${this.userId_}] reconnect timeout(${e/1e3}s), try again`),this.clearReconnectionTimer(),this.reconnect()}),e),!(this.isSDPExchanging_||this.peerConnection_&&this.peerConnection_.connectionState===me))try{this.closePeerConnection(),this.initialize(),await this.connect(),this.stopReconnection(),this.log_.warn("reconnect() downlink reconnect successfully"),sd.logSuccessEvent({userId:this.client_.getUserId(),eventType:Me}),this.addEventInternal(Kr,"downlink-connection reconnect success"),this.recoverSubscription()}catch(t){}}recoverSubscription(){const e=this.client_.getSubscriptionManager();e&&[...this.remoteStreams_.values()].forEach((t=>{e.hasAutoRecoveryFlag(this.userId_,t.getType())&&e.recover(t)}))}getIsReconnecting(){return this.isReconnecting_}getSubscribedMainStream(){let e=null;return this.isMainStreamSubscribed&&(e=this.remoteStreams_.get(ne)),e}clearReconnectionTimer(){-1!==this.reconnectionTimer_&&(clearTimeout(this.reconnectionTimer_),this.reconnectionTimer_=-1)}startReconnection(){const e=this.client_.getSubscriptionManager();if(e)for(let t of this.remoteStreams_.values()){const i=t.getType();(i===re&&(this.trackState_.audio||this.trackState_.video)||i===de&&this.trackState_.auxiliary)&&e.setAutoRecoveryFlag(this.userId_,t.getType())}super.startReconnection()}getCurrentState(){return this.currentState_}hasMainStream(){return this.trackState_.video||this.trackState_.audio||this.trackState_.smallVideo}hasAuxStream(){return this.trackState_.auxiliary}}).prototype,"subscribe",[xl,$l],Object.getOwnPropertyDescriptor(Hl.prototype,"subscribe"),Hl.prototype),e(Hl.prototype,"unsubscribe",[Fl],Object.getOwnPropertyDescriptor(Hl.prototype,"unsubscribe"),Hl.prototype),e(Hl.prototype,"exchangeSDP",[Bl],Object.getOwnPropertyDescriptor(Hl.prototype,"exchangeSDP"),Hl.prototype),Hl);class Jl{constructor(){this.startTime=0,this.endTime=0,this.start()}start(){0===this.startTime&&(this.startTime=va())}stop(){0===this.endTime&&(this.endTime=va())}getDuration(){return 0===this.endTime?va()-this.startTime:this.endTime-this.startTime}}class Wl{constructor(e){this.client_=e.client,this.intervalId_=-1,this.statsCalculator_=e.stats,this.prevStats_=null,this.renderFreezeMap_=new Map,this.remoteStreamMap_=new Map,this.dataFreezeMap_=new Map,this.monitorFreezeData_=new Map}installEvents(){La.on(yo,this.handlePlayVideoStart,this),La.on(So,this.onVideoTrackMuted,this),La.on(fo,this.onVideoTrackUnmuted,this),La.on(uo,this.handleStreamStopped,this),La.on(lo,this.handleStreamStopped,this),La.on(so,this.handleVideoPlaying,this)}uninstallEvents(){La.off(yo,this.handlePlayVideoStart,this),La.off(So,this.onVideoTrackMuted,this),La.off(fo,this.onVideoTrackUnmuted,this),La.off(uo,this.handleStreamStopped,this),La.off(lo,this.handleStreamStopped,this),La.off(so,this.handleVideoPlaying,this)}start(){-1===this.intervalId_&&(this.installEvents(),this.intervalId_=kd.run((async()=>{try{await this.detectFPS()}catch(e){}}),{delay:1e3}))}stop(){-1!==this.intervalId_&&(this.uninstallEvents(),kd.clearTask(this.intervalId_),this.intervalId_=-1,this.renderFreezeMap_.clear(),this.dataFreezeMap_.clear(),this.remoteStreamMap_.clear())}onVideoTrackMuted({stream:e}){if(e.getClient()!==this.client_||!e.isRemote())return;const t=e.userId_,i=e.type_,s=`${t}_${i}`,n=this.dataFreezeMap_.get(s),a=new Jl;n?n.durationItemList.push(a):this.dataFreezeMap_.set(s,{userId:t,type:i,durationItemList:[a],isFreezing(){const e=this.durationItemList[this.durationItemList.length-1];return e&&0===e.endTime}})}onVideoTrackUnmuted({stream:e}){if(e.getClient()!==this.client_||!e.isRemote())return;const t=e.userId_,i=e.type_,s=`${t}_${i}`;this.stopDataFreeze({key:s,userId:t,type:i})}handleStreamStopped({client:e,stream:t}){if(e!==this.client_)return;const i=t.getUserId(),s=t.getType(),n=`${i}_${s}`;this.stopDataFreeze({key:n,userId:i,type:s})}stopDataFreeze({key:e,userId:t,type:i}){const s=this.dataFreezeMap_.get(e);if(!s||!s.isFreezing())return;const n=s.durationItemList[s.durationItemList.length-1];n.stop();const a=n.getDuration();a>500?(sd.logEvent({eventType:"videoFrozenCount",delta:a}),this.monitorFreezeData_.set(e,{userId:t,type:i,duration:a})):s.durationItemList.pop()}getTotalDuration(e){return e.reduce(((e,t)=>{const i=t.getDuration();return e+Math.min(i,5e3)}),0)}async getStats(){const e=this.client_.getConnections(),t={};for(let[i,s]of e){if(!s.getPeerConnection())continue;const e=s.getSubscribeState(),n=s.getTrackState(),a=await this.statsCalculator_.getReceiverStats(s),o={userId:a.userId,tinyId:i,hasVideo:n.video&&e.video,hasAuxiliary:n.auxiliary&&e.auxiliary,video:{framesDecoded:0},auxiliary:{framesDecoded:0}};o.hasVideo&&(o.video.framesDecoded=a.video.framesDecoded),o.hasAuxiliary&&(o.auxiliary.framesDecoded=a.auxiliary.framesDecoded),t[a.userId]=o}return t}async detectFPS(){const e=await this.getStats();if(this.prevStats_){for(let t in e){if(!this.prevStats_[t])continue;const i=e[t].tinyId,s=this.client_.getMutedStates();if(e[t].hasVideo&&this.prevStats_[t].hasVideo&&s.has(i)&&!s.get(i).videoMuted){const i=e[t].video.framesDecoded-this.prevStats_[t].video.framesDecoded;this.handleRenderFreeze({userId:t,type:re,fps:i})}if(e[t].hasAuxiliary&&this.prevStats_[t].hasAuxiliary){const i=e[t].auxiliary.framesDecoded-this.prevStats_[t].auxiliary.framesDecoded;this.handleRenderFreeze({userId:t,type:de,fps:i})}}this.prevStats_=e}else this.prevStats_=e}async handleRenderFreeze({userId:e,fps:t,type:i}){const s=`${e}_${i}`;let n=this.renderFreezeMap_.get(s);if(t<=2){const t=va();n&&!n.isFreeze&&(n.freezeTimeline.push({startTime:t,endTime:void 0}),n.isFreeze=!0),n||this.renderFreezeMap_.set(s,{userId:e,type:i,isFreeze:!0,freezeTimeline:[{startTime:t,endTime:void 0}],renderFreezeTotal:0})}else if(n&&n.isFreeze){n.isFreeze=!1;const e=n.freezeTimeline.pop();e.endTime=va();const t=e.endTime-e.startTime;n.freezeTimeline.push(e),n.renderFreezeTotal+=Math.min(5e3,t)}}handlePlayVideoStart({stream:e}){if(e.getClient()!==this.client_||!e.isRemote()||!e.hasVideo())return;const t=`${e.getUserId()}_${e.getType()}`;this.remoteStreamMap_.has(t)||this.remoteStreamMap_.set(t,{isPlayingFired:!1})}handleVideoPlaying({stream:e}){if(!e.isRemote()||e.getClient()!==this.client_)return;const t=`${e.getUserId()}_${e.getType()}`;if(this.remoteStreamMap_.has(t)){this.remoteStreamMap_.get(t).isPlayingFired=!0}}getDataFreezeDuration(e){const t={dataFreeze:0,count:0},i=this.dataFreezeMap_.get(e);if(i){if(i.isFreezing()){const e=i.durationItemList[i.durationItemList.length-1];e.stop();e.getDuration()<500&&i.durationItemList.pop()}t.dataFreeze=this.getTotalDuration(i.durationItemList),t.count=i.durationItemList.length}return t}getRenderFreezeDuration(e){const t=this.renderFreezeMap_.get(e);let i=0,s=0;if(t)if(t.isFreeze){const e=va()-t.freezeTimeline[t.freezeTimeline.length-1].startTime;i=t.renderFreezeTotal+Math.min(e,5e3),s=t.freezeTimeline.length}else i=t.renderFreezeTotal;return{renderFreeze:i,count:s}}getMonitorFreeze(){return this.monitorFreezeData_}isBlackStream(e){if(this.remoteStreamMap_.has(e)){return!this.remoteStreamMap_.get(e).isPlayingFired}return!1}resetMonitor(){this.monitorFreezeData_.clear()}}class Gl{constructor(e){this.userId=e.userId,this.tinyId=e.tinyId,this.role=e.role===ie?"anchor":"audience"}}var zl,ql={exports:{}};zl=ql,function(e){function t(e,t){var i=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(i>>16)<<16|65535&i}function i(e,i,s,n,a,o){return t((r=t(t(i,e),t(n,o)))<<(d=a)|r>>>32-d,s);var r,d}function s(e,t,s,n,a,o,r){return i(t&s|~t&n,e,t,a,o,r)}function n(e,t,s,n,a,o,r){return i(t&n|s&~n,e,t,a,o,r)}function a(e,t,s,n,a,o,r){return i(t^s^n,e,t,a,o,r)}function o(e,t,s,n,a,o,r){return i(s^(t|~n),e,t,a,o,r)}function r(e,i){var r,d,c,l,h;e[i>>5]|=128<>>9<<4)]=i;var u=1732584193,_=-271733879,m=-1732584194,p=271733878;for(r=0;r>5]>>>t%32&255);return i}function c(e){var t,i=[];for(i[(e.length>>2)-1]=void 0,t=0;t>5]|=(255&e.charCodeAt(t/8))<>>4&15)+s.charAt(15&t);return n}function h(e){return unescape(encodeURIComponent(e))}function u(e){return function(e){return d(r(c(e),8*e.length))}(h(e))}function _(e,t){return function(e,t){var i,s,n=c(e),a=[],o=[];for(a[15]=o[15]=void 0,n.length>16&&(n=r(n,8*e.length)),i=0;i<16;i+=1)a[i]=909522486^n[i],o[i]=1549556828^n[i];return s=r(a.concat(c(t)),512+8*t.length),d(r(o.concat(s),640))}(h(e),h(t))}function m(e,t,i){return t?i?_(t,e):l(_(t,e)):i?u(e):l(u(e))}zl.exports?zl.exports=m:e.md5=m}(Na);var Kl=ql.exports;class Ql{constructor(e){this.client_=e.client,this.signalChannel_=e.signalChannel,this.log_=Oo.createLogger({id:"mix|"+this.client_.getUserId(),userId:e.client.getUserId(),sdkAppId:e.client.getSDKAppId()}),this.isMixing_=!1,this.config_=null,this.data_=null,this.remoteStreamMap_=new Map,this.installEvents()}get isPresetLayoutMode(){return this.config_&&this.config_.mode===qe.PRESET_LAYOUT}installEvents(){La.on(co,this.onStreamSubscribed,this),La.on(lo,this.onStreamUnsubscribed,this),this.client_.on("stream-removed",this.onStreamRemoved,this)}uninstallEvents(){La.off(co,this.onStreamSubscribed,this),La.off(lo,this.onStreamUnsubscribed,this),this.client_.off("stream-removed",this.onStreamRemoved,this)}reset(){this.uninstallEvents(),this.isMixing_=!1,this.config_=null}onStreamSubscribed({client:e,stream:t}){e===this.client_&&(this.remoteStreamMap_.set(t.getId(),{remoteStream:t,isUsed:!1}),this.isMixing_&&this.hasAvailablePlaceHolder()&&this.startMixTranscode(this.config_))}onStreamUnsubscribed({client:e,stream:t}){e===this.client_&&this.onStreamRemoved({stream:t})}onStreamRemoved({stream:e}){if(this.remoteStreamMap_.has(e.getId())){const{isUsed:t}=this.remoteStreamMap_.get(e.getId());this.remoteStreamMap_.delete(e.getId()),this.isMixing_&&this.isPresetLayoutMode&&t&&this.startMixTranscode(this.config_)}}async startMixTranscode(e){try{this.resetIsUsedFlag(),this.config_=e;const t=this.getInputParam(e,this.remoteStreamMap_),i=this.getOutputParam(e),s=this.getOutputSessionId({config:e,roomId:this.client_.getRoomId(),userId:this.client_.getUserId()});this.isMixing_&&this.data_&&s!==this.data_.outputSessionId&&(this.log_.info("startMixTranscode() streamId changed, stop mixing before start"),await this.doStopMixTranscode()),await this.doStartMixTranscode({outputSessionId:s,inputParam:t,outputParam:i})}catch(t){throw this.resetIsUsedFlag(),t}}async doStartMixTranscode({outputSessionId:e,inputParam:t,outputParam:i}){const s={roomId:String(this.client_.getRoomId()),mcuRequestTime:Date.now(),outputSessionId:e,inputParam:t,outputParam:i};this.data_=s,this.log_.info(`startMixTranscode: ${JSON.stringify(s)}`),this.isMixing_=!0;try{const e=await this.signalChannel_.sendWaitForResponse({command:lr,data:s,timeout:5e3,responseCommand:qo.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"});let{code:t,message:i}=e.data;if(0!==t)throw-102083===t&&(i=`Please enable relayed-push in https://console.cloud.tencent.com/trtc and try later, refer to ${Et}tutorial-26-advanced-publish-cdn-stream.html`),this.log_.error(`startMixTranscode failed, errCode: ${t} errMsg: ${i}`),this.isMixing_=!1,new gr({code:pr.START_MIX_TRANSCODE_FAILED,message:ta({key:Xi,data:{message:i},link:{className:"Client",fnName:"startMixTranscode"}})})}catch(n){throw this.isMixing_=!1,n}}reStartMixTranscode(){this.isMixing_&&this.startMixTranscode(this.config_)}async stopMixTranscode(){if(!this.isMixing_)throw new gr({code:pr.INVALID_OPERATION,message:ta({key:Zi})});await this.doStopMixTranscode(),this.resetIsUsedFlag()}async doStopMixTranscode(){const e={mcuRequestTime:Date.now(),outputSessionId:this.data_.outputSessionId,streamType:this.data_.outputParam.streamType};this.log_.info(`stopMixTranscode: ${JSON.stringify(e)}`);const t=await this.signalChannel_.sendWaitForResponse({command:hr,data:e,timeout:5e3,responseCommand:qo.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"}),{code:i,message:s}=t.data;if(0!==i)throw this.log_.error(`stopMixTranscode failed, errCode: ${i} errMsg: ${s}`),new gr({code:pr.STOP_MIX_TRANSCODE_FAILED,message:ta({key:Yi,data:{message:s},link:{className:"Client",fnName:"stopMixTranscode"}})});this.isMixing_=!1}getOutputSessionId({config:e,userId:t,roomId:i}){return ha(e.streamId)&&e.streamId.length>0?e.streamId:Kl(`${i}_${t}_main`)}getInputParam(e,t){let i=e.mixUsers.map((e=>({userId:e.userId,roomId:String(e.roomId||this.client_.getRoomId()),width:e.width||0,height:e.height||0,locationX:e.locationX||0,locationY:e.locationY||0,zOrder:e.zOrder,streamType:la(e.streamType)||e.streamType!==de?0:1,inputType:e.pureAudio?Qe.IT_PURE_AUDIO:Qe.IT_AUDIO_VIDEO,renderMode:e.renderMode||0})));return e.mode===qe.PRESET_LAYOUT&&(i.forEach((e=>{if(e.userId===Ke.REMOTE){const i=[...t.values()].find((({isUsed:e})=>!e));i&&(e.userId=i.remoteStream.getUserId(),e.streamType=i.remoteStream.getType()===de?1:0,i.isUsed=!0)}})),i=i.filter((e=>e.userId!==Ke.REMOTE))),i}getOutputParam(e){const t=e.streamId||"";return{streamId:t,streamType:t.length>0?1:0,width:la(e.videoWidth)?640:e.videoWidth,height:la(e.videoHeight)?480:e.videoHeight,videoBps:e.videoBitrate||0,fps:e.videoFramerate||15,gop:e.videoGOP||2,audioSampleRate:e.audioSampleRate||48e3,audioBps:e.audioBitrate||64,audioChannels:e.audioChannels||1,backgroundColor:e.backgroundColor||0,backgroundImg:e.backgroundImage||"",extraInfo:"",videoCodec:2,audioCodec:0}}hasAvailablePlaceHolder(){return!!this.isPresetLayoutMode&&this.data_.inputParam.length!==this.config_.mixUsers.length}resetIsUsedFlag(){this.remoteStreamMap_.forEach((e=>e.isUsed=!1))}}class Xl{constructor(e){this.client_=e.client,this.signalChannel_=e.signalChannel,this.publishTencentMainStreamObj_={params_:null,streamId_:void 0,isPublishing_:!1},this.publishTencentAuxStreamObj_={params_:null,streamId_:void 0,isPublishing_:!1},this.publishGivenCDNData_=null,this.isPublishingGivenCDN_=!1}setSignalChannel(e){this.signalChannel_=e.signalChannel}getIsPublishingTencentCDN(){return this.publishTencentMainStreamObj_.isPublishing_||this.publishTencentAuxStreamObj_.isPublishing_}getIsPublishingGivenCDN(){return this.isPublishingGivenCDN_}generatePublishCDNStreamId(e,t){if(!e){let e=`${this.client_.getRoomId()}_${this.client_.getUserId()}_${t}`;return/^[A-Za-z\d_-]*$/.test(e)||(e=Kl(e)),`${this.client_.getSDKAppId()}_${e}`}return e}generatePublishCDNSessionId(e){return Kl(`${this.client_.getRoomId()}_${this.client_.getUserId()}_${e}`)}async startPublishTencentCDN(e){if(e.streamType===u?(this.publishTencentAuxStreamObj_.params_=e,this.publishTencentAuxStreamObj_.isPublishing_=!0):(this.publishTencentMainStreamObj_.params_=e,this.publishTencentMainStreamObj_.isPublishing_=!0),!this.client_.isJoined_)return;const t=this.generatePublishCDNStreamId(e.streamId,e.streamType),i=this.generatePublishCDNSessionId(e.streamType),s=e.streamType===u?1:0,n={requestTime:Date.now(),sessionId:i,streamId:t,streamType:s};await this.doStartPublishTencentCDN(n,e.streamType)}async doStartPublishTencentCDN(e,t){try{Oo.info("startPublishTencentCDN: "+JSON.stringify(e));const i=await this.signalChannel_.sendWaitForResponseWithRetry({command:or,data:e,timeout:2e3,responseCommand:qo.START_PUBLISH_TENCENT_CDN_RES,commandDesc:"startPublishCDNStream",retries:2});let{code:s,message:n}=i.data;if(0!==s)throw t===u?this.publishTencentAuxStreamObj_.isPublishing_=!1:this.publishTencentMainStreamObj_.isPublishing_=!1,-102083===s&&(n=`Please enable relayed-push in https://console.cloud.tencent.com/trtc and try later, refer to ${Et}tutorial-26-advanced-publish-cdn-stream.html`),Oo.error(`startPublishTencentCDN failed, errCode: ${s}, errMsg: ${n}`),new gr({code:pr.START_PUBLISH_CDN_FAILED,message:ta({key:bi,data:{message:n},link:{className:"Client",fnName:"startPublishCDNStream"}})});t===u?this.publishTencentAuxStreamObj_.streamId_=e.streamId:this.publishTencentMainStreamObj_.streamId_=e.streamId}catch(i){throw t===u?this.publishTencentAuxStreamObj_.isPublishing_=!1:this.publishTencentMainStreamObj_.isPublishing_=!1,i}}resetPublishTencentParam(e){e===R&&(this.publishTencentMainStreamObj_={params_:null,streamId_:void 0,isPublishing_:!1}),e===u&&(this.publishTencentAuxStreamObj_={params_:null,streamId_:void 0,isPublishing_:!1})}async stopPublishTencentCDN(){if(!this.client_.isJoined_)return this.resetPublishTencentParam(R),void this.resetPublishTencentParam(u);this.publishTencentMainStreamObj_.isPublishing_&&await this.doStopPublishTencentCDN(R),this.publishTencentAuxStreamObj_.isPublishing_&&await this.doStopPublishTencentCDN(u)}async doStopPublishTencentCDN(e){const t={requestTime:Date.now(),sessionId:Kl(`${this.client_.getRoomId()}_${this.client_.getUserId()}_${e}`)};Oo.info("stopPublishTencentCDN: "+JSON.stringify(t));const i=await this.signalChannel_.sendWaitForResponse({command:rr,data:t,timeout:5e3,responseCommand:qo.STOP_PUBLISH_TENCENT_CDN_RES,commandDesc:"stopPublishCDNStream"});let{code:s,message:n}=i.data;if(0===s)this.resetPublishTencentParam(e);else{if(-102069!==s)throw Oo.error(`stopPublishTencentCDN failed, errCode: ${s} errMsg: ${n}`),new gr({code:pr.STOP_PUBLISH_CDN_FAILED,message:ta({key:Ei,data:{message:n},link:{className:"Client",fnName:"stopPublishCDNStream"}})});Oo.warn("stopPublishTencentCDN failed, can not stopPublishTencentCDN in auto relayed-push mode"),this.resetPublishTencentParam(e)}}async startPublishGivenCDN(e){const t=e.streamType===R?this.publishTencentMainStreamObj_.streamId_:this.publishTencentAuxStreamObj_.streamId_,i={pushRequestTime:Date.now(),pushAppId:e.appId,pushBizId:e.bizId,pushCdnUrl:e.url,pushStreamType:e.streamType,pushStreamId:t};if(Oo.info("startPublishGivenCDN: "+JSON.stringify(i)),this.publishGivenCDNData_=i,this.isPublishingGivenCDN_=!0,this.client_.isJoined_)try{const e=await this.signalChannel_.sendWaitForResponse({command:dr,data:i,timeout:5e3,responseCommand:qo.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDNStream"});let{code:t,message:s}=e.data;if(0!==t)throw Oo.error(`startPublishGivenCDN failed, errCode: ${t}, errMsg: ${s}`),this.publishGivenCDNData_=null,this.isPublishingGivenCDN_=!1,new gr({code:pr.START_PUBLISH_CDN_FAILED,message:ta({key:bi,data:{message:s},link:{className:"Client",fnName:"startPublishCDNStream"}})})}catch(s){throw this.publishGivenCDNData_=null,this.isPublishingGivenCDN_=!1,s}}async stopPublishGivenCDN(){if(!this.client_.isJoined_)return this.publishGivenCDNData_=null,void(this.isPublishingGivenCDN_=!1);let{pushAppId:e,pushBizId:t,pushCdnUrl:i,pushStreamType:s}=this.publishGivenCDNData_;const n={pushRequestTime:Date.now(),pushAppId:e,pushBizId:t,pushCdnUrl:i,pushStreamType:s};Oo.info("stopPublishGivenCDN: "+JSON.stringify(n));const a=await this.signalChannel_.sendWaitForResponse({command:cr,data:n,timeout:5e3,responseCommand:qo.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDNStream"});let{code:o,message:r}=a.data;if(0!==o)throw Oo.error(`stopPublishGivenCDN failed, errCode: ${o} errMsg: ${r}`),new gr({code:pr.STOP_PUBLISH_CDN_FAILED,message:ta({key:Ei,data:{message:r},link:{className:"Client",fnName:"stopPublishCDNStream"}})});this.publishGivenCDNData_=null,this.isPublishingGivenCDN_=!1}handleCDNConfigForJoinData(e){let t,i=e;if(this.publishTencentMainStreamObj_.isPublishing_||this.publishTencentAuxStreamObj_.isPublishing_){let e={};ha(i)&&(e=JSON.parse(i)),e.Str_uc_params||(e.Str_uc_params={}),this.publishTencentMainStreamObj_.isPublishing_&&(this.publishTencentMainStreamObj_.streamId_?e.Str_uc_params.userdefine_streamid_main=this.publishTencentMainStreamObj_.streamId_:this.publishTencentMainStreamObj_.params_&&(e.Str_uc_params.userdefine_streamid_main=this.generatePublishCDNStreamId(this.publishTencentMainStreamObj_.params_.streamId,R))),this.publishTencentAuxStreamObj_.isPublishing_&&(this.publishTencentAuxStreamObj_.streamId_?e.Str_uc_params.userdefine_streamid_aux=this.publishTencentAuxStreamObj_.streamId_:this.publishTencentAuxStreamObj_.params_&&(e.Str_uc_params.userdefine_streamid_aux=this.generatePublishCDNStreamId(this.publishTencentAuxStreamObj_.params_.streamId,u))),i=JSON.stringify(e)}if(this.isPublishingGivenCDN_){let{pushAppId:e,pushBizId:i,pushCdnUrl:s,pushStreamType:n,pushStreamId:a}=this.publishGivenCDNData_;t={pushRequestTime:Date.now(),pushAppId:e,pushBizId:i,pushCdnUrl:s,pushStreamType:n,pushStreamId:a}}return{bussinessInfo:i,pushUserCdnInfo:t}}reset(){this.resetPublishTencentParam(R),this.resetPublishTencentParam(u),this.publishGivenCDNData_=null,this.isPublishingGivenCDN_=!1}}class Yl{constructor(e){this.client_=e.client,this.durationMap_=new Map,this.installEvents()}installEvents(){La.on(co,this.handleSubscribed,this),La.on(ao,this.handleStreamTrackUpdated,this),La.on(lo,this.handleStreamStopped,this),La.on(uo,this.handleStreamStopped,this)}uninstallEvents(){La.off(co,this.handleSubscribed,this),La.off(ao,this.handleStreamTrackUpdated,this),La.off(lo,this.handleStreamStopped,this),La.off(uo,this.handleStreamStopped,this)}handleSubscribed({client:e,stream:t}){if(e!==this.client_)return;const i=t.getUserId(),s=t.getType(),n=`${i}_${s}`;if(t.hasAudio())if(t.isMainAudioSubscribed){const e=new Jl,t=this.durationMap_.get(n);t?this.isRecording(t.audio)||t.audio.push(e):this.durationMap_.set(n,{userId:i,type:s,audio:[e],video:[]})}else this.stopDurationItem(n,o);if(t.hasVideo())if(s===re&&t.isMainVideoSubscribed||s===de&&t.isAuxVideoSubscribed){const e=new Jl,t=this.durationMap_.get(n);t?this.isRecording(t.video)||t.video.push(e):this.durationMap_.set(n,{userId:i,type:s,audio:[],video:[e]})}else this.stopDurationItem(n,r)}handleStreamStopped({client:e,stream:t}){if(!this.clientHitTest(e))return;const i=`${t.getUserId()}_${t.getType()}`;this.stopDurationItem(i,o),this.stopDurationItem(i,r)}handleStreamTrackUpdated({client:e,userId:t,tinyId:i,kind:s,action:n}){if(!this.clientHitTest(e)||!this.client_.getConnections().has(i))return;const a=s===h?s:re,d=`${t}_${a}`;if(n===it.ADD){const e=this.client_.getConnections().get(i).getSubscribeState();if(s===o&&!e.audio||s===r&&!e.video||s===h&&!e.auxiliary)return;const n=new Jl,c=this.durationMap_.get(d);c?(s!==o||this.isRecording(c.audio)||c.audio.push(n),s===o||this.isRecording(c.video)||c.video.push(n)):this.durationMap_.set(d,{userId:t,type:a,audio:s===o?[n]:[],video:s===o?[]:[n]})}else this.stopDurationItem(d,s===o?o:r)}isRecording(e){return e.findIndex((e=>0===e.endTime))>=0}stopDurationItem(e,t){if(this.durationMap_.has(e)){const i=this.durationMap_.get(e)[t].find((e=>0===e.endTime));i&&i.stop()}}clientHitTest(e){return this.client_===e}getDuration(e,t){if(this.durationMap_.has(e)){return this.durationMap_.get(e)[t].reduce(((e,t)=>e+t.getDuration()),0)}return 0}getDurationMap(){return this.durationMap_}reset(){this.durationMap_.clear()}destroy(){this.client_=null,this.uninstallEvents()}}function Zl(){return function(e,t,i){const s=i.value,n=new Set;return i.value=async function(...e){if(n.has(this))throw new gr({code:pr.INVALID_OPERATION,message:ta({key:Vt,data:{name:t}})});try{n.add(this);const t=await s.apply(this,e);return n.delete(this),t}catch(i){throw n.delete(this),i}},i}}let eh=null,th=!0;function ih(e){_a(e)&&e!==th&&(th=e,Oo.info("setIsNeedToSchedule "+e))}async function sh({userId:e,sdkAppId:t,useStringRoomId:i,roomId:s,userSig:n}){if(!th&&eh)return{isCached:!0,result:eh};const a={delta:0,count:[1,1],msg:[]};try{const o=new FormData;o.append("userId",String(e)),o.append("sdkAppId",String(t)),o.append("isStrGroupId",i),o.append("groupId",String(s)),o.append("sdkVersion","4.15.19"),o.append("userSig",String(n)),_t&&o.append("oversea",!0),function(e,t){try{if(PerformanceObserver){const i=va(),s=ah(e,R),n=ah(e,A),a=new PerformanceObserver((e=>{e.getEntries().forEach((e=>{if(e.startTime>=i&&(e.name===s||e.name===n)){const i=e.name===s?R:A;if(e.code&&200!==e.code)return void Oo.warn(`${i} schedule with code ${e.code}, ${JSON.stringify(e.toJSON())}`);const n=e.responseEnd-e.startTime,o=[e.domainLookupStart-e.startTime,e.domainLookupEnd-e.domainLookupStart,e.requestStart-e.secureConnectionStart,e.secureConnectionStart-e.connectStart,e.responseStart-e.requestStart,e.responseEnd-e.responseStart].map((e=>e.toFixed(1)));a.disconnect(),sd.uploadEvent({log:`stat-schedule-net:${n.toFixed(1)}(${o.join("->")}) ${i}`,userId:t})}}))}));a.observe({type:"resource",buffered:!0})}}catch(i){}}(t,e);const r=va(),d=await function(e,t,i){return new Promise(((s,n)=>{let a=null;var o;(o=[rh((e=>t.count[0]=e+1),((e,i)=>{t.msg[0]=e.message,a||i()}))(ah(i,R),e,{get timeout(){return 1e3*ra(2+t.count[0])}}),rh((e=>t.count[1]=e+1),((e,i)=>{t.msg[1]=e.message,a||i()}))(ah(i,A),e,{get timeout(){return 1e3*ra(2+t.count[1])}})],new Promise(((e,t)=>{let i=[];o.forEach((s=>{s.then(e).catch((e=>{i.push(e),i.length===o.length&&t(i)}))}))}))).then((e=>{a=e,s(a)})).catch(n)}))}(o,a,t);return d.config&&(d.config.loggerDomain&&Z(d.config.loggerDomain),_a(d.config.scheduleCache)&&ih(!d.config.scheduleCache)),a.delta=va()-r,nh({stat:a,userId:e}),eh=d,{isCached:!1,result:d}}catch(o){const t=pa(o)?o[0]:o,i=ua(t.code)?t.code:0,n="schedule failed"+(t.message?`: ${t.message}`:""),r=new gr({code:pr.SCHEDULE_FAILED,extraCode:i,message:ta({key:ai,data:{error:n,code:i}})});throw Oo.error(r),nh({stat:a,userId:e,roomId:s,error:r}),r}}function nh({stat:e,userId:t,error:i}){i?sd.logFailedEvent({eventType:We,error:i,userId:t}):sd.logSuccessEvent({eventType:We,delta:e.delta,userId:t}),sd.uploadEvent({log:"stat-schedule:"+JSON.stringify(e),userId:t})}function ah(e,t=R){let i;return i=_t||(sa(e)?t===R?ht:ut:t===R?ct:lt),`https://${i}/api/v1/config`}function oh(e,t,i){return new Promise(((s,n)=>{Da({url:e,body:t,timeout:i.timeout}).then((e=>{0===e.data.code?s(e.data.data):n({code:e.data.code,message:e.data.msg})})).catch(n)}))}La.on($a,(()=>ih(!0))),La.on(Za,(()=>ih(!0))),La.on(eo,(()=>ih(!0))),La.on(Ya,(()=>ih(!0))),La.on(wo,(e=>{e.state===he&&ih(!0)}));const rh=(e,t)=>No({retryFunction:oh,settings:{retries:3,timeout:0},onError:t,onRetrying:e});var dh,ch,lh,hh,uh,_h,mh,ph,gh,Sh,fh,vh,Ih,yh,Th,bh,Eh,wh,kh,Rh,Ah,Ch,Dh,Nh,Ph,Mh,Lh,Oh,Vh,Uh,xh,$h,Fh=new class{constructor(){}call(e,t){return ca(this[e])?this[e](t):Promise.reject(new gr({code:pr.INVALID_PARAMETER,message:ta({key:Rs,data:{name:e}})}))}updatePrivateMapKey({privateMapKey:e,client:t}){return t.setProperty("privateMapKey",e),Promise.resolve()}};let Bh=(dh=Zl(),ch=jc(Bc.CLIENT.join),lh=Gc({retries:1,timeout:0,onError(e,t,i){this.isUsingCachedSchedule_?(this.log_.warn("is using cached schedule, retry join"),ih(!0),this.reset(),t()):(La.emit($a,{client:this,error:e}),sd.logFailedEvent({userId:this.userId_,eventType:Ie,error:e}),this.reset(),this.log_.error(e),i(e))}}),hh=Zl(),uh=Gc({retries:3}),_h=Zl(),mh=jc(...Bc.CLIENT.publish),ph=Xc(gt),gh=Zl(),Sh=jc(Bc.CLIENT.unpublish),fh=jc(...Bc.CLIENT.subscribe),vh=jc(Bc.CLIENT.unsubscribe),Ih=Zl(),yh=jc(Bc.CLIENT.switchRole),Th=Xc(gt),bh=jc(Bc.CLIENT.startPublishCDNStream),Eh=Xc(gt),wh=Xc(gt),kh=jc(Bc.CLIENT.startMixTranscode),Rh=Xc(gt),Ah=Xc(gt),Ch=Xc(gt),Dh=Xc(gt),Nh=Xc(gt),Ph=Xc(gt),Mh=Xc(gt),Lh=Hc(...Bc.CLIENT.sendSEIMessage),Oh=Xc(gt),Vh=function({timesInSecond:e,maxSizeInSecond:t,getSize:i}){return function(s,n,a){const o=a.value,r=new Map;return La.on(Xa,(({client:e})=>r.delete(e))),a.value=function(...s){let a=r.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},r.set(this,a)),0===a.timestamp?a.timestamp=Date.now():Date.now()-a.timestamp>1e3&&(a.timestamp=Date.now(),a.callCountInSecond=0,a.totalSizeInSecond=0),i&&(a.totalSizeInSecond+=i(...s)),0!==a.timestamp&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=e||a.totalSizeInSecond>t))throw new gr({code:pr.INVALID_OPERATION,message:ta({key:Vs,data:{isTimes:a.callCountInSecond>=e,isSize:a.totalSizeInSecond>t,name:n,timesInSecond:e,maxSizeInSecond:t}})});return a.callCountInSecond++,o.apply(this,s)},a}}({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...e)=>e[0].byteLength}),Uh=Xc(gt),xh=Xc(gt),$h=class{constructor(e){this.name_=gt,this.mode_=e.mode,this.sdpSemantics_="plan-b",la(e.sdpSemantics)?function(){var e;if(la(window.RTCRtpTransceiver))return!1;if(!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let t=null,i=!1;try{t=new RTCPeerConnection({sdpSemantics:"unified-plan"}),t.addTransceiver(o),i=!0}catch(s){}return null===(e=t)||void 0===e||e.close(),i}()&&(this.sdpSemantics_="unified-plan"):this.sdpSemantics_=e.sdpSemantics,this.sdkAppId_=e.sdkAppId,this.userId_=e.userId,this.log_=Oo.createLogger({id:`c${e.seq}|${this.userId_}`,userId:this.userId_,sdkAppId:this.sdkAppId_}),this.userSig_=e.userSig,this.roomId_=0,this.useStringRoomId_=e.useStringRoomId||!1,this.pureAudioPushMode_=null,this.version_=e.version,this.log_.info("using sdpSemantics: "+this.sdpSemantics_),this.signalChannel_=null,this.role_="anchor",this.privateMapKey_="",this.tinyId_=0,this.env_="",this.proxy_=null,this.unifiedProxy_=null,this.connections_=new Map,this.mutedStates_=new Map,this.userMap_=new Map,this.syncUserListInterval_=-1,this.localStream_=null,this.localAuxStream_=null,this.uplinkConnection_=null,this.emitter_=ka(new Ma,this.name_),this.isJoined_=!1,this.heartbeat_=-1,this.lastHeartBeatTime_=-1,this.stats_=new cc(this),this.joinTimeout_=-1,this.changeBigSmallRecords_=new Map,this.networkQuality_=null,this.badCaseDetector_=null,this.networkType_=aa(),this.autoSubscribe_=!!la(e.autoSubscribe)||e.autoSubscribe,this.joinedTimestamp_=0,this.joinOptions_={},this.basis_=function(){const e={browser:Yn().name+"/"+Yn().version,os:zd(),displayResolution:qd(),isScreenShareSupported:Od(),isWebRTCSupported:Dd(),isGetUserMediaSupported:Kd(),isWebAudioSupported:Qd(),isWebSocketsSupported:"WebSocket"in window&&2===window.WebSocket.CLOSING,isWebCodecSupported:Yd(),isMediaSessionSupported:"mediaSession"in navigator&&!la(navigator.mediaSession.setActionHandler),isWebTransportSupported:!la(window.WebTransport)};return navigator.userAgent.includes("miniProgram")&&(e.browser=`mini/${e.browser}`),e}(),this.initBussinessInfo_(e),this.publishedCDN_=!1,this.publishCDNData_=null,this.mixedMCU_=!1,this.mixTranscodeData_=null,this.checkSystemResult_=null,this.enableAudioVolumeEvaluation_=!1,this.audioVolumeIntervalId_=null,this.mixTranscodeManager_=null,this.publishCDNManager_=new Xl({client:this}),this.keyPointManager_=new Kc({client:this,frameWorkType:e.frameWorkType,component:e.component}),this.isPublishing_=!1,this.isEnableSmallStream_=!1,this.smallStreamConfig_={bitrate:100,frameRate:15,height:120,width:160},this.turnServers_=[],this.iceTransportPolicy_=e.iceTransportPolicy,this.schedule_={domains:null,iceServers:null,iceTransportPolicy:null,trtcCapability:null},this.isUsingCachedSchedule_=!1,this.enableAutoPlayDialog_=!!la(e.enableAutoPlayDialog)||e.enableAutoPlayDialog,this.enableMultiAuxStream_=!la(e.enableMultiAuxStream)&&e.enableMultiAuxStream,this.signalInfo_={},this.enableSEI_=!la(e.enableSEI)&&e.enableSEI,this.isDestroyed_=!1}initBussinessInfo_(e){this.bussinessInfo_=e.bussinessInfo;let t={};if(ha(e.bussinessInfo)&&(t=JSON.parse(e.bussinessInfo)),!la(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new gr({code:pr.INVALID_PARAMETER,message:ta({key:Qt})});this.pureAudioPushMode_=e.pureAudioPushMode,t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.pure_audio_push_mod=this.pureAudioPushMode_}if(!la(e.streamId)){if(!(ha(e.streamId)&&String(e.streamId)&&String(e.streamId).length<=64))throw new gr({code:pr.INVALID_PARAMETER,message:ta({key:Xt})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_streamid_main=e.streamId}if(!la(e.userDefineRecordId)){const i=/^[A-Za-z0-9_-]{1,64}$/gi;if(null===e.userDefineRecordId.match(i))throw new gr({code:pr.INVALID_PARAMETER,message:ta({key:Yt})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!la(e.userDefinePushArgs)){if(!(ha(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256))throw new gr({code:pr.INVALID_PARAMETER,message:ta({key:Zt})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_push_args=e.userDefinePushArgs}e.enableServerAudioMix&&(t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.enable_server_audio_mix=1,t.Str_uc_params.uc_biz_type=1e3),id(t)||(this.bussinessInfo_=JSON.stringify(t))}async schedule(e){const{result:t,isCached:i}=await sh({userId:this.userId_,sdkAppId:this.sdkAppId_,roomId:e,useStringRoomId:this.useStringRoomId_,version:this.version_,userSig:this.userSig_});this.isUsingCachedSchedule_=i,t&&(this.log_.info(`schedule with cache:${i} : ${JSON.stringify(t)}`),t.trtcCapability=null==t?void 0:t.trtcAutoConf,this.schedule_={...this.schedule_,...t},La.emit(Ka,this.schedule_))}getSignalChannelUrl(){const e={mainUrl:"",backupUrl:""},t=ia();return t?e.mainUrl=e.backupUrl=`wss://${t}.rtc.qq.com`:this.proxy_?e.mainUrl=e.backupUrl=this.proxy_:this.unifiedProxy_?e.mainUrl=e.backupUrl=`wss://${this.unifiedProxy_}`:Array.isArray(this.schedule_.domains)&&this.schedule_.domains.length>0&&(e.mainUrl=e.backupUrl=`wss://${this.schedule_.domains[0]}`,this.schedule_.domains[1]&&(e.backupUrl=`wss://${this.schedule_.domains[1]}`)),e}getUserId(){return this.userId_}getUserSig(){return this.userSig_}getRole(){return this.role_}getSignalInfo(){return this.signalInfo_}getRoomId(){return this.roomId_}getSDKAppId(){return this.sdkAppId_}getTinyId(){return this.tinyId_}getIceTransportPolicy(){return this.iceTransportPolicy_||this.schedule_.iceTransportPolicy||"all"}initialize(e){this.log_.info("setup signal channel");const{mainUrl:t,backupUrl:i}=this.getSignalChannelUrl();return this.signalChannel_=new nd({sdkAppId:this.sdkAppId_,userId:this.userId_,userSig:this.userSig_,roomId:e.roomId,url:t,backupUrl:i,signalDomainWhenUnifiedProxy:this.unifiedProxy_?this.schedule_.domains[0]:void 0,client:this}),this.networkQuality_||(this.networkQuality_=new lc({connections:this.connections_,signalChannel:this.signalChannel_,userId:this.userId_,client:this}),this.networkQuality_.on(ic.NETWORK_QUALITY,(e=>{this.emitter_.emit(ic.NETWORK_QUALITY,e)}))),this.deviceDetector_||(this.deviceDetector_=new hc({client:this})),this.subscriptionManager_||(this.subscriptionManager_=new nl({client:this})),this.badCaseDetector_||(this.badCaseDetector_=new Wl({client:this,stats:this.stats_})),this.callDurationCalculator_||(this.callDurationCalculator_=new Yl({client:this})),this.mixTranscodeManager_||(this.mixTranscodeManager_=new Ql({client:this,signalChannel:this.signalChannel_})),this.publishCDNManager_&&this.publishCDNManager_.setSignalChannel({signalChannel:this.signalChannel_}),this.signalChannel_.on($o,(e=>{this.log_.info(`SignalChannel state changed from ${e.prevState} to ${e.state}`),this.emitter_.emit(ic.CONNECTION_STATE_CHANGED,e)})),this.signalChannel_.on(Bo,(e=>{this.reset(),this.emitter_.emit(ic.ERROR,e)})),this.signalChannel_.once(Uo,(e=>{this.tinyId_=e.signalInfo.tinyId,La.emit(za,{client:this})})),this.signalChannel_.on(qo.PEER_JOIN,this.onPeerJoin,this),this.signalChannel_.on(qo.PEER_LEAVE,this.onPeerLeave,this),this.signalChannel_.on(qo.UPDATE_REMOTE_MUTE_STAT,(e=>{Date.now()-this.lastHeartBeatTime_>=1e4&&this.doHeartbeat(),La.emit(Ja,{client:this,data:e.data}),this.onPublishedUserList(e.data),this.onUpdateRemoteMuteStat(e.data)})),this.signalChannel_.on(qo.CLIENT_BANNED,(e=>{let t,i=e.data.data.reason;if(sd.uploadEvent({log:`stat-banned:${i}`,userId:this.userId_}),i===C)t="you got banned by the admin";else if(i===D)t="duplicated userId joining the room";else if(i===P)t="the room has been disbanded by the admin",i=i.replace("_","-");else if(i===N)return this.log_.warn(`${i} last heart beat time: ${this.lastHeartBeatTime_} interval: ${Date.now()-this.lastHeartBeatTime_}, visibility: ${document.visibilityState}`),void this.reJoin();this.log_["kick"===i?"error":"info"](`user was banned because of [${i}]`),this.reset(),this.emitter_.emit(ic.CLIENT_BANNED,{reason:i,message:ta({key:vi,data:{message:t,reason:i}})||i})})),La.emit(Ga,{client:this}),this.signalChannel_.connect()}async preJoin(e){this.joinOptions_=e,this.checkSystemResult_=await Md(),this.checkDestroy();let t=ia();t||(t=G,this.proxy_&&(this.proxy_.startsWith(J)?t=z:this.proxy_.startsWith(W)&&(t=q))),this.env_=t,sd.setConfig({env:t,sdkAppId:this.sdkAppId_,userId:this.userId_,roomId:e.roomId}),this.uploadTrtcStats();const{isH264EncodeSupported:i,isVp8EncodeSupported:s}=this.checkSystemResult_.detail;if(!Dd()||!i&&!s)throw new gr({code:pr.NOT_SUPPORTED,message:ta({key:ps})})}async join(e){this.roomId_=e.roomId,la(e.role)||(this.role_=e.role),la(e.privateMapKey)||(this.privateMapKey_=e.privateMapKey);const t=va();return La.emit(Oa,{client:this}),ed(this.userId_,{eventId:Vr,eventDesc:"joining room",timestamp:s(),userId:this.userId_,tinyId:this.tinyId_}),await this.preJoin(e),new Promise((async(i,s)=>{this.joinReject_=s;try{this.proxy_||this.schedule_.domains||await this.schedule(e.roomId),this.checkDestroy(),await this.initialize(e),await this.doJoin(e),this.signalInfo_=this.signalChannel_.getSignalInfo(),La.emit(xa,{client:this}),this.joinedTimestamp_=va(),sd.logSuccessEvent({userId:this.userId_,eventType:ye,delta:this.joinedTimestamp_-t}),sd.logSuccessEvent({userId:this.userId_,eventType:Ie}),sd.uploadEvent({log:`stat-autoplay-dialog:${this.enableAutoPlayDialog_}`,userId:this.userId_}),sd.uploadEvent({log:`stat-conv-${Kn}-${location.hostname}`,userId:this.userId_}),i()}catch(n){s(n)}this.joinReject_=null}))}checkDestroy(){if(this.isDestroyed_)throw new gr({code:pr.INVALID_OPERATION,message:ta({key:Qi,data:{funName:"join"}})})}async uploadTrtcStats(){let e,t;try{const t=await Xh.getMicrophones();e=t&&t.length}catch(l){}try{const e=await Xh.getCameras();t=e&&e.length}catch(l){}const i={microphone:e,camera:t},{isH264EncodeSupported:s,isVp8EncodeSupported:n,isH264DecodeSupported:a,isVp8DecodeSupported:o}=this.checkSystemResult_.detail,r={webRTC:this.basis_.isWebRTCSupported,getUserMedia:this.basis_.isGetUserMediaSupported,webSocket:this.basis_.isWebSocketsSupported,screenShare:this.basis_.isScreenShareSupported,webAudio:this.basis_.isWebAudioSupported,h264Encode:s,h264Decode:a,vp8Encode:n,vp8Decode:o},d={browser:this.basis_.browser,os:this.basis_.os,trtc:r,devices:i},c={isWebCodecSupported:this.basis_.isWebCodecSupported,isMediaSessionSupported:this.basis_.isMediaSessionSupported,isWebTransportSupported:this.basis_.isWebTransportSupported};sd.uploadEvent({log:"trtcstats-"+JSON.stringify(d),userId:this.userId_}),this.log_.info("TrtcStats-"+JSON.stringify(d)),sd.uploadEvent({log:"trtcadvancedstats-"+JSON.stringify(c),userId:this.userId_})}doJoin(e){return new Promise(((e,t)=>{this.log_.info(`Join() => joining room: ${this.roomId_} useStringRoomId: ${this.useStringRoomId_} mode: ${this.mode_} role: ${this.role_}`);const i={roomId:String(this.roomId_),useStringRoomId:this.useStringRoomId_,privateMapKey:this.privateMapKey_,trtcRole:"anchor"===this.role_?ie:se,trtcScene:"live"===this.mode_?te:ee,sdpSemantics:this.sdpSemantics_,version:Aa(this.version_),ua:navigator&&navigator.userAgent||"",autoSubscribe:this.autoSubscribe_,terminalType:qs?4:Ws?2:js?3:Tn?12:yn?5:bn?13:1,netType:st[aa()],bussinessInfo:this.bussinessInfo_,receiveMix:!0};if(this.publishCDNManager_){const{bussinessInfo:e,pushUserCdnInfo:t}=this.publishCDNManager_.handleCDNConfigForJoinData(this.bussinessInfo_);Object.assign(i,{bussinessInfo:e,pushUserCdnInfo:t})}this.log_.debug(`join room signal data: ${JSON.stringify(i)}`),this.joinTimeout_=setTimeout((()=>{t(new gr({code:pr.JOIN_ROOM_FAILED,message:ta({key:ni})}))}),5e3),La.emit(Va,{client:this}),this.signalChannel_.once(xo,(e=>{this.clearJoinTimeout(),La.emit(za,{client:this,error:e}),t(e)})),this.signalChannel_.send(Xo,i),this.signalChannel_.once(qo.JOIN_ROOM_RESULT,(i=>{this.clearJoinTimeout();const{code:s,message:n,data:a}=i.data;this.onPublishedUserList({data:{userList:a.publishers}}),La.emit(Ua,{client:this,code:s}),0===s?(this.isJoined_=!0,this.log_.info("Join room success, start heartbeat"),this.startHeartbeat(),this.badCaseDetector_&&this.badCaseDetector_.start(),this.syncUserList(),this.startSyncUserListInterval(),e()):(this.log_.error("Join room failed result: "+s+" error: "+n),t(new gr({code:pr.JOIN_ROOM_FAILED,extraCode:s,message:ta({key:ai,data:{error:n,code:s}})})))}))}))}async reJoin(){if(this.isJoined_){this.isJoined_=!1;try{this.log_.warn(`reJoin pending: ${this.joinOptions_.roomId}`),this.subscriptionManager_&&this.subscriptionManager_.markAllStream(),this.signalChannel_.close(),await this.signalChannel_.connect(),await this.doJoin({...this.joinOptions_,role:this.role_,privateMapKey:this.privateMapKey_}),this.log_.warn("reJoin success"),sd.logSuccessEvent({userId:this.userId_,eventType:Te}),this.checkConnectionsToReconnect(),this.uplinkConnection_&&!this.uplinkConnection_.getIsReconnecting()&&this.uplinkConnection_.startReconnection(),this.mixTranscodeManager_&&this.mixTranscodeManager_.reStartMixTranscode()}catch(e){this.log_.warn("reJoin fail "+e),this.reset(),sd.logFailedEvent({userId:this.userId_,eventType:Te,error:e}),this.emitter_.emit(ic.ERROR,new gr({code:pr.JOIN_ROOM_FAILED,message:ta({key:oi,data:{roomId:this.joinOptions_.roomId}})}))}}else this.log_.warn("reJoin abort")}async leave(){La.emit(Fa,{client:this}),ed(this.userId_,{eventId:Ur,eventDesc:"leaving room",timestamp:s(),userId:this.userId_,tinyId:this.tinyId_});try{await this.doHeartbeat()}catch(t){}this.doLeave(),La.emit(Ha,{client:this}),sd.logSuccessEvent({userId:this.userId_,eventType:be});const e=Math.floor((va()-this.joinedTimestamp_)/1e3);sd.logSuccessEvent({userId:this.userId_,eventType:Ee,delta:e})}doLeave(){this.isJoined_&&(La.emit(Ba,{client:this}),this.log_.info("leave() => leaving room"),this.signalChannel_.send(Yo),this.reset())}clearNetworkQuality(){this.networkQuality_&&(this.networkQuality_.stop(),this.networkQuality_=null)}closeConnections(){this.connections_.forEach((e=>{this.closeDownLink(e.getTinyId())}))}clearJoinTimeout(){clearTimeout(this.joinTimeout_),this.joinTimeout_=-1}destroy(){var e,t,i;if(this.isJoined_)throw this.log_.warn(Fs.INVALID_DESTROY),new gr({code:pr.INVALID_OPERATION,message:ta({key:ri})});this.isDestroyed_||(this.log_.info("destroy client"),this.joinReject_&&(this.joinReject_(new gr({code:pr.INVALID_OPERATION,message:ta({key:Qi,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.off("*"),null===(e=this.callDurationCalculator_)||void 0===e||e.destroy(),null===(t=this.keyPointManager_)||void 0===t||t.destroy(),null===(i=this.deviceDetector_)||void 0===i||i.destroy(),this.callDurationCalculator_=null,this.keyPointManager_=null,this.deviceDetector_=null,this.badCaseDetector_=null,this.publishCDNManager_=null,this.isDestroyed_=!0,La.emit(Xa,{client:this}))}reset(){this.isJoined_=!1,this.schedule_={domains:null,iceServers:null,iceTransportPolicy:null,trtcCapability:null},this.keyPointManager_&&this.keyPointManager_.prepareReport(),this.mixTranscodeManager_&&(this.mixTranscodeManager_.reset(),this.mixTranscodeManager_=null),this.publishCDNManager_&&this.publishCDNManager_.reset(),this.userMap_.clear(),this.stopSyncUserListInterval(),this.stopHeartbeat(),this.closeConnections(),this.mutedStates_.clear(),this.clearNetworkQuality(),this.badCaseDetector_&&this.callDurationCalculator_&&this.uploadAllCallStats(),this.closeUplink(),this.signalChannel_&&(this.log_.info("destroying SignalChannel"),this.signalChannel_.close(),this.signalChannel_=null),this.stats_.reset()}startSyncUserListInterval(){-1===this.syncUserListInterval_&&(this.syncUserListInterval_=kd.run(Pt,this.syncUserList.bind(this)))}stopSyncUserListInterval(){kd.clearTask(this.syncUserListInterval_),this.syncUserListInterval_=-1}async syncUserList(){try{const e=await this.getUserList();0!==this.userMap_.size&&this.userMap_.forEach((t=>{e.findIndex((({userId:e})=>e===t.userId))<0&&(this.log_.info(`peer leave detected: ${t.userId}`),this.cleanUser({userId:t.userId,tinyId:t.tinyId}))})),e.forEach((e=>{const{userId:t}=e;this.userMap_.has(t)||t===this.userId_||(this.userMap_.set(t,e),this.emitter_.emit(ic.PEER_JOIN,{userId:t}))}))}catch(e){this.log_.warn("sync user list failed: "+e)}}getUserList(){return this.signalChannel_?this.signalChannel_.sendWaitForResponse({command:ur,responseCommand:qo.USER_LIST_RES,enableLog:!1,timeout:2e3}).then((({data:e})=>{const{code:t,message:i}=e;if(0===t){return(e.data&&e.data.userList||[]).map((({userId:e,srcTinyId:t,role:i})=>new Gl({userId:e,tinyId:t,role:i})))}throw ta({key:ws,data:{signalResponse:qo.USER_LIST_RES,code:t,message:i}})})):[]}async publish(e,t={isAuxiliary:!1}){e.setPublishState(at),this.isPublishing_=!0;const i=va();La.emit(Wa,{client:this,stream:e});const n=t.isAuxiliary,a=n?h:R,o=e.getScreen();this.log_.info(`publish() => publishing ${o?d+" ":""}${a} stream ${e.getId()}`);let r=this.uplinkConnection_;try{r||(r=new Ol({userId:this.userId_,tinyId:this.tinyId_,client:this,isUplink:!0,signalChannel:this.signalChannel_,enableSEI:this.enableSEI_}),r.initialize(),r.on(tc.ERROR,(e=>{const t=e.getCode();t!==pr.ICE_TRANSPORT_ERROR&&(t===pr.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emitter_.emit(ic.ERROR,e))}))),e.setConnection(r),await r.publish(e,n),this.log_.info(`local ${o?d+" ":""}${a} stream is published`),this.isPublishing_=!1,n?this.localAuxStream_=e:(this.localStream_=e,this.deviceDetector_&&this.deviceDetector_.setLocalStream(this.localStream_),this.localStream_.getBeautyStatus()&&this.log_.info("beauty stream is published successfully")),e.setPublishState(ot),e.setClient(this,n),this.uplinkConnection_=r;const t=va()-i;sd.logSuccessEvent({userId:this.userId_,eventType:we}),sd.logSuccessEvent({userId:this.userId_,eventType:ke,delta:t}),e.hasAudio()&&ed(this.userId_,{eventId:fr,eventDesc:"publish audio track",timestamp:s(),userId:this.userId_,tinyId:this.tinyId_}),e.hasVideo()&&ed(this.userId_,{eventId:Sr,eventDesc:"publish video track",timestamp:s(),userId:this.userId_,tinyId:this.tinyId_}),this.networkQuality_&&this.networkQuality_.setUplinkConnection(this.uplinkConnection_),La.emit(_o,{localStream:e,isAuxiliary:n,client:this}),this.notPublishWithoutH264Supported_=!1,e.isAIDenoiser&&Qc.handleFunctionState({fnName:"AI_DENOISER"})}catch(c){throw c instanceof gr&&c.getCode()===pr.NOT_SUPPORTED_H264&&(this.notPublishWithoutH264Supported_=!0),e.setPublishState(nt),r.close(),this.log_.error("failed to publish stream "+c),this.isPublishing_=!1,sd.logFailedEvent({userId:this.userId_,eventType:we,error:c}),c}}async unpublish(e){if(!this.uplinkConnection_)return;const t=e===this.localAuxStream_,i=e.getScreen();this.log_.info(`unpublish() => unpublishing local ${i?d+" ":""}${t?h:R} stream`);try{await this.uplinkConnection_.unpublish(e),sd.logSuccessEvent({userId:this.userId_,eventType:Re})}catch(n){this.log_.warn(`unpublish error ${n}`),sd.logFailedEvent({userId:this.userId_,eventType:Re,error:n})}e.setClient(null),e.setConnection(null),t?this.localAuxStream_=null:(this.localStream_=null,e.hasAudio()&&ed(this.userId_,{eventId:Ir,eventDesc:"unpublish audio track",timestamp:s(),userId:this.userId_,tinyId:this.tinyId_}),e.hasVideo()&&ed(this.userId_,{eventId:vr,eventDesc:"unpublish video track",timestamp:s(),userId:this.userId_,tinyId:this.tinyId_})),this.localStream_||this.localAuxStream_||this.closeUplink()}closeUplink(){this.uplinkConnection_&&(this.uplinkConnection_.close(),this.uplinkConnection_=null,this.networkQuality_&&this.networkQuality_.setUplinkConnection(null),this.localStream_&&(this.localStream_.setClient(null),this.localStream_.setConnection(null),this.localStream_=null),this.localAuxStream_&&(this.localAuxStream_.setClient(null),this.localAuxStream_.setConnection(null),this.localAuxStream_=null),this.deviceDetector_&&this.deviceDetector_.setLocalStream(null))}closeDownLink(e){const t=this.connections_.get(e);t&&(t.getIsReconnecting()&&t.stopReconnection(),this.subscriptionManager_&&this.subscriptionManager_.delete(t.getUserId()),t.close(),this.connections_.delete(e),this.mutedStates_.delete(e))}async subscribe(e,t){this.log_.info(`subscribe() => subscribe to [${e.getUserId()}] ${e.getType()} stream with options: ${JSON.stringify(t)}`),la(t)&&(t={audio:!0,video:!0}),la(t.audio)&&(t.audio=!0),la(t.smallVideo)?la(t.video)&&(t.video=!0):t.smallVideo?la(t.video)?(t.video=!1,t.smallVideo=!0):t.video&&(t.video=!0,delete t.smallVideo,this.log_.warn("options.video and options.smallVideo can't be both true")):la(t.video)&&(t.video=!0,delete t.smallVideo),t.video&&this.changeBigSmallRecords_.delete(e.getUserId());const i=e.getConnection();t.smallVideo&&(i.getTrackState().smallVideo||(this.setRemoteVideoStreamType(e,"small"),t.video=!0,delete t.smallVideo));try{La.emit(ro,{client:this,stream:e}),await i.subscribe(e,t),this.subscriptionManager_&&this.subscriptionManager_.addSubscriptionRecord(e.getUserId(),e,t),this.notSubscribeWithoutH264Supported_=!1,sd.logSuccessEvent({userId:this.userId_,eventType:Ae})}catch(s){const t=s instanceof gr?s.getCode():pr.UNKNOWN;let i;throw t===pr.NOT_SUPPORTED_H264&&(this.notSubscribeWithoutH264Supported_=!0),i=new gr(t===pr.REMOTE_STREAM_NOT_EXIST?{code:pr.API_CALL_ABORTED,message:ta({key:xs,data:{message:s.message,stream:e}})}:{code:t,message:ta({key:mi,data:{message:s.message,stream:e}})}),i.getCode()===pr.API_CALL_ABORTED?this.log_.warn(i):this.log_.error(i),sd.logFailedEvent({userId:this.userId_,eventType:Ae,error:i}),i}}async unsubscribe(e){this.log_.info(`unsubscribe() => unsubscribe to [${e.getUserId()}] ${e.getType()} stream`);try{const t=e.getConnection();await t.unsubscribe(e),this.subscriptionManager_&&this.subscriptionManager_.addUnsubscriptionRecord(e.getUserId(),e),La.emit(lo,{client:this,stream:e}),sd.logSuccessEvent({userId:this.userId_,eventType:Ce})}catch(t){throw sd.logFailedEvent({userId:this.userId_,eventType:Ce,error:t}),t}}async switchRole(e){this.role_!==e&&("audience"===e&&this.uplinkConnection_&&this.closeUplink(),this.log_.info("switchRole() => switch role to: "+e),await this.doSwitchRole(e))}doSwitchRole(e){var t,i;const s={command:_r,data:{role:"anchor"===e?ie:se,privateMapKey:this.privateMapKey_},responseCommand:qo.SWITCH_ROLE_RES,retries:(null===(t=this.schedule_.config)||void 0===t||null===(i=t.retries)||void 0===i?void 0:i.switchRole)||1};return this.log_.info("switchRole signal data: "+JSON.stringify(s.data)),this.signalChannel_.sendWaitForResponseWithRetry(s).then((t=>{const{code:i,message:s}=t.data;if(0!==i)throw new gr({code:pr.SWITCH_ROLE_FAILED,message:ta({key:fi,data:{errMsg:s,errCode:i}})});this.role_=e})).catch((e=>{throw e instanceof gr&&e.getCode()===pr.API_CALL_TIMEOUT&&(e=new gr({code:pr.SWITCH_ROLE_FAILED,message:ta({key:Si})})),this.log_.error(e),e}))}on(e,t,i){this.emitter_.on(e,t,i)}off(e,t,i){"*"===e?this.emitter_.removeAllListeners():this.emitter_.off(e,t,i)}getRemoteMutedState(){const e=[];return this.mutedStates_.forEach(((t,i,s)=>{const n=this.connections_.get(i);n&&e.push({userId:n.getUserId(),...t})})),e}async getTransportStats(){let e={rtt:0,downlinksRTT:{}};if(this.uplinkConnection_){const t=await this.stats_.getSenderStats(this.uplinkConnection_);e.rtt=t.rtt}for(let[t,i]of this.connections_){const t=await this.stats_.getReceiverStats(i);e.downlinksRTT[t.userId]=t.rtt}return e}async getLocalAudioStats(){const e={};if(e[this.userId_]={bytesSent:0,packetsSent:0},this.uplinkConnection_){const t=await this.stats_.getSenderStats(this.uplinkConnection_);e[this.userId_]={bytesSent:t.audio.bytesSent,packetsSent:t.audio.packetsSent}}return e}async getLocalVideoStats(){const e={};if(e[this.userId_]={bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0},this.uplinkConnection_){const t=await this.stats_.getSenderStats(this.uplinkConnection_);e[this.userId_]={bytesSent:t.video.bytesSent,packetsSent:t.video.packetsSent,framesEncoded:t.video.framesEncoded,framesSent:t.video.framesSent,frameWidth:t.video.frameWidth,frameHeight:t.video.frameHeight}}return e}async getRemoteAudioStats(){const e={};for(let[t,i]of this.connections_){const{audioDelay:t}=i.getDelay(),s=await this.stats_.getReceiverStats(i);s.hasAudio&&(e[s.userId]={bytesReceived:s.audio.bytesReceived,packetsReceived:s.audio.packetsReceived,packetsLost:s.audio.packetsLost,end2EndDelay:t})}return e}async getRemoteVideoStats(e=re){const t={};for(let[i,s]of this.connections_){const i=await this.stats_.getReceiverStats(s),{videoDelay:n}=s.getDelay();e===re&&i.hasVideo&&(t[i.userId]={bytesReceived:i.video.bytesReceived,packetsReceived:i.video.packetsReceived,packetsLost:i.video.packetsLost,framesDecoded:i.video.framesDecoded,frameWidth:i.video.frameWidth,frameHeight:i.video.frameHeight,end2EndDelay:n}),e===de&&i.hasAuxiliary&&(t[i.userId]={bytesReceived:i.auxiliary.bytesReceived,packetsReceived:i.auxiliary.packetsReceived,packetsLost:i.auxiliary.packetsLost,framesDecoded:i.auxiliary.framesDecoded,frameWidth:i.auxiliary.frameWidth,frameHeight:i.auxiliary.frameHeight,end2EndDelay:n})}return t}getSdpSemantics(){return this.sdpSemantics_}getIceServers(){return 0===this.turnServers_.length&&this.schedule_.iceServers?this.schedule_.iceServers:this.turnServers_}getConnections(){return this.connections_}getMutedStates(){return this.mutedStates_}startHeartbeat(){-1===this.heartbeat_&&(this.log_.info("startHeartbeat..."),this.heartbeat_=kd.run(Pt,this.doHeartbeat.bind(this),{delay:2e3}))}stopHeartbeat(){-1!==this.heartbeat_&&(this.log_.info("stopHeartbeat"),kd.clearTask(this.heartbeat_),this.heartbeat_=-1,this.lastHeartBeatTime_=-1)}async doHeartbeat(){var e;const t=this.badCaseDetector_.getMonitorFreeze(),i=await this.stats_.getStatsReport({uplinkConnection:this.uplinkConnection_,downlinkConnections:this.connections_,freezeMap:t});if(La.emit(ja,{client:this,stats:i}),null===(e=this.badCaseDetector_)||void 0===e||e.resetMonitor(),!this.signalChannel_)return;const s=this.signalChannel_.isConnected()?function(e){let t=Zr.get(e),i=[];return t?(Zr.delete(e),i=t.map((e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,str_event_json:e.eventDesc})))):i=[],i}(this.userId_):[],n={str_sdk_version:this.version_,uint64_datetime:(new Date).getTime(),msg_user_info:{str_identifier:this.userId_,uint64_tinyid:this.tinyId_},msg_device_info:{uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:st[this.networkType_]},...i,msg_event_msg:s};this.signalChannel_.send(Zo,n);const a=Date.now();this.lastHeartBeatTime_>0&&a-this.lastHeartBeatTime_>1e4&&this.log_.warn("heartbeat took "+(a-this.lastHeartBeatTime_)),this.lastHeartBeatTime_=a,!this.isRelayChanged_&&this.isRelayMaybeFailed()&&(this.reJoin(),this.isRelayChanged_=!0)}onRemoteStreamAdded(e){const t=e.content,{userId:i,tinyId:s,audio:n,bigVideo:a,auxVideo:o,smallVideo:r}=t;if(null===i)return void this.log_.warn("received null userId on stream added");this.userMap_.has(i)||(this.userMap_.set(i,new Gl({userId:i,tinyId:s,role:"anchor"})),this.emitter_.emit(ic.PEER_JOIN,{userId:i}));const d=this.connections_.get(s);if(d){if(d.getIsReconnecting())return;this.log_.warn("duplicated stream-added observed, rebuild the connection"),d.close(),this.connections_.delete(s)}const c={audio:n,video:a,auxiliary:o,smallVideo:r};this.log_.info(`remote peer [${i}] published stream. trackState: ${JSON.stringify(c)}`),this.createDownlinkConnection({userId:i,tinyId:s,trackState:c})}createDownlinkConnection({userId:e,tinyId:t,trackState:i}){const s=new jl({userId:e,tinyId:t,client:this,isUplink:!1,signalChannel:this.signalChannel_,autoSubscribe:this.autoSubscribe_,trackState:i,enableSEI:this.enableSEI_});this.connections_.set(t,s),this.installDownlinkEvents(s,e,t),this.autoSubscribe_?(s.initialize(),s.connect().catch((()=>{!s.getMainStream()&&s.hasMainStream()&&this.initRemoteStream({type:re,userId:e,downlinkConnection:s}),!s.getAuxStream()&&s.hasAuxStream()&&this.initRemoteStream({type:de,userId:e,downlinkConnection:s})}))):(s.hasMainStream()&&this.initRemoteStream({type:re,userId:e,downlinkConnection:s}),s.hasAuxStream()&&this.initRemoteStream({type:de,userId:e,downlinkConnection:s}))}initRemoteStream({type:e,userId:t,downlinkConnection:i}){const s=new sl({type:e,userId:t,client:this});s.setConnection(i),i.setRemoteStream(e===re?ne:ae,s),s.setIsStreamAddedEventEmitted(!0),La.emit(oo,{client:this,stream:s}),this.emitter_.emit(ic.STREAM_ADDED,{stream:s})}installDownlinkEvents(e,t,i){e.on(tc.SEI_MESSAGE,(e=>{this.emitter_.emit(ic.SEI_MESSAGE,e)})),e.on(tc.STREAM_ADDED,(e=>{e.stream.setIsStreamAddedEventEmitted(!0),La.emit(oo,{client:this,stream:e.stream}),this.emitter_.emit(ic.STREAM_ADDED,{stream:e.stream})})),e.on(tc.STREAM_REMOVED,(e=>{this.changeBigSmallRecords_.delete(e.stream.getUserId()),e.stream.stop(),e.stream.setIsStreamAddedEventEmitted(!1),this.subscriptionManager_&&this.subscriptionManager_.deleteAutoRecoveryFlag(e.stream.getUserId(),e.stream.getType()),La.emit(uo,{client:this,stream:e.stream}),this.emitter_.emit(ic.STREAM_REMOVED,{stream:e.stream})})),e.on(tc.STREAM_UPDATED,(t=>{La.emit(ho,{client:this,stream:t.stream});const i=e.getMixUserList();i&&(t.mixUserList=i),this.emitter_.emit(ic.STREAM_UPDATED,t)})),e.on(tc.STREAM_SUBSCRIBED,(e=>{La.emit(co,{client:this,stream:e.stream}),this.emitter_.emit(ic.STREAM_SUBSCRIBED,{stream:e.stream})})),e.on(tc.ERROR,(e=>{const t=e.getCode();t!==pr.ICE_TRANSPORT_ERROR&&(t===pr.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLink(i),this.emitter_.emit(ic.ERROR,e))}))}onPeerJoin(e){const{srcTinyId:t,userId:i,role:s}=e.data.data;this.userMap_.has(i)||(this.userMap_.set(i,new Gl({userId:i,tinyId:t,role:s})),this.emitter_.emit(ic.PEER_JOIN,{userId:i}))}onPeerLeave(e){const{srcTinyId:t,userId:i,reason:s=0}=e.data.data;this.log_.info(`peer leave [${i}]: ${Nt[s]}`),this.cleanUser({userId:i,tinyId:t})}cleanUser({userId:e,tinyId:t}){this.userMap_.delete(e),this.closeDownLink(t),this.emitter_.emit(ic.PEER_LEAVE,{userId:e})}onPublishedUserList(e){try{const t=[...e.data.userList];e.data.mixRobotList&&t.push(...e.data.mixRobotList),e.data.fakeMixUser&&t.push(e.data.fakeMixUser);const i=t.map((e=>e.userId));this.connections_.forEach((e=>{const t=e.getUserId(),s=e.getTinyId();i.findIndex((e=>e===t))<0&&(this.log_.info(`peer unpublished detected [${t}]`),this.closeDownLink(s))})),t.forEach((({userId:e,srcTinyId:t,flag:i,mixUserList:s})=>{if(e===this.userId_)return;const n=!!(1&i),a=!!(8&i),d=!!(4&i),c=!!(2&i),l=this.connections_.get(t);if((c||n)&&this.checkSubscribeBigSmallVideo(l,c),l){const{audio:i,video:u,auxiliary:m,smallVideo:p}=l.getTrackState();pa(s)&&l.setMixUserList(s),!u&&n&&La.emit(ao,{client:this,tinyId:t,userId:e,action:it.ADD,kind:r}),!i&&a&&La.emit(ao,{client:this,tinyId:t,userId:e,action:it.ADD,kind:o}),!m&&d&&La.emit(ao,{client:this,tinyId:t,userId:e,action:it.ADD,kind:h}),!p&&c&&La.emit(ao,{client:this,tinyId:t,userId:e,action:it.ADD,kind:_}),u&&!n&&La.emit(ao,{client:this,tinyId:t,userId:e,action:it.REMOVE,kind:r}),i&&!a&&La.emit(ao,{client:this,tinyId:t,userId:e,action:it.REMOVE,kind:o}),m&&!d&&La.emit(ao,{client:this,tinyId:t,userId:e,action:it.REMOVE,kind:h}),p&&!c&&La.emit(ao,{client:this,tinyId:t,userId:e,action:it.REMOVE,kind:_})}else this.log_.info(`peer published detected [${e}]`),this.onRemoteStreamAdded({content:{audio:a,bigVideo:n,auxVideo:d,smallVideo:c,userId:e,tinyId:t}})}))}catch(t){}}onUpdateRemoteMuteStat(e){const t=e.data;(t&&t.userList||[]).forEach((e=>{const{srcTinyId:t,userId:i}=e;if(0===t||t===this.tinyId_)return;const s=this.connections_.get(t);if(!s)return void this.mutedStates_.delete(t);const n=s.getMainStream();if(!n||!n.getIsStreamAddedEventEmitted())return;const a=!!(1&e.flag),o=!!(8&e.flag),r=!!(2&e.flag),d=!!(64&e.flag),c=!!(16&e.flag),l=this.mutedStates_.get(t);if(void 0===l)return this.mutedStates_.set(t,{hasAudio:o,hasVideo:a,hasSmall:r,audioMuted:d,videoMuted:c}),a?c?this.emitter_.emit(ic.MUTE_VIDEO,{userId:i}):this.emitter_.emit(ic.UNMUTE_VIDEO,{userId:i}):this.emitter_.emit(ic.MUTE_VIDEO,{userId:i}),void(o?d?this.emitter_.emit(ic.MUTE_AUDIO,{userId:i}):this.emitter_.emit(ic.UNMUTE_AUDIO,{userId:i}):this.emitter_.emit(ic.MUTE_AUDIO,{userId:i}));{const e=!l.audioMuted&&l.hasAudio,s=!d&&o,n=!l.videoMuted&&l.hasVideo,h=!c&&a;this.mutedStates_.set(t,{hasAudio:o,hasVideo:a,hasSmall:r,audioMuted:d,videoMuted:c}),e!==s&&(s?this.emitter_.emit(ic.UNMUTE_AUDIO,{userId:i}):this.emitter_.emit(ic.MUTE_AUDIO,{userId:i})),n!==h&&(h?this.emitter_.emit(ic.UNMUTE_VIDEO,{userId:i}):this.emitter_.emit(ic.MUTE_VIDEO,{userId:i}))}}))}getEnv(){return this.env_}getSubscriptionManager(){return this.subscriptionManager_}async startPublishCDNStream(e={}){if(this.log_.info(`startPublishCDNStream with params: ${JSON.stringify(e)}; isJoined: ${this.isJoined_}; hasMainStream: ${!!this.localStream_}; hasAuxStream: ${!!this.localAuxStream_};`),e.streamType=e.streamType||R,e.streamType===h&&(e.streamType=u),e.streamId=e.streamId||"",this.isJoined_){if(e.streamType===R&&!this.localStream_)throw new gr({code:pr.INVALID_OPERATION,message:ta({key:Ii})});if(e.streamType===u&&!this.localAuxStream_)throw new gr({code:pr.INVALID_OPERATION,message:ta({key:Ii})})}await this.publishCDNManager_.startPublishTencentCDN(e),e.appId&&e.bizId&&e.url&&await this.publishCDNManager_.startPublishGivenCDN(e)}async stopPublishCDNStream(){if(!this.publishCDNManager_.getIsPublishingTencentCDN())throw new gr({code:pr.INVALID_OPERATION,message:ta({key:yi})});this.log_.info("stopPublishCDNStream"),await this.publishCDNManager_.stopPublishTencentCDN(),this.publishCDNManager_.getIsPublishingGivenCDN()&&await this.publishCDNManager_.stopPublishGivenCDN()}async startMixTranscode(e){if(!this.isJoined_||!this.mixTranscodeManager_)throw new gr({code:pr.INVALID_OPERATION,message:ta({key:wi})});la(e.mode)&&(e.mode=qe.MANUAL);try{this.log_.info(`startMixTranscode with config ${JSON.stringify(e)}`),sd.uploadEvent({log:`mix-transcode-mode:${e.mode}`,userId:this.userId_}),await this.mixTranscodeManager_.startMixTranscode(e),sd.logSuccessEvent({userId:this.userId_,eventType:He})}catch(t){throw sd.logFailedEvent({userId:this.userId_,eventType:He,error:t}),t}}async stopMixTranscode(){if(!this.isJoined_||!this.mixTranscodeManager_)throw new gr({code:pr.INVALID_OPERATION,message:ta({key:ki})});try{await this.mixTranscodeManager_.stopMixTranscode(),sd.logSuccessEvent({userId:this.userId_,eventType:je})}catch(e){throw sd.logFailedEvent({userId:this.userId_,eventType:je,error:e}),e}}getSystemResult(){return this.checkSystemResult_}enableAudioVolumeEvaluation(e=2e3,t=!1){if(!ua(e))throw new gr({code:pr.INVALID_PARAMETER,message:ta({key:Ri})});if(this.log_.info("enableAudioVolumeEvaluation with interval: "+e),e<=0)return this.enableAudioVolumeEvaluation_=!1,kd.clearTask(this.audioVolumeIntervalId_),void(this.audioVolumeIntervalId_=null);e=Math.floor(Math.max(e,16)),La.emit(Qa,{interval:e}),this.audioVolumeIntervalId_&&(kd.clearTask(this.audioVolumeIntervalId_),this.audioVolumeIntervalId_=null),this.enableAudioVolumeEvaluation_=!0,this.audioVolumeIntervalId_=kd.run("raf",(()=>{const e=[];if(this.localStream_){const t=Math.floor(100*this.localStream_.getAudioLevel());e.push({userId:this.userId_,audioVolume:t,stream:this.localStream_})}this.connections_.forEach((t=>{const i=t.getSubscribedMainStream();if(i){const s=Math.floor(100*i.getAudioLevel());e.push({userId:t.getUserId(),audioVolume:s,stream:i})}})),this.emitter_.emit(ic.AUDIO_VOLUME,{result:e})}),{fps:1e3/e,backgroundTask:t})}callExperimentalAPI(e,t){return Fh.call(e,{client:this,...t})}setProperty(e,t){const i=`${e}_`;la(this[i])||(this[i]=t)}uploadAllCallStats(){this.callDurationCalculator_.getDurationMap().forEach((({userId:e,type:t},i)=>{const s=this.callDurationCalculator_.getDuration(i,r),{dataFreeze:n}=this.badCaseDetector_.getDataFreezeDuration(i),{renderFreeze:a}=this.badCaseDetector_.getRenderFreezeDuration(i),o={userId:e,type:t,duration:s,dataFreeze:n,renderFreeze:a};sd.uploadEvent({log:"callStats-"+JSON.stringify(o),userId:this.userId_})})),this.badCaseDetector_.stop(),this.callDurationCalculator_.reset()}async enableSmallStream(){if(this.isPublished()||this.isPublishing_)throw new gr({code:pr.INVALID_OPERATION,message:ta({key:Ai})});if(!Xd())throw new gr({code:pr.INVALID_OPERATION,message:ta({key:Di})});this.setIsEnableSmallStream(!0),this.log_.info("SmallStream successfully enabled")}async disableSmallStream(){if(this.isPublished()||this.isPublishing_)throw new gr({code:pr.INVALID_OPERATION,message:ta({key:Ci})});this.setIsEnableSmallStream(!1),this.log_.info("SmallStream successfully disabled")}setSmallStreamProfile(e){e&&e.framerate&&(e.frameRate=e.framerate),e.width*e.height>307200&&(e.width=320,e.height=240,this.log_.info("Small stream resolution is beyond limitation, which is invalid. Reset to 320 * 240")),Object.keys(this.smallStreamConfig_).forEach((t=>{e[t]&&(this.smallStreamConfig_[t]=e[t])}));const{width:t,height:i,bitrate:s,frameRate:n}=this.smallStreamConfig_;if(this.log_.info(`setSmallStreamProfile: bitrate=${s}, frameRate=${n}, height=${i}, width=${t}`),t<0||i<0||s<0||n<0)throw new gr({code:pr.INVALID_PARAMETER,message:ta({key:Ni})})}async setRemoteVideoStreamType(e,t){if(!(e instanceof sl))throw new gr({code:pr.INVALID_PARAMETER,message:ta({key:Pi})});if(!e.getConnection())throw new gr({code:pr.INVALID_OPERATION,message:ta({key:_i})});if(e.getType()!==de)switch(t){case rt:case dt:await this.changeVideoType(e,t)}}async changeVideoType(e,t){const i=e.getUserId(),s={stream:e,options:{video:t===rt,smallVideo:t===dt},isSubscribing:!1,reSubscribeCount:10};this.changeBigSmallRecords_.set(i,s),this.log_.info(`set [${i}] ${e.getType()} stream video prefer type: ${t}`)}async checkSubscribeBigSmallVideo(e,t){if(!(null!=e&&e.isBigStreamSubscribed||null!=e&&e.isSmallStreamSubscribed))return;const i=e.getUserId();if(!this.changeBigSmallRecords_.has(i))return;let s=this.changeBigSmallRecords_.get(i);const{video:n,smallVideo:a}=e.getSubscribeState(),{stream:o,options:r,isSubscribing:d,reSubscribeCount:c}=s;if(r.video&&n||r.smallVideo&&a&&t)return;let l={video:r.video,smallVideo:r.smallVideo};if(t&&e.isBigStreamSubscribed||e.isSmallStreamSubscribed)try{if(r&&o&&!d&&c>=1){s.isSubscribing=!0,s.reSubscribeCount=c-1;const e=o.getConnection();!t&&e.isSmallStreamSubscribed&&(l={video:!0,smallVideo:!1}),l.emitEvent=!1,await(null==e?void 0:e.subscribe(o,l)),this.log_.info(`change [${i}] to ${l.smallVideo?"small":"big"} video successfully. count ${10-s.reSubscribeCount}.`),s.isSubscribing=!1,s.reSubscribeCount=10}}catch(h){this.log_.info(`change [${i}] to ${l.smallVideo?"small":"big"} video failed. count ${10-s.reSubscribeCount}.`),s.isSubscribing=!1,0===c&&this.changeBigSmallRecords_.delete(i)}}setIsEnableSmallStream(e){this.isEnableSmallStream_=e}getIsEnableSmallStream(){return this.isEnableSmallStream_}get smallStreamConfig(){return this.smallStreamConfig_}isPublished(){return!!this.localStream_}getUplinkConnection(){return this.uplinkConnection_}getLocalStream(){return this.localStream_}getMode(){return this.mode_}getBadCaseDetector(){return this.badCaseDetector_}getCallDurationCalculator(){return this.callDurationCalculator_}getIsJoined(){return this.isJoined_}getAllConnections(){const e=[...this.connections_.values()];return this.uplinkConnection_&&e.push(this.uplinkConnection_),e}isRelayMaybeFailed(){if(!this.signalChannel_.isOnline)return!1;const e=this.getAllConnections();if(0===e.length)return!1;for(let t=0;t{if(!e.getIsReconnecting()){const t=e.getPeerConnection();t&&t.connectionState===ge&&(this.log_.warn(`[${e.getUserId()}] pc is closed but not reconnect`),e.startReconnection())}}))}getEnableAutoPlayDialog(){return this.enableAutoPlayDialog_}sendSEIMessage(e,t){this.uplinkConnection_.sendSEI(e,t)}setProxyServer(e){if(this.log_.info(`set proxy server: ${JSON.stringify(e)}`),ha(e)){if(!e.startsWith("wss://"))throw new gr({code:pr.INVALID_PARAMETER,message:ta({key:ei})});this.proxy_=e}else if(oa(e)){const{websocketProxy:t,loggerProxy:i,scheduleProxy:s,unifiedProxy:n}=e;t&&(this.proxy_=t),i&&Z(i),s&&mt(s),n&&(this.unifiedProxy_=n,Z(`https://${n}`),mt(n))}}setTurnServer(e){this.log_.info("set turn server: "+JSON.stringify(e));const t=[];Array.isArray(e)?e.forEach((e=>t.push(fa(e)))):oa(e)&&t.push(fa(e)),this.turnServers_=t}get2k4kFlag(){var e,t;return(null===(e=this.schedule_)||void 0===e||null===(t=e.trtcCapability)||void 0===t?void 0:t["2k4k"])||2}},e($h.prototype,"join",[dh,ch,lh],Object.getOwnPropertyDescriptor($h.prototype,"join"),$h.prototype),e($h.prototype,"leave",[hh],Object.getOwnPropertyDescriptor($h.prototype,"leave"),$h.prototype),e($h.prototype,"getUserList",[uh],Object.getOwnPropertyDescriptor($h.prototype,"getUserList"),$h.prototype),e($h.prototype,"publish",[_h,mh,ph],Object.getOwnPropertyDescriptor($h.prototype,"publish"),$h.prototype),e($h.prototype,"unpublish",[gh,Sh],Object.getOwnPropertyDescriptor($h.prototype,"unpublish"),$h.prototype),e($h.prototype,"subscribe",[fh],Object.getOwnPropertyDescriptor($h.prototype,"subscribe"),$h.prototype),e($h.prototype,"unsubscribe",[vh],Object.getOwnPropertyDescriptor($h.prototype,"unsubscribe"),$h.prototype),e($h.prototype,"switchRole",[Ih,yh,Th],Object.getOwnPropertyDescriptor($h.prototype,"switchRole"),$h.prototype),e($h.prototype,"startPublishCDNStream",[bh,Eh],Object.getOwnPropertyDescriptor($h.prototype,"startPublishCDNStream"),$h.prototype),e($h.prototype,"stopPublishCDNStream",[wh],Object.getOwnPropertyDescriptor($h.prototype,"stopPublishCDNStream"),$h.prototype),e($h.prototype,"startMixTranscode",[kh,Rh],Object.getOwnPropertyDescriptor($h.prototype,"startMixTranscode"),$h.prototype),e($h.prototype,"stopMixTranscode",[Ah],Object.getOwnPropertyDescriptor($h.prototype,"stopMixTranscode"),$h.prototype),e($h.prototype,"enableAudioVolumeEvaluation",[Ch],Object.getOwnPropertyDescriptor($h.prototype,"enableAudioVolumeEvaluation"),$h.prototype),e($h.prototype,"enableSmallStream",[Dh],Object.getOwnPropertyDescriptor($h.prototype,"enableSmallStream"),$h.prototype),e($h.prototype,"disableSmallStream",[Nh],Object.getOwnPropertyDescriptor($h.prototype,"disableSmallStream"),$h.prototype),e($h.prototype,"setSmallStreamProfile",[Ph],Object.getOwnPropertyDescriptor($h.prototype,"setSmallStreamProfile"),$h.prototype),e($h.prototype,"setRemoteVideoStreamType",[Mh],Object.getOwnPropertyDescriptor($h.prototype,"setRemoteVideoStreamType"),$h.prototype),e($h.prototype,"sendSEIMessage",[Lh,Oh,Vh],Object.getOwnPropertyDescriptor($h.prototype,"sendSEIMessage"),$h.prototype),e($h.prototype,"setProxyServer",[Uh],Object.getOwnPropertyDescriptor($h.prototype,"setProxyServer"),$h.prototype),e($h.prototype,"setTurnServer",[xh],Object.getOwnPropertyDescriptor($h.prototype,"setTurnServer"),$h.prototype),$h);var Hh,jh,Jh,Wh,Gh,zh,qh;let Kh=0,Qh=0;var Xh=new(Hh=Xc(pt),jh=Xc(pt),Jh=Xc(pt),Wh=Hc(Bc.TRTC.createClient),Gh=Xc(pt),zh=Hc(Bc.TRTC.createStream),e((qh=class{constructor(){this.name_=pt,this.VERSION="4.15.19",this.Logger={loggerManager:Oo,LogLevel:wt,setLogLevel(e){Oo.setLogLevel(e),e<=1&&ea()},enableUploadLog(){Qc.handleFunctionState({fnName:"TRTC.enableUploadLog"}),Oo.enableUploadLog()},disableUploadLog(){Oo.warn("disableUploadLog"),Qc.handleFunctionState({fnName:"TRTC.disableUploadLog"}),Oo.disableUploadLog()}}}async checkSystemRequirements(){return await Md()}isScreenShareSupported(){return Od()}isSmallStreamSupported(){return Xd()}getDevices(){return mc()}getCameras(){return async function(){return jd()||Hd()?[]:(await _c()).filter((e=>e.kind===E)).map(((e,t)=>{let i=e.label;e.label||(i="camera_"+t);const s={label:i,deviceId:e.deviceId,kind:e.kind};return e.groupId&&(s.groupId=e.groupId),e.getCapabilities&&(s.getCapabilities=()=>e.getCapabilities()),s}))}()}getMicrophones(){return pc()}getSpeakers(){return gc()}createClient(e){!function(){if(Vo&&(Vo=!1,Oo.getLogLevel()!=Xh.Logger.LogLevel.NONE&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${Et}index.html`),console.info("* Changelog: https://cloud.tencent.com/document/product/647/38958"),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),Oo.info("TRTC Web SDK Version: 4.15.19"),Oo.info("UserAgent: "+navigator.userAgent),Oo.info("URL of current page: "+location.href),navigator.userAgentData&&ca(navigator.userAgentData.getHighEntropyValues)))try{navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]).then((e=>{let t=`UAData: ${e.platform}/${e.platformVersion}`;e.architecture&&e.bitness&&(t+=` ${e.architecture}/${e.bitness}`),e.mobile&&(t+=" mobile"),e.model&&(t+=` model: ${e.model}`),e.fullVersionList&&(t+=` ${e.fullVersionList.filter((e=>"Not/A)Brand"!==e.brand)).map((e=>`${e.brand}/${e.version}`)).join(",")}`),Oo.info(t)})).catch((()=>{}))}catch(e){}}();const t={version:this.VERSION},i=new Bh({...t,...e,seq:++Kh});return La.emit(qa,{client:i}),i}createStream(e){return new Nl({...e,seq:++Qh})}}).prototype,"checkSystemRequirements",[Hh],Object.getOwnPropertyDescriptor(qh.prototype,"checkSystemRequirements"),qh.prototype),e(qh.prototype,"isScreenShareSupported",[jh],Object.getOwnPropertyDescriptor(qh.prototype,"isScreenShareSupported"),qh.prototype),e(qh.prototype,"isSmallStreamSupported",[Jh],Object.getOwnPropertyDescriptor(qh.prototype,"isSmallStreamSupported"),qh.prototype),e(qh.prototype,"createClient",[Wh,Gh],Object.getOwnPropertyDescriptor(qh.prototype,"createClient"),qh.prototype),e(qh.prototype,"createStream",[zh],Object.getOwnPropertyDescriptor(qh.prototype,"createStream"),qh.prototype),qh);export{Xh as default};