trtc-sdk-v5 5.0.2 → 5.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/trtc.esm.js CHANGED
@@ -1,4 +1,4 @@
1
- var cp=Object.create;var Ar=Object.defineProperty,dp=Object.defineProperties,zc=Object.getOwnPropertyDescriptor,up=Object.getOwnPropertyDescriptors,lp=Object.getOwnPropertyNames,Mn=Object.getOwnPropertySymbols,qc=Object.getPrototypeOf,so=Object.prototype.hasOwnProperty,Qc=Object.prototype.propertyIsEnumerable,pp=Reflect.get;var Ln=Math.pow,no=(i,t,e)=>t in i?Ar(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e,B=(i,t)=>{for(var e in t||(t={}))so.call(t,e)&&no(i,e,t[e]);if(Mn)for(var e of Mn(t))Qc.call(t,e)&&no(i,e,t[e]);return i},te=(i,t)=>dp(i,up(t));var Zc=(i,t)=>{var e={};for(var r in i)so.call(i,r)&&t.indexOf(r)<0&&(e[r]=i[r]);if(i!=null&&Mn)for(var r of Mn(i))t.indexOf(r)<0&&Qc.call(i,r)&&(e[r]=i[r]);return e};var _e=(i,t)=>()=>(t||i((t={exports:{}}).exports,t),t.exports),oo=(i,t)=>{for(var e in t)Ar(i,e,{get:t[e],enumerable:!0})},hp=(i,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of lp(t))!so.call(i,n)&&n!==e&&Ar(i,n,{get:()=>t[n],enumerable:!(r=zc(t,n))||r.enumerable});return i};var _=(i,t,e)=>(e=i!=null?cp(qc(i)):{},hp(t||!i||!i.__esModule?Ar(e,"default",{value:i,enumerable:!0}):e,i));var F=(i,t,e,r)=>{for(var n=r>1?void 0:r?zc(t,e):t,s=i.length-1,o;s>=0;s--)(o=i[s])&&(n=(r?o(t,e,n):o(n))||n);return r&&n&&Ar(t,e,n),n};var p=(i,t,e)=>(no(i,typeof t!="symbol"?t+"":t,e),e);var Ei=(i,t,e)=>pp(qc(i),e,t);var E=(i,t,e)=>new Promise((r,n)=>{var s=c=>{try{a(e.next(c))}catch(d){n(d)}},o=c=>{try{a(e.throw(c))}catch(d){n(d)}},a=c=>c.done?r(c.value):Promise.resolve(c.value).then(s,o);a((e=e.apply(i,t)).next())});var ft=_e(tt=>{"use strict";var df=_(f());Object.defineProperty(tt,"__esModule",{value:!0});var ao=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(i){return typeof i}:function(i){return i&&typeof Symbol=="function"&&i.constructor===Symbol&&i!==Symbol.prototype?"symbol":typeof i};tt.extractVersion=Cr;tt.wrapPeerConnectionEvent=_p;tt.disableLog=fp;tt.disableWarnings=Ep;tt.log=Tp;tt.deprecated=Sp;tt.detectBrowser=gp;tt.compactObject=rd;tt.walkStats=kn;tt.filterStats=Ip;function mp(i,t,e){return t in i?Object.defineProperty(i,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):i[t]=e,i}var td=!0,id=!0;function Cr(i,t,e){var r=i.match(t);return r&&r.length>=e&&parseInt(r[e],10)}function _p(i,t,e){if(!!i.RTCPeerConnection){var r=i.RTCPeerConnection.prototype,n=r.addEventListener;r.addEventListener=function(o,a){if(o!==t)return n.apply(this,arguments);var c=function(u){var l=e(u);l&&(a.handleEvent?a.handleEvent(l):a(l))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(a,c),n.apply(this,[o,c])};var s=r.removeEventListener;r.removeEventListener=function(o,a){if(o!==t||!this._eventMap||!this._eventMap[t])return s.apply(this,arguments);if(!this._eventMap[t].has(a))return s.apply(this,arguments);var c=this._eventMap[t].get(a);return this._eventMap[t].delete(a),this._eventMap[t].size===0&&delete this._eventMap[t],Object.keys(this._eventMap).length===0&&delete this._eventMap,s.apply(this,[o,c])},Object.defineProperty(r,"on"+t,{get:function(){return this["_on"+t]},set:function(a){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),a&&this.addEventListener(t,this["_on"+t]=a)},enumerable:!0,configurable:!0})}}function fp(i){return typeof i!="boolean"?new Error("Argument type: "+(typeof i=="undefined"?"undefined":ao(i))+". Please use a boolean."):(td=i,i?"adapter.js logging disabled":"adapter.js logging enabled")}function Ep(i){return typeof i!="boolean"?new Error("Argument type: "+(typeof i=="undefined"?"undefined":ao(i))+". Please use a boolean."):(id=!i,"adapter.js deprecation warnings "+(i?"disabled":"enabled"))}function Tp(){if((typeof window=="undefined"?"undefined":ao(window))==="object"){if(td)return;typeof console!="undefined"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function Sp(i,t){!id||console.warn(i+" is deprecated, please use "+t+" instead.")}function gp(i){var t={browser:null,version:null};if(typeof i=="undefined"||!i.navigator)return t.browser="Not a browser.",t;var e=i.navigator;if(e.mozGetUserMedia)t.browser="firefox",t.version=Cr(e.userAgent,/Firefox\/(\d+)\./,1);else if(e.webkitGetUserMedia||i.isSecureContext===!1&&i.webkitRTCPeerConnection&&!i.RTCIceGatherer)t.browser="chrome",t.version=Cr(e.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(e.mediaDevices&&e.userAgent.match(/Edge\/(\d+).(\d+)$/))t.browser="edge",t.version=Cr(e.userAgent,/Edge\/(\d+).(\d+)$/,2);else if(i.RTCPeerConnection&&e.userAgent.match(/AppleWebKit\/(\d+)\./))t.browser="safari",t.version=Cr(e.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=i.RTCRtpTransceiver&&"currentDirection"in i.RTCRtpTransceiver.prototype;else return t.browser="Not a supported browser.",t;return t}function ed(i){return Object.prototype.toString.call(i)==="[object Object]"}function rd(i){return ed(i)?Object.keys(i).reduce(function(t,e){var r=ed(i[e]),n=r?rd(i[e]):i[e],s=r&&!Object.keys(n).length;return n===void 0||s?t:Object.assign(t,mp({},e,n))},{}):i}function kn(i,t,e){!t||e.has(t.id)||(e.set(t.id,t),Object.keys(t).forEach(function(r){r.endsWith("Id")?kn(i,i.get(t[r]),e):r.endsWith("Ids")&&t[r].forEach(function(n){kn(i,i.get(n),e)})}))}function Ip(i,t,e){var r=e?"outbound-rtp":"inbound-rtp",n=new Map;if(t===null)return n;var s=[];return i.forEach(function(o){o.type==="track"&&o.trackIdentifier===t.id&&s.push(o)}),s.forEach(function(o){i.forEach(function(a){a.type===r&&a.trackId===o.id&&kn(i,a,n)})}),n}});var sd=_e(co=>{"use strict";var lf=_(f());Object.defineProperty(co,"__esModule",{value:!0});var yr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(i){return typeof i}:function(i){return i&&typeof Symbol=="function"&&i.constructor===Symbol&&i!==Symbol.prototype?"symbol":typeof i};co.shimGetUserMedia=yp;var Rp=ft(),Ap=Cp(Rp);function Cp(i){if(i&&i.__esModule)return i;var t={};if(i!=null)for(var e in i)Object.prototype.hasOwnProperty.call(i,e)&&(t[e]=i[e]);return t.default=i,t}var nd=Ap.log;function yp(i,t){var e=i&&i.navigator;if(!!e.mediaDevices){var r=function(d){if((typeof d=="undefined"?"undefined":yr(d))!=="object"||d.mandatory||d.optional)return d;var u={};return Object.keys(d).forEach(function(l){if(!(l==="require"||l==="advanced"||l==="mediaSource")){var h=yr(d[l])==="object"?d[l]:{ideal:d[l]};h.exact!==void 0&&typeof h.exact=="number"&&(h.min=h.max=h.exact);var I=function(H,U){return H?H+U.charAt(0).toUpperCase()+U.slice(1):U==="deviceId"?"sourceId":U};if(h.ideal!==void 0){u.optional=u.optional||[];var T={};typeof h.ideal=="number"?(T[I("min",l)]=h.ideal,u.optional.push(T),T={},T[I("max",l)]=h.ideal,u.optional.push(T)):(T[I("",l)]=h.ideal,u.optional.push(T))}h.exact!==void 0&&typeof h.exact!="number"?(u.mandatory=u.mandatory||{},u.mandatory[I("",l)]=h.exact):["min","max"].forEach(function(N){h[N]!==void 0&&(u.mandatory=u.mandatory||{},u.mandatory[I(N,l)]=h[N])})}}),d.advanced&&(u.optional=(u.optional||[]).concat(d.advanced)),u},n=function(d,u){if(t.version>=61)return u(d);if(d=JSON.parse(JSON.stringify(d)),d&&yr(d.audio)==="object"){var l=function(H,U,G){U in H&&!(G in H)&&(H[G]=H[U],delete H[U])};d=JSON.parse(JSON.stringify(d)),l(d.audio,"autoGainControl","googAutoGainControl"),l(d.audio,"noiseSuppression","googNoiseSuppression"),d.audio=r(d.audio)}if(d&&yr(d.video)==="object"){var h=d.video.facingMode;h=h&&((typeof h=="undefined"?"undefined":yr(h))==="object"?h:{ideal:h});var I=t.version<66;if(h&&(h.exact==="user"||h.exact==="environment"||h.ideal==="user"||h.ideal==="environment")&&!(e.mediaDevices.getSupportedConstraints&&e.mediaDevices.getSupportedConstraints().facingMode&&!I)){delete d.video.facingMode;var T=void 0;if(h.exact==="environment"||h.ideal==="environment"?T=["back","rear"]:(h.exact==="user"||h.ideal==="user")&&(T=["front"]),T)return e.mediaDevices.enumerateDevices().then(function(N){N=N.filter(function(U){return U.kind==="videoinput"});var H=N.find(function(U){return T.some(function(G){return U.label.toLowerCase().includes(G)})});return!H&&N.length&&T.includes("back")&&(H=N[N.length-1]),H&&(d.video.deviceId=h.exact?{exact:H.deviceId}:{ideal:H.deviceId}),d.video=r(d.video),nd("chrome: "+JSON.stringify(d)),u(d)})}d.video=r(d.video)}return nd("chrome: "+JSON.stringify(d)),u(d)},s=function(d){return t.version>=64?d:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[d.name]||d.name,message:d.message,constraint:d.constraint||d.constraintName,toString:function(){return this.name+(this.message&&": ")+this.message}}},o=function(d,u,l){n(d,function(h){e.webkitGetUserMedia(h,u,function(I){l&&l(s(I))})})};if(e.getUserMedia=o.bind(e),e.mediaDevices.getUserMedia){var a=e.mediaDevices.getUserMedia.bind(e.mediaDevices);e.mediaDevices.getUserMedia=function(c){return n(c,function(d){return a(d).then(function(u){if(d.audio&&!u.getAudioTracks().length||d.video&&!u.getVideoTracks().length)throw u.getTracks().forEach(function(l){l.stop()}),new DOMException("","NotFoundError");return u},function(u){return Promise.reject(s(u))})})}}}}});var od=_e(uo=>{"use strict";var hf=_(f());Object.defineProperty(uo,"__esModule",{value:!0});uo.shimGetDisplayMedia=vp;function vp(i,t){if(!(i.navigator.mediaDevices&&"getDisplayMedia"in i.navigator.mediaDevices)&&!!i.navigator.mediaDevices){if(typeof t!="function"){console.error("shimGetDisplayMedia: getSourceId argument is not a function");return}i.navigator.mediaDevices.getDisplayMedia=function(r){return t(r).then(function(n){var s=r.video&&r.video.width,o=r.video&&r.video.height,a=r.video&&r.video.frameRate;return r.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:n,maxFrameRate:a||3}},s&&(r.video.mandatory.maxWidth=s),o&&(r.video.mandatory.maxHeight=o),i.navigator.mediaDevices.getUserMedia(r)})}}}});var dd=_e(Ue=>{"use strict";var _f=_(f());Object.defineProperty(Ue,"__esModule",{value:!0});Ue.shimGetDisplayMedia=Ue.shimGetUserMedia=void 0;var xn=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(i){return typeof i}:function(i){return i&&typeof Symbol=="function"&&i.constructor===Symbol&&i!==Symbol.prototype?"symbol":typeof i},Np=sd();Object.defineProperty(Ue,"shimGetUserMedia",{enumerable:!0,get:function(){return Np.shimGetUserMedia}});var bp=od();Object.defineProperty(Ue,"shimGetDisplayMedia",{enumerable:!0,get:function(){return bp.shimGetDisplayMedia}});Ue.shimMediaStream=Pp;Ue.shimOnTrack=Mp;Ue.shimGetSendersWithDtmf=Lp;Ue.shimGetStats=kp;Ue.shimSenderReceiverGetStats=xp;Ue.shimAddTrackRemoveTrackWithNative=cd;Ue.shimAddTrackRemoveTrack=Up;Ue.shimPeerConnection=Vp;Ue.fixNegotiationNeeded=wp;var Dp=ft(),vr=Op(Dp);function Op(i){if(i&&i.__esModule)return i;var t={};if(i!=null)for(var e in i)Object.prototype.hasOwnProperty.call(i,e)&&(t[e]=i[e]);return t.default=i,t}function ad(i,t,e){return t in i?Object.defineProperty(i,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):i[t]=e,i}function Pp(i){i.MediaStream=i.MediaStream||i.webkitMediaStream}function Mp(i){if((typeof i=="undefined"?"undefined":xn(i))==="object"&&i.RTCPeerConnection&&!("ontrack"in i.RTCPeerConnection.prototype)){Object.defineProperty(i.RTCPeerConnection.prototype,"ontrack",{get:function(){return this._ontrack},set:function(r){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=r)},enumerable:!0,configurable:!0});var t=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){var r=this;return this._ontrackpoly||(this._ontrackpoly=function(n){n.stream.addEventListener("addtrack",function(s){var o=void 0;i.RTCPeerConnection.prototype.getReceivers?o=r.getReceivers().find(function(c){return c.track&&c.track.id===s.track.id}):o={track:s.track};var a=new Event("track");a.track=s.track,a.receiver=o,a.transceiver={receiver:o},a.streams=[n.stream],r.dispatchEvent(a)}),n.stream.getTracks().forEach(function(s){var o=void 0;i.RTCPeerConnection.prototype.getReceivers?o=r.getReceivers().find(function(c){return c.track&&c.track.id===s.id}):o={track:s};var a=new Event("track");a.track=s,a.receiver=o,a.transceiver={receiver:o},a.streams=[n.stream],r.dispatchEvent(a)})},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else vr.wrapPeerConnectionEvent(i,"track",function(e){return e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e})}function Lp(i){if((typeof i=="undefined"?"undefined":xn(i))==="object"&&i.RTCPeerConnection&&!("getSenders"in i.RTCPeerConnection.prototype)&&"createDTMFSender"in i.RTCPeerConnection.prototype){var t=function(c,d){return{track:d,get dtmf(){return this._dtmf===void 0&&(d.kind==="audio"?this._dtmf=c.createDTMFSender(d):this._dtmf=null),this._dtmf},_pc:c}};if(!i.RTCPeerConnection.prototype.getSenders){i.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};var e=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addTrack=function(c,d){var u=e.apply(this,arguments);return u||(u=t(this,c),this._senders.push(u)),u};var r=i.RTCPeerConnection.prototype.removeTrack;i.RTCPeerConnection.prototype.removeTrack=function(c){r.apply(this,arguments);var d=this._senders.indexOf(c);d!==-1&&this._senders.splice(d,1)}}var n=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(c){var d=this;this._senders=this._senders||[],n.apply(this,[c]),c.getTracks().forEach(function(u){d._senders.push(t(d,u))})};var s=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(c){var d=this;this._senders=this._senders||[],s.apply(this,[c]),c.getTracks().forEach(function(u){var l=d._senders.find(function(h){return h.track===u});l&&d._senders.splice(d._senders.indexOf(l),1)})}}else if((typeof i=="undefined"?"undefined":xn(i))==="object"&&i.RTCPeerConnection&&"getSenders"in i.RTCPeerConnection.prototype&&"createDTMFSender"in i.RTCPeerConnection.prototype&&i.RTCRtpSender&&!("dtmf"in i.RTCRtpSender.prototype)){var o=i.RTCPeerConnection.prototype.getSenders;i.RTCPeerConnection.prototype.getSenders=function(){var c=this,d=o.apply(this,[]);return d.forEach(function(u){return u._pc=c}),d},Object.defineProperty(i.RTCRtpSender.prototype,"dtmf",{get:function(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function kp(i){if(!!i.RTCPeerConnection){var t=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){var r=this,n=Array.prototype.slice.call(arguments),s=n[0],o=n[1],a=n[2];if(arguments.length>0&&typeof s=="function")return t.apply(this,arguments);if(t.length===0&&(arguments.length===0||typeof s!="function"))return t.apply(this,[]);var c=function(h){var I={},T=h.result();return T.forEach(function(N){var H={id:N.id,timestamp:N.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[N.type]||N.type};N.names().forEach(function(U){H[U]=N.stat(U)}),I[H.id]=H}),I},d=function(h){return new Map(Object.keys(h).map(function(I){return[I,h[I]]}))};if(arguments.length>=2){var u=function(h){o(d(c(h)))};return t.apply(this,[u,s])}return new Promise(function(l,h){t.apply(r,[function(I){l(d(c(I)))},h])}).then(o,a)}}}function xp(i){if(!!((typeof i=="undefined"?"undefined":xn(i))==="object"&&i.RTCPeerConnection&&i.RTCRtpSender&&i.RTCRtpReceiver)){if(!("getStats"in i.RTCRtpSender.prototype)){var t=i.RTCPeerConnection.prototype.getSenders;t&&(i.RTCPeerConnection.prototype.getSenders=function(){var o=this,a=t.apply(this,[]);return a.forEach(function(c){return c._pc=o}),a});var e=i.RTCPeerConnection.prototype.addTrack;e&&(i.RTCPeerConnection.prototype.addTrack=function(){var o=e.apply(this,arguments);return o._pc=this,o}),i.RTCRtpSender.prototype.getStats=function(){var o=this;return this._pc.getStats().then(function(a){return vr.filterStats(a,o.track,!0)})}}if(!("getStats"in i.RTCRtpReceiver.prototype)){var r=i.RTCPeerConnection.prototype.getReceivers;r&&(i.RTCPeerConnection.prototype.getReceivers=function(){var o=this,a=r.apply(this,[]);return a.forEach(function(c){return c._pc=o}),a}),vr.wrapPeerConnectionEvent(i,"track",function(s){return s.receiver._pc=s.srcElement,s}),i.RTCRtpReceiver.prototype.getStats=function(){var o=this;return this._pc.getStats().then(function(a){return vr.filterStats(a,o.track,!1)})}}if("getStats"in i.RTCRtpSender.prototype&&"getStats"in i.RTCRtpReceiver.prototype){var n=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof i.MediaStreamTrack){var o=arguments[0],a=void 0,c=void 0,d=void 0;return this.getSenders().forEach(function(u){u.track===o&&(a?d=!0:a=u)}),this.getReceivers().forEach(function(u){return u.track===o&&(c?d=!0:c=u),u.track===o}),d||a&&c?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):a?a.getStats():c?c.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return n.apply(this,arguments)}}}}function cd(i){i.RTCPeerConnection.prototype.getLocalStreams=function(){var o=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(function(a){return o._shimmedLocalStreams[a][0]})};var t=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addTrack=function(o,a){if(!a)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};var c=t.apply(this,arguments);return this._shimmedLocalStreams[a.id]?this._shimmedLocalStreams[a.id].indexOf(c)===-1&&this._shimmedLocalStreams[a.id].push(c):this._shimmedLocalStreams[a.id]=[a,c],c};var e=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(o){var a=this;this._shimmedLocalStreams=this._shimmedLocalStreams||{},o.getTracks().forEach(function(u){var l=a.getSenders().find(function(h){return h.track===u});if(l)throw new DOMException("Track already exists.","InvalidAccessError")});var c=this.getSenders();e.apply(this,arguments);var d=this.getSenders().filter(function(u){return c.indexOf(u)===-1});this._shimmedLocalStreams[o.id]=[o].concat(d)};var r=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[o.id],r.apply(this,arguments)};var n=i.RTCPeerConnection.prototype.removeTrack;i.RTCPeerConnection.prototype.removeTrack=function(o){var a=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},o&&Object.keys(this._shimmedLocalStreams).forEach(function(c){var d=a._shimmedLocalStreams[c].indexOf(o);d!==-1&&a._shimmedLocalStreams[c].splice(d,1),a._shimmedLocalStreams[c].length===1&&delete a._shimmedLocalStreams[c]}),n.apply(this,arguments)}}function Up(i,t){if(!i.RTCPeerConnection)return;if(i.RTCPeerConnection.prototype.addTrack&&t.version>=65)return cd(i);var e=i.RTCPeerConnection.prototype.getLocalStreams;i.RTCPeerConnection.prototype.getLocalStreams=function(){var u=this,l=e.apply(this);return this._reverseStreams=this._reverseStreams||{},l.map(function(h){return u._reverseStreams[h.id]})};var r=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(u){var l=this;if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},u.getTracks().forEach(function(I){var T=l.getSenders().find(function(N){return N.track===I});if(T)throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[u.id]){var h=new i.MediaStream(u.getTracks());this._streams[u.id]=h,this._reverseStreams[h.id]=u,u=h}r.apply(this,[u])};var n=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(u){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},n.apply(this,[this._streams[u.id]||u]),delete this._reverseStreams[this._streams[u.id]?this._streams[u.id].id:u.id],delete this._streams[u.id]},i.RTCPeerConnection.prototype.addTrack=function(u,l){var h=this;if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");var I=[].slice.call(arguments,1);if(I.length!==1||!I[0].getTracks().find(function(U){return U===u}))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");var T=this.getSenders().find(function(U){return U.track===u});if(T)throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};var N=this._streams[l.id];if(N)N.addTrack(u),Promise.resolve().then(function(){h.dispatchEvent(new Event("negotiationneeded"))});else{var H=new i.MediaStream([u]);this._streams[l.id]=H,this._reverseStreams[H.id]=l,this.addStream(H)}return this.getSenders().find(function(U){return U.track===u})};function s(d,u){var l=u.sdp;return Object.keys(d._reverseStreams||[]).forEach(function(h){var I=d._reverseStreams[h],T=d._streams[I.id];l=l.replace(new RegExp(T.id,"g"),I.id)}),new RTCSessionDescription({type:u.type,sdp:l})}function o(d,u){var l=u.sdp;return Object.keys(d._reverseStreams||[]).forEach(function(h){var I=d._reverseStreams[h],T=d._streams[I.id];l=l.replace(new RegExp(I.id,"g"),T.id)}),new RTCSessionDescription({type:u.type,sdp:l})}["createOffer","createAnswer"].forEach(function(d){var u=i.RTCPeerConnection.prototype[d],l=ad({},d,function(){var h=this,I=arguments,T=arguments.length&&typeof arguments[0]=="function";return T?u.apply(this,[function(N){var H=s(h,N);I[0].apply(null,[H])},function(N){I[1]&&I[1].apply(null,N)},arguments[2]]):u.apply(this,arguments).then(function(N){return s(h,N)})});i.RTCPeerConnection.prototype[d]=l[d]});var a=i.RTCPeerConnection.prototype.setLocalDescription;i.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?a.apply(this,arguments):(arguments[0]=o(this,arguments[0]),a.apply(this,arguments))};var c=Object.getOwnPropertyDescriptor(i.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(i.RTCPeerConnection.prototype,"localDescription",{get:function(){var u=c.get.apply(this);return u.type===""?u:s(this,u)}}),i.RTCPeerConnection.prototype.removeTrack=function(u){var l=this;if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!u._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");var h=u._pc===this;if(!h)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};var I=void 0;Object.keys(this._streams).forEach(function(T){var N=l._streams[T].getTracks().find(function(H){return u.track===H});N&&(I=l._streams[T])}),I&&(I.getTracks().length===1?this.removeStream(this._reverseStreams[I.id]):I.removeTrack(u.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Vp(i,t){!i.RTCPeerConnection&&i.webkitRTCPeerConnection&&(i.RTCPeerConnection=i.webkitRTCPeerConnection),!!i.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(e){var r=i.RTCPeerConnection.prototype[e],n=ad({},e,function(){return arguments[0]=new(e==="addIceCandidate"?i.RTCIceCandidate:i.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)});i.RTCPeerConnection.prototype[e]=n[e]})}function wp(i,t){vr.wrapPeerConnectionEvent(i,"negotiationneeded",function(e){var r=e.target;if(!((t.version<72||r.getConfiguration&&r.getConfiguration().sdpSemantics==="plan-b")&&r.signalingState!=="stable"))return e})}});var ud=_e(lo=>{"use strict";var Ef=_(f());Object.defineProperty(lo,"__esModule",{value:!0});lo.shimGetUserMedia=Bp;function Bp(i){var t=i&&i.navigator,e=function(s){return{name:{PermissionDeniedError:"NotAllowedError"}[s.name]||s.name,message:s.message,constraint:s.constraint,toString:function(){return this.name}}},r=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(n){return r(n).catch(function(s){return Promise.reject(e(s))})}}});var ld=_e(po=>{"use strict";var Sf=_(f());Object.defineProperty(po,"__esModule",{value:!0});po.shimGetDisplayMedia=$p;function $p(i){"getDisplayMedia"in i.navigator&&(!i.navigator.mediaDevices||i.navigator.mediaDevices&&"getDisplayMedia"in i.navigator.mediaDevices||(i.navigator.mediaDevices.getDisplayMedia=i.navigator.getDisplayMedia.bind(i.navigator)))}});var pd=_e(ho=>{"use strict";var If=_(f());Object.defineProperty(ho,"__esModule",{value:!0});ho.filterIceServers=Wp;var Hp=ft(),Fp=Gp(Hp);function Gp(i){if(i&&i.__esModule)return i;var t={};if(i!=null)for(var e in i)Object.prototype.hasOwnProperty.call(i,e)&&(t[e]=i[e]);return t.default=i,t}function Wp(i,t){var e=!1;return i=JSON.parse(JSON.stringify(i)),i.filter(function(r){if(r&&(r.urls||r.url)){var n=r.urls||r.url;r.url&&!r.urls&&Fp.deprecated("RTCIceServer.url","RTCIceServer.urls");var s=typeof n=="string";return s&&(n=[n]),n=n.filter(function(o){if(o.indexOf("stun:")===0)return!1;var a=o.startsWith("turn")&&!o.startsWith("turn:[")&&o.includes("transport=udp");return a&&!e?(e=!0,!0):a&&!e}),delete r.url,r.urls=s?n[0]:n,!!n.length}})}});var _o=_e((Rf,mo)=>{"use strict";var Af=_(f()),P={};P.generateIdentifier=function(){return Math.random().toString(36).substr(2,10)};P.localCName=P.generateIdentifier();P.splitLines=function(i){return i.trim().split(`
1
+ var Tp=Object.create;var jr=Object.defineProperty,Sp=Object.defineProperties,Id=Object.getOwnPropertyDescriptor,gp=Object.getOwnPropertyDescriptors,Ip=Object.getOwnPropertyNames,ns=Object.getOwnPropertySymbols,Rd=Object.getPrototypeOf,xo=Object.prototype.hasOwnProperty,Ad=Object.prototype.propertyIsEnumerable,Rp=Reflect.get;var ss=Math.pow,ko=(i,t,e)=>t in i?jr(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e,w=(i,t)=>{for(var e in t||(t={}))xo.call(t,e)&&ko(i,e,t[e]);if(ns)for(var e of ns(t))Ad.call(t,e)&&ko(i,e,t[e]);return i},ee=(i,t)=>Sp(i,gp(t));var Cd=(i,t)=>{var e={};for(var r in i)xo.call(i,r)&&t.indexOf(r)<0&&(e[r]=i[r]);if(i!=null&&ns)for(var r of ns(i))t.indexOf(r)<0&&Ad.call(i,r)&&(e[r]=i[r]);return e};var fe=(i,t)=>()=>(t||i((t={exports:{}}).exports,t),t.exports),Jr=(i,t)=>{for(var e in t)jr(i,e,{get:t[e],enumerable:!0})},Ap=(i,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Ip(t))!xo.call(i,n)&&n!==e&&jr(i,n,{get:()=>t[n],enumerable:!(r=Id(t,n))||r.enumerable});return i};var _=(i,t,e)=>(e=i!=null?Tp(Rd(i)):{},Ap(t||!i||!i.__esModule?jr(e,"default",{value:i,enumerable:!0}):e,i));var H=(i,t,e,r)=>{for(var n=r>1?void 0:r?Id(t,e):t,s=i.length-1,o;s>=0;s--)(o=i[s])&&(n=(r?o(t,e,n):o(n))||n);return r&&n&&jr(t,e,n),n};var p=(i,t,e)=>(ko(i,typeof t!="symbol"?t+"":t,e),e);var Ci=(i,t,e)=>Rp(Rd(i),e,t);var E=(i,t,e)=>new Promise((r,n)=>{var s=c=>{try{a(e.next(c))}catch(d){n(d)}},o=c=>{try{a(e.throw(c))}catch(d){n(d)}},a=c=>c.done?r(c.value):Promise.resolve(c.value).then(s,o);a((e=e.apply(i,t)).next())});var It=fe(tt=>{"use strict";var Wf=_(f());Object.defineProperty(tt,"__esModule",{value:!0});var Uo=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(i){return typeof i}:function(i){return i&&typeof Symbol=="function"&&i.constructor===Symbol&&i!==Symbol.prototype?"symbol":typeof i};tt.extractVersion=Yr;tt.wrapPeerConnectionEvent=yp;tt.disableLog=vp;tt.disableWarnings=Np;tt.log=bp;tt.deprecated=Dp;tt.detectBrowser=Op;tt.compactObject=bd;tt.walkStats=os;tt.filterStats=Pp;function Cp(i,t,e){return t in i?Object.defineProperty(i,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):i[t]=e,i}var vd=!0,Nd=!0;function Yr(i,t,e){var r=i.match(t);return r&&r.length>=e&&parseInt(r[e],10)}function yp(i,t,e){if(!!i.RTCPeerConnection){var r=i.RTCPeerConnection.prototype,n=r.addEventListener;r.addEventListener=function(o,a){if(o!==t)return n.apply(this,arguments);var c=function(u){var l=e(u);l&&(a.handleEvent?a.handleEvent(l):a(l))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(a,c),n.apply(this,[o,c])};var s=r.removeEventListener;r.removeEventListener=function(o,a){if(o!==t||!this._eventMap||!this._eventMap[t])return s.apply(this,arguments);if(!this._eventMap[t].has(a))return s.apply(this,arguments);var c=this._eventMap[t].get(a);return this._eventMap[t].delete(a),this._eventMap[t].size===0&&delete this._eventMap[t],Object.keys(this._eventMap).length===0&&delete this._eventMap,s.apply(this,[o,c])},Object.defineProperty(r,"on"+t,{get:function(){return this["_on"+t]},set:function(a){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),a&&this.addEventListener(t,this["_on"+t]=a)},enumerable:!0,configurable:!0})}}function vp(i){return typeof i!="boolean"?new Error("Argument type: "+(typeof i=="undefined"?"undefined":Uo(i))+". Please use a boolean."):(vd=i,i?"adapter.js logging disabled":"adapter.js logging enabled")}function Np(i){return typeof i!="boolean"?new Error("Argument type: "+(typeof i=="undefined"?"undefined":Uo(i))+". Please use a boolean."):(Nd=!i,"adapter.js deprecation warnings "+(i?"disabled":"enabled"))}function bp(){if((typeof window=="undefined"?"undefined":Uo(window))==="object"){if(vd)return;typeof console!="undefined"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function Dp(i,t){!Nd||console.warn(i+" is deprecated, please use "+t+" instead.")}function Op(i){var t={browser:null,version:null};if(typeof i=="undefined"||!i.navigator)return t.browser="Not a browser.",t;var e=i.navigator;if(e.mozGetUserMedia)t.browser="firefox",t.version=Yr(e.userAgent,/Firefox\/(\d+)\./,1);else if(e.webkitGetUserMedia||i.isSecureContext===!1&&i.webkitRTCPeerConnection&&!i.RTCIceGatherer)t.browser="chrome",t.version=Yr(e.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(e.mediaDevices&&e.userAgent.match(/Edge\/(\d+).(\d+)$/))t.browser="edge",t.version=Yr(e.userAgent,/Edge\/(\d+).(\d+)$/,2);else if(i.RTCPeerConnection&&e.userAgent.match(/AppleWebKit\/(\d+)\./))t.browser="safari",t.version=Yr(e.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=i.RTCRtpTransceiver&&"currentDirection"in i.RTCRtpTransceiver.prototype;else return t.browser="Not a supported browser.",t;return t}function yd(i){return Object.prototype.toString.call(i)==="[object Object]"}function bd(i){return yd(i)?Object.keys(i).reduce(function(t,e){var r=yd(i[e]),n=r?bd(i[e]):i[e],s=r&&!Object.keys(n).length;return n===void 0||s?t:Object.assign(t,Cp({},e,n))},{}):i}function os(i,t,e){!t||e.has(t.id)||(e.set(t.id,t),Object.keys(t).forEach(function(r){r.endsWith("Id")?os(i,i.get(t[r]),e):r.endsWith("Ids")&&t[r].forEach(function(n){os(i,i.get(n),e)})}))}function Pp(i,t,e){var r=e?"outbound-rtp":"inbound-rtp",n=new Map;if(t===null)return n;var s=[];return i.forEach(function(o){o.type==="track"&&o.trackIdentifier===t.id&&s.push(o)}),s.forEach(function(o){i.forEach(function(a){a.type===r&&a.trackId===o.id&&os(i,a,n)})}),n}});var Od=fe(Vo=>{"use strict";var jf=_(f());Object.defineProperty(Vo,"__esModule",{value:!0});var Xr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(i){return typeof i}:function(i){return i&&typeof Symbol=="function"&&i.constructor===Symbol&&i!==Symbol.prototype?"symbol":typeof i};Vo.shimGetUserMedia=xp;var Mp=It(),Lp=kp(Mp);function kp(i){if(i&&i.__esModule)return i;var t={};if(i!=null)for(var e in i)Object.prototype.hasOwnProperty.call(i,e)&&(t[e]=i[e]);return t.default=i,t}var Dd=Lp.log;function xp(i,t){var e=i&&i.navigator;if(!!e.mediaDevices){var r=function(d){if((typeof d=="undefined"?"undefined":Xr(d))!=="object"||d.mandatory||d.optional)return d;var u={};return Object.keys(d).forEach(function(l){if(!(l==="require"||l==="advanced"||l==="mediaSource")){var h=Xr(d[l])==="object"?d[l]:{ideal:d[l]};h.exact!==void 0&&typeof h.exact=="number"&&(h.min=h.max=h.exact);var I=function($,x){return $?$+x.charAt(0).toUpperCase()+x.slice(1):x==="deviceId"?"sourceId":x};if(h.ideal!==void 0){u.optional=u.optional||[];var T={};typeof h.ideal=="number"?(T[I("min",l)]=h.ideal,u.optional.push(T),T={},T[I("max",l)]=h.ideal,u.optional.push(T)):(T[I("",l)]=h.ideal,u.optional.push(T))}h.exact!==void 0&&typeof h.exact!="number"?(u.mandatory=u.mandatory||{},u.mandatory[I("",l)]=h.exact):["min","max"].forEach(function(N){h[N]!==void 0&&(u.mandatory=u.mandatory||{},u.mandatory[I(N,l)]=h[N])})}}),d.advanced&&(u.optional=(u.optional||[]).concat(d.advanced)),u},n=function(d,u){if(t.version>=61)return u(d);if(d=JSON.parse(JSON.stringify(d)),d&&Xr(d.audio)==="object"){var l=function($,x,F){x in $&&!(F in $)&&($[F]=$[x],delete $[x])};d=JSON.parse(JSON.stringify(d)),l(d.audio,"autoGainControl","googAutoGainControl"),l(d.audio,"noiseSuppression","googNoiseSuppression"),d.audio=r(d.audio)}if(d&&Xr(d.video)==="object"){var h=d.video.facingMode;h=h&&((typeof h=="undefined"?"undefined":Xr(h))==="object"?h:{ideal:h});var I=t.version<66;if(h&&(h.exact==="user"||h.exact==="environment"||h.ideal==="user"||h.ideal==="environment")&&!(e.mediaDevices.getSupportedConstraints&&e.mediaDevices.getSupportedConstraints().facingMode&&!I)){delete d.video.facingMode;var T=void 0;if(h.exact==="environment"||h.ideal==="environment"?T=["back","rear"]:(h.exact==="user"||h.ideal==="user")&&(T=["front"]),T)return e.mediaDevices.enumerateDevices().then(function(N){N=N.filter(function(x){return x.kind==="videoinput"});var $=N.find(function(x){return T.some(function(F){return x.label.toLowerCase().includes(F)})});return!$&&N.length&&T.includes("back")&&($=N[N.length-1]),$&&(d.video.deviceId=h.exact?{exact:$.deviceId}:{ideal:$.deviceId}),d.video=r(d.video),Dd("chrome: "+JSON.stringify(d)),u(d)})}d.video=r(d.video)}return Dd("chrome: "+JSON.stringify(d)),u(d)},s=function(d){return t.version>=64?d:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[d.name]||d.name,message:d.message,constraint:d.constraint||d.constraintName,toString:function(){return this.name+(this.message&&": ")+this.message}}},o=function(d,u,l){n(d,function(h){e.webkitGetUserMedia(h,u,function(I){l&&l(s(I))})})};if(e.getUserMedia=o.bind(e),e.mediaDevices.getUserMedia){var a=e.mediaDevices.getUserMedia.bind(e.mediaDevices);e.mediaDevices.getUserMedia=function(c){return n(c,function(d){return a(d).then(function(u){if(d.audio&&!u.getAudioTracks().length||d.video&&!u.getVideoTracks().length)throw u.getTracks().forEach(function(l){l.stop()}),new DOMException("","NotFoundError");return u},function(u){return Promise.reject(s(u))})})}}}}});var Pd=fe(wo=>{"use strict";var Yf=_(f());Object.defineProperty(wo,"__esModule",{value:!0});wo.shimGetDisplayMedia=Up;function Up(i,t){if(!(i.navigator.mediaDevices&&"getDisplayMedia"in i.navigator.mediaDevices)&&!!i.navigator.mediaDevices){if(typeof t!="function"){console.error("shimGetDisplayMedia: getSourceId argument is not a function");return}i.navigator.mediaDevices.getDisplayMedia=function(r){return t(r).then(function(n){var s=r.video&&r.video.width,o=r.video&&r.video.height,a=r.video&&r.video.frameRate;return r.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:n,maxFrameRate:a||3}},s&&(r.video.mandatory.maxWidth=s),o&&(r.video.mandatory.maxHeight=o),i.navigator.mediaDevices.getUserMedia(r)})}}}});var kd=fe(we=>{"use strict";var zf=_(f());Object.defineProperty(we,"__esModule",{value:!0});we.shimGetDisplayMedia=we.shimGetUserMedia=void 0;var as=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(i){return typeof i}:function(i){return i&&typeof Symbol=="function"&&i.constructor===Symbol&&i!==Symbol.prototype?"symbol":typeof i},Vp=Od();Object.defineProperty(we,"shimGetUserMedia",{enumerable:!0,get:function(){return Vp.shimGetUserMedia}});var wp=Pd();Object.defineProperty(we,"shimGetDisplayMedia",{enumerable:!0,get:function(){return wp.shimGetDisplayMedia}});we.shimMediaStream=Hp;we.shimOnTrack=Fp;we.shimGetSendersWithDtmf=Gp;we.shimGetStats=Wp;we.shimSenderReceiverGetStats=Kp;we.shimAddTrackRemoveTrackWithNative=Ld;we.shimAddTrackRemoveTrack=jp;we.shimPeerConnection=Jp;we.fixNegotiationNeeded=Yp;var Bp=It(),zr=$p(Bp);function $p(i){if(i&&i.__esModule)return i;var t={};if(i!=null)for(var e in i)Object.prototype.hasOwnProperty.call(i,e)&&(t[e]=i[e]);return t.default=i,t}function Md(i,t,e){return t in i?Object.defineProperty(i,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):i[t]=e,i}function Hp(i){i.MediaStream=i.MediaStream||i.webkitMediaStream}function Fp(i){if((typeof i=="undefined"?"undefined":as(i))==="object"&&i.RTCPeerConnection&&!("ontrack"in i.RTCPeerConnection.prototype)){Object.defineProperty(i.RTCPeerConnection.prototype,"ontrack",{get:function(){return this._ontrack},set:function(r){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=r)},enumerable:!0,configurable:!0});var t=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){var r=this;return this._ontrackpoly||(this._ontrackpoly=function(n){n.stream.addEventListener("addtrack",function(s){var o=void 0;i.RTCPeerConnection.prototype.getReceivers?o=r.getReceivers().find(function(c){return c.track&&c.track.id===s.track.id}):o={track:s.track};var a=new Event("track");a.track=s.track,a.receiver=o,a.transceiver={receiver:o},a.streams=[n.stream],r.dispatchEvent(a)}),n.stream.getTracks().forEach(function(s){var o=void 0;i.RTCPeerConnection.prototype.getReceivers?o=r.getReceivers().find(function(c){return c.track&&c.track.id===s.id}):o={track:s};var a=new Event("track");a.track=s,a.receiver=o,a.transceiver={receiver:o},a.streams=[n.stream],r.dispatchEvent(a)})},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else zr.wrapPeerConnectionEvent(i,"track",function(e){return e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e})}function Gp(i){if((typeof i=="undefined"?"undefined":as(i))==="object"&&i.RTCPeerConnection&&!("getSenders"in i.RTCPeerConnection.prototype)&&"createDTMFSender"in i.RTCPeerConnection.prototype){var t=function(c,d){return{track:d,get dtmf(){return this._dtmf===void 0&&(d.kind==="audio"?this._dtmf=c.createDTMFSender(d):this._dtmf=null),this._dtmf},_pc:c}};if(!i.RTCPeerConnection.prototype.getSenders){i.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};var e=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addTrack=function(c,d){var u=e.apply(this,arguments);return u||(u=t(this,c),this._senders.push(u)),u};var r=i.RTCPeerConnection.prototype.removeTrack;i.RTCPeerConnection.prototype.removeTrack=function(c){r.apply(this,arguments);var d=this._senders.indexOf(c);d!==-1&&this._senders.splice(d,1)}}var n=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(c){var d=this;this._senders=this._senders||[],n.apply(this,[c]),c.getTracks().forEach(function(u){d._senders.push(t(d,u))})};var s=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(c){var d=this;this._senders=this._senders||[],s.apply(this,[c]),c.getTracks().forEach(function(u){var l=d._senders.find(function(h){return h.track===u});l&&d._senders.splice(d._senders.indexOf(l),1)})}}else if((typeof i=="undefined"?"undefined":as(i))==="object"&&i.RTCPeerConnection&&"getSenders"in i.RTCPeerConnection.prototype&&"createDTMFSender"in i.RTCPeerConnection.prototype&&i.RTCRtpSender&&!("dtmf"in i.RTCRtpSender.prototype)){var o=i.RTCPeerConnection.prototype.getSenders;i.RTCPeerConnection.prototype.getSenders=function(){var c=this,d=o.apply(this,[]);return d.forEach(function(u){return u._pc=c}),d},Object.defineProperty(i.RTCRtpSender.prototype,"dtmf",{get:function(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function Wp(i){if(!!i.RTCPeerConnection){var t=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){var r=this,n=Array.prototype.slice.call(arguments),s=n[0],o=n[1],a=n[2];if(arguments.length>0&&typeof s=="function")return t.apply(this,arguments);if(t.length===0&&(arguments.length===0||typeof s!="function"))return t.apply(this,[]);var c=function(h){var I={},T=h.result();return T.forEach(function(N){var $={id:N.id,timestamp:N.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[N.type]||N.type};N.names().forEach(function(x){$[x]=N.stat(x)}),I[$.id]=$}),I},d=function(h){return new Map(Object.keys(h).map(function(I){return[I,h[I]]}))};if(arguments.length>=2){var u=function(h){o(d(c(h)))};return t.apply(this,[u,s])}return new Promise(function(l,h){t.apply(r,[function(I){l(d(c(I)))},h])}).then(o,a)}}}function Kp(i){if(!!((typeof i=="undefined"?"undefined":as(i))==="object"&&i.RTCPeerConnection&&i.RTCRtpSender&&i.RTCRtpReceiver)){if(!("getStats"in i.RTCRtpSender.prototype)){var t=i.RTCPeerConnection.prototype.getSenders;t&&(i.RTCPeerConnection.prototype.getSenders=function(){var o=this,a=t.apply(this,[]);return a.forEach(function(c){return c._pc=o}),a});var e=i.RTCPeerConnection.prototype.addTrack;e&&(i.RTCPeerConnection.prototype.addTrack=function(){var o=e.apply(this,arguments);return o._pc=this,o}),i.RTCRtpSender.prototype.getStats=function(){var o=this;return this._pc.getStats().then(function(a){return zr.filterStats(a,o.track,!0)})}}if(!("getStats"in i.RTCRtpReceiver.prototype)){var r=i.RTCPeerConnection.prototype.getReceivers;r&&(i.RTCPeerConnection.prototype.getReceivers=function(){var o=this,a=r.apply(this,[]);return a.forEach(function(c){return c._pc=o}),a}),zr.wrapPeerConnectionEvent(i,"track",function(s){return s.receiver._pc=s.srcElement,s}),i.RTCRtpReceiver.prototype.getStats=function(){var o=this;return this._pc.getStats().then(function(a){return zr.filterStats(a,o.track,!1)})}}if("getStats"in i.RTCRtpSender.prototype&&"getStats"in i.RTCRtpReceiver.prototype){var n=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof i.MediaStreamTrack){var o=arguments[0],a=void 0,c=void 0,d=void 0;return this.getSenders().forEach(function(u){u.track===o&&(a?d=!0:a=u)}),this.getReceivers().forEach(function(u){return u.track===o&&(c?d=!0:c=u),u.track===o}),d||a&&c?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):a?a.getStats():c?c.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return n.apply(this,arguments)}}}}function Ld(i){i.RTCPeerConnection.prototype.getLocalStreams=function(){var o=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(function(a){return o._shimmedLocalStreams[a][0]})};var t=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addTrack=function(o,a){if(!a)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};var c=t.apply(this,arguments);return this._shimmedLocalStreams[a.id]?this._shimmedLocalStreams[a.id].indexOf(c)===-1&&this._shimmedLocalStreams[a.id].push(c):this._shimmedLocalStreams[a.id]=[a,c],c};var e=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(o){var a=this;this._shimmedLocalStreams=this._shimmedLocalStreams||{},o.getTracks().forEach(function(u){var l=a.getSenders().find(function(h){return h.track===u});if(l)throw new DOMException("Track already exists.","InvalidAccessError")});var c=this.getSenders();e.apply(this,arguments);var d=this.getSenders().filter(function(u){return c.indexOf(u)===-1});this._shimmedLocalStreams[o.id]=[o].concat(d)};var r=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[o.id],r.apply(this,arguments)};var n=i.RTCPeerConnection.prototype.removeTrack;i.RTCPeerConnection.prototype.removeTrack=function(o){var a=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},o&&Object.keys(this._shimmedLocalStreams).forEach(function(c){var d=a._shimmedLocalStreams[c].indexOf(o);d!==-1&&a._shimmedLocalStreams[c].splice(d,1),a._shimmedLocalStreams[c].length===1&&delete a._shimmedLocalStreams[c]}),n.apply(this,arguments)}}function jp(i,t){if(!i.RTCPeerConnection)return;if(i.RTCPeerConnection.prototype.addTrack&&t.version>=65)return Ld(i);var e=i.RTCPeerConnection.prototype.getLocalStreams;i.RTCPeerConnection.prototype.getLocalStreams=function(){var u=this,l=e.apply(this);return this._reverseStreams=this._reverseStreams||{},l.map(function(h){return u._reverseStreams[h.id]})};var r=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(u){var l=this;if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},u.getTracks().forEach(function(I){var T=l.getSenders().find(function(N){return N.track===I});if(T)throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[u.id]){var h=new i.MediaStream(u.getTracks());this._streams[u.id]=h,this._reverseStreams[h.id]=u,u=h}r.apply(this,[u])};var n=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(u){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},n.apply(this,[this._streams[u.id]||u]),delete this._reverseStreams[this._streams[u.id]?this._streams[u.id].id:u.id],delete this._streams[u.id]},i.RTCPeerConnection.prototype.addTrack=function(u,l){var h=this;if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");var I=[].slice.call(arguments,1);if(I.length!==1||!I[0].getTracks().find(function(x){return x===u}))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");var T=this.getSenders().find(function(x){return x.track===u});if(T)throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};var N=this._streams[l.id];if(N)N.addTrack(u),Promise.resolve().then(function(){h.dispatchEvent(new Event("negotiationneeded"))});else{var $=new i.MediaStream([u]);this._streams[l.id]=$,this._reverseStreams[$.id]=l,this.addStream($)}return this.getSenders().find(function(x){return x.track===u})};function s(d,u){var l=u.sdp;return Object.keys(d._reverseStreams||[]).forEach(function(h){var I=d._reverseStreams[h],T=d._streams[I.id];l=l.replace(new RegExp(T.id,"g"),I.id)}),new RTCSessionDescription({type:u.type,sdp:l})}function o(d,u){var l=u.sdp;return Object.keys(d._reverseStreams||[]).forEach(function(h){var I=d._reverseStreams[h],T=d._streams[I.id];l=l.replace(new RegExp(I.id,"g"),T.id)}),new RTCSessionDescription({type:u.type,sdp:l})}["createOffer","createAnswer"].forEach(function(d){var u=i.RTCPeerConnection.prototype[d],l=Md({},d,function(){var h=this,I=arguments,T=arguments.length&&typeof arguments[0]=="function";return T?u.apply(this,[function(N){var $=s(h,N);I[0].apply(null,[$])},function(N){I[1]&&I[1].apply(null,N)},arguments[2]]):u.apply(this,arguments).then(function(N){return s(h,N)})});i.RTCPeerConnection.prototype[d]=l[d]});var a=i.RTCPeerConnection.prototype.setLocalDescription;i.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?a.apply(this,arguments):(arguments[0]=o(this,arguments[0]),a.apply(this,arguments))};var c=Object.getOwnPropertyDescriptor(i.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(i.RTCPeerConnection.prototype,"localDescription",{get:function(){var u=c.get.apply(this);return u.type===""?u:s(this,u)}}),i.RTCPeerConnection.prototype.removeTrack=function(u){var l=this;if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!u._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");var h=u._pc===this;if(!h)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};var I=void 0;Object.keys(this._streams).forEach(function(T){var N=l._streams[T].getTracks().find(function($){return u.track===$});N&&(I=l._streams[T])}),I&&(I.getTracks().length===1?this.removeStream(this._reverseStreams[I.id]):I.removeTrack(u.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Jp(i,t){!i.RTCPeerConnection&&i.webkitRTCPeerConnection&&(i.RTCPeerConnection=i.webkitRTCPeerConnection),!!i.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(e){var r=i.RTCPeerConnection.prototype[e],n=Md({},e,function(){return arguments[0]=new(e==="addIceCandidate"?i.RTCIceCandidate:i.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)});i.RTCPeerConnection.prototype[e]=n[e]})}function Yp(i,t){zr.wrapPeerConnectionEvent(i,"negotiationneeded",function(e){var r=e.target;if(!((t.version<72||r.getConfiguration&&r.getConfiguration().sdpSemantics==="plan-b")&&r.signalingState!=="stable"))return e})}});var xd=fe(Bo=>{"use strict";var Qf=_(f());Object.defineProperty(Bo,"__esModule",{value:!0});Bo.shimGetUserMedia=Xp;function Xp(i){var t=i&&i.navigator,e=function(s){return{name:{PermissionDeniedError:"NotAllowedError"}[s.name]||s.name,message:s.message,constraint:s.constraint,toString:function(){return this.name}}},r=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(n){return r(n).catch(function(s){return Promise.reject(e(s))})}}});var Ud=fe($o=>{"use strict";var eE=_(f());Object.defineProperty($o,"__esModule",{value:!0});$o.shimGetDisplayMedia=zp;function zp(i){"getDisplayMedia"in i.navigator&&(!i.navigator.mediaDevices||i.navigator.mediaDevices&&"getDisplayMedia"in i.navigator.mediaDevices||(i.navigator.mediaDevices.getDisplayMedia=i.navigator.getDisplayMedia.bind(i.navigator)))}});var Vd=fe(Ho=>{"use strict";var iE=_(f());Object.defineProperty(Ho,"__esModule",{value:!0});Ho.filterIceServers=eh;var qp=It(),Qp=Zp(qp);function Zp(i){if(i&&i.__esModule)return i;var t={};if(i!=null)for(var e in i)Object.prototype.hasOwnProperty.call(i,e)&&(t[e]=i[e]);return t.default=i,t}function eh(i,t){var e=!1;return i=JSON.parse(JSON.stringify(i)),i.filter(function(r){if(r&&(r.urls||r.url)){var n=r.urls||r.url;r.url&&!r.urls&&Qp.deprecated("RTCIceServer.url","RTCIceServer.urls");var s=typeof n=="string";return s&&(n=[n]),n=n.filter(function(o){if(o.indexOf("stun:")===0)return!1;var a=o.startsWith("turn")&&!o.startsWith("turn:[")&&o.includes("transport=udp");return a&&!e?(e=!0,!0):a&&!e}),delete r.url,r.urls=s?n[0]:n,!!n.length}})}});var Go=fe((rE,Fo)=>{"use strict";var nE=_(f()),P={};P.generateIdentifier=function(){return Math.random().toString(36).substr(2,10)};P.localCName=P.generateIdentifier();P.splitLines=function(i){return i.trim().split(`
2
2
  `).map(function(t){return t.trim()})};P.splitSections=function(i){var t=i.split(`
3
3
  m=`);return t.map(function(e,r){return(r>0?"m="+e:e).trim()+`\r
4
4
  `})};P.getDescription=function(i){var t=P.splitSections(i);return t&&t[0]};P.getMediaSections=function(i){var t=P.splitSections(i);return t.shift(),t};P.matchPrefix=function(i,t){return P.splitLines(i).filter(function(e){return e.indexOf(t)===0})};P.parseCandidate=function(i){var t;i.indexOf("a=candidate:")===0?t=i.substring(12).split(" "):t=i.substring(10).split(" ");for(var e={foundation:t[0],component:parseInt(t[1],10),protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]},r=8;r<t.length;r+=2)switch(t[r]){case"raddr":e.relatedAddress=t[r+1];break;case"rport":e.relatedPort=parseInt(t[r+1],10);break;case"tcptype":e.tcpType=t[r+1];break;case"ufrag":e.ufrag=t[r+1],e.usernameFragment=t[r+1];break;default:e[t[r]]=t[r+1];break}return e};P.writeCandidate=function(i){var t=[];t.push(i.foundation),t.push(i.component),t.push(i.protocol.toUpperCase()),t.push(i.priority),t.push(i.address||i.ip),t.push(i.port);var e=i.type;return t.push("typ"),t.push(e),e!=="host"&&i.relatedAddress&&i.relatedPort&&(t.push("raddr"),t.push(i.relatedAddress),t.push("rport"),t.push(i.relatedPort)),i.tcpType&&i.protocol.toLowerCase()==="tcp"&&(t.push("tcptype"),t.push(i.tcpType)),(i.usernameFragment||i.ufrag)&&(t.push("ufrag"),t.push(i.usernameFragment||i.ufrag)),"candidate:"+t.join(" ")};P.parseIceOptions=function(i){return i.substr(14).split(" ")};P.parseRtpMap=function(i){var t=i.substr(9).split(" "),e={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),e.name=t[0],e.clockRate=parseInt(t[1],10),e.channels=t.length===3?parseInt(t[2],10):1,e.numChannels=e.channels,e};P.writeRtpMap=function(i){var t=i.payloadType;i.preferredPayloadType!==void 0&&(t=i.preferredPayloadType);var e=i.channels||i.numChannels||1;return"a=rtpmap:"+t+" "+i.name+"/"+i.clockRate+(e!==1?"/"+e:"")+`\r
@@ -36,25 +36,25 @@ t=0 0\r
36
36
  `;n+="a="+s,n+="a=ssrc:"+i.sendEncodingParameters[0].ssrc+" "+s,i.sendEncodingParameters[0].rtx&&(n+="a=ssrc:"+i.sendEncodingParameters[0].rtx.ssrc+" "+s,n+="a=ssrc-group:FID "+i.sendEncodingParameters[0].ssrc+" "+i.sendEncodingParameters[0].rtx.ssrc+`\r
37
37
  `)}return n+="a=ssrc:"+i.sendEncodingParameters[0].ssrc+" cname:"+P.localCName+`\r
38
38
  `,i.rtpSender&&i.sendEncodingParameters[0].rtx&&(n+="a=ssrc:"+i.sendEncodingParameters[0].rtx.ssrc+" cname:"+P.localCName+`\r
39
- `),n};P.getDirection=function(i,t){for(var e=P.splitLines(i),r=0;r<e.length;r++)switch(e[r]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return e[r].substr(2);default:}return t?P.getDirection(t):"sendrecv"};P.getKind=function(i){var t=P.splitLines(i),e=t[0].split(" ");return e[0].substr(2)};P.isRejected=function(i){return i.split(" ",2)[1]==="0"};P.parseMLine=function(i){var t=P.splitLines(i),e=t[0].substr(2).split(" ");return{kind:e[0],port:parseInt(e[1],10),protocol:e[2],fmt:e.slice(3).join(" ")}};P.parseOLine=function(i){var t=P.matchPrefix(i,"o=")[0],e=t.substr(2).split(" ");return{username:e[0],sessionId:e[1],sessionVersion:parseInt(e[2],10),netType:e[3],addressType:e[4],address:e[5]}};P.isValidSDP=function(i){if(typeof i!="string"||i.length===0)return!1;for(var t=P.splitLines(i),e=0;e<t.length;e++)if(t[e].length<2||t[e].charAt(1)!=="=")return!1;return!0};typeof mo=="object"&&(mo.exports=P)});var fd=_e((Cf,_d)=>{"use strict";var yf=_(f()),j=_o();function Kp(i){return{inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[i.type]||i.type}function hd(i,t,e,r,n){var s=j.writeRtpDescription(i.kind,t);if(s+=j.writeIceParameters(i.iceGatherer.getLocalParameters()),s+=j.writeDtlsParameters(i.dtlsTransport.getLocalParameters(),e==="offer"?"actpass":n||"active"),s+="a=mid:"+i.mid+`\r
39
+ `),n};P.getDirection=function(i,t){for(var e=P.splitLines(i),r=0;r<e.length;r++)switch(e[r]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return e[r].substr(2);default:}return t?P.getDirection(t):"sendrecv"};P.getKind=function(i){var t=P.splitLines(i),e=t[0].split(" ");return e[0].substr(2)};P.isRejected=function(i){return i.split(" ",2)[1]==="0"};P.parseMLine=function(i){var t=P.splitLines(i),e=t[0].substr(2).split(" ");return{kind:e[0],port:parseInt(e[1],10),protocol:e[2],fmt:e.slice(3).join(" ")}};P.parseOLine=function(i){var t=P.matchPrefix(i,"o=")[0],e=t.substr(2).split(" ");return{username:e[0],sessionId:e[1],sessionVersion:parseInt(e[2],10),netType:e[3],addressType:e[4],address:e[5]}};P.isValidSDP=function(i){if(typeof i!="string"||i.length===0)return!1;for(var t=P.splitLines(i),e=0;e<t.length;e++)if(t[e].length<2||t[e].charAt(1)!=="=")return!1;return!0};typeof Fo=="object"&&(Fo.exports=P)});var Hd=fe((sE,$d)=>{"use strict";var oE=_(f()),K=Go();function th(i){return{inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[i.type]||i.type}function wd(i,t,e,r,n){var s=K.writeRtpDescription(i.kind,t);if(s+=K.writeIceParameters(i.iceGatherer.getLocalParameters()),s+=K.writeDtlsParameters(i.dtlsTransport.getLocalParameters(),e==="offer"?"actpass":n||"active"),s+="a=mid:"+i.mid+`\r
40
40
  `,i.rtpSender&&i.rtpReceiver?s+=`a=sendrecv\r
41
41
  `:i.rtpSender?s+=`a=sendonly\r
42
42
  `:i.rtpReceiver?s+=`a=recvonly\r
43
43
  `:s+=`a=inactive\r
44
44
  `,i.rtpSender){var o=i.rtpSender._initialTrackId||i.rtpSender.track.id;i.rtpSender._initialTrackId=o;var a="msid:"+(r?r.id:"-")+" "+o+`\r
45
45
  `;s+="a="+a,s+="a=ssrc:"+i.sendEncodingParameters[0].ssrc+" "+a,i.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+i.sendEncodingParameters[0].rtx.ssrc+" "+a,s+="a=ssrc-group:FID "+i.sendEncodingParameters[0].ssrc+" "+i.sendEncodingParameters[0].rtx.ssrc+`\r
46
- `)}return s+="a=ssrc:"+i.sendEncodingParameters[0].ssrc+" cname:"+j.localCName+`\r
47
- `,i.rtpSender&&i.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+i.sendEncodingParameters[0].rtx.ssrc+" cname:"+j.localCName+`\r
48
- `),s}function jp(i,t){var e=!1;return i=JSON.parse(JSON.stringify(i)),i.filter(function(r){if(r&&(r.urls||r.url)){var n=r.urls||r.url;r.url&&!r.urls&&console.warn("RTCIceServer.url is deprecated! Use urls instead.");var s=typeof n=="string";return s&&(n=[n]),n=n.filter(function(o){var a=o.indexOf("turn:")===0&&o.indexOf("transport=udp")!==-1&&o.indexOf("turn:[")===-1&&!e;return a?(e=!0,!0):o.indexOf("stun:")===0&&t>=14393&&o.indexOf("?transport=udp")===-1}),delete r.url,r.urls=s?n[0]:n,!!n.length}})}function Un(i,t){var e={codecs:[],headerExtensions:[],fecMechanisms:[]},r=function(s,o){s=parseInt(s,10);for(var a=0;a<o.length;a++)if(o[a].payloadType===s||o[a].preferredPayloadType===s)return o[a]},n=function(s,o,a,c){var d=r(s.parameters.apt,a),u=r(o.parameters.apt,c);return d&&u&&d.name.toLowerCase()===u.name.toLowerCase()};return i.codecs.forEach(function(s){for(var o=0;o<t.codecs.length;o++){var a=t.codecs[o];if(s.name.toLowerCase()===a.name.toLowerCase()&&s.clockRate===a.clockRate){if(s.name.toLowerCase()==="rtx"&&s.parameters&&a.parameters.apt&&!n(s,a,i.codecs,t.codecs))continue;a=JSON.parse(JSON.stringify(a)),a.numChannels=Math.min(s.numChannels,a.numChannels),e.codecs.push(a),a.rtcpFeedback=a.rtcpFeedback.filter(function(c){for(var d=0;d<s.rtcpFeedback.length;d++)if(s.rtcpFeedback[d].type===c.type&&s.rtcpFeedback[d].parameter===c.parameter)return!0;return!1});break}}}),i.headerExtensions.forEach(function(s){for(var o=0;o<t.headerExtensions.length;o++){var a=t.headerExtensions[o];if(s.uri===a.uri){e.headerExtensions.push(a);break}}}),e}function md(i,t,e){return{offer:{setLocalDescription:["stable","have-local-offer"],setRemoteDescription:["stable","have-remote-offer"]},answer:{setLocalDescription:["have-remote-offer","have-local-pranswer"],setRemoteDescription:["have-local-offer","have-remote-pranswer"]}}[t][i].indexOf(e)!==-1}function fo(i,t){var e=i.getRemoteCandidates().find(function(r){return t.foundation===r.foundation&&t.ip===r.ip&&t.port===r.port&&t.priority===r.priority&&t.protocol===r.protocol&&t.type===r.type});return e||i.addRemoteCandidate(t),!e}function Pe(i,t){var e=new Error(t);return e.name=i,e.code={NotSupportedError:9,InvalidStateError:11,InvalidAccessError:15,TypeError:void 0,OperationError:void 0}[i],e}_d.exports=function(i,t){function e(c,d){d.addTrack(c),d.dispatchEvent(new i.MediaStreamTrackEvent("addtrack",{track:c}))}function r(c,d){d.removeTrack(c),d.dispatchEvent(new i.MediaStreamTrackEvent("removetrack",{track:c}))}function n(c,d,u,l){var h=new Event("track");h.track=d,h.receiver=u,h.transceiver={receiver:u},h.streams=l,i.setTimeout(function(){c._dispatchEvent("track",h)})}var s=function(c){var d=this,u=document.createDocumentFragment();if(["addEventListener","removeEventListener","dispatchEvent"].forEach(function(h){d[h]=u[h].bind(u)}),this.canTrickleIceCandidates=null,this.needNegotiation=!1,this.localStreams=[],this.remoteStreams=[],this._localDescription=null,this._remoteDescription=null,this.signalingState="stable",this.iceConnectionState="new",this.connectionState="new",this.iceGatheringState="new",c=JSON.parse(JSON.stringify(c||{})),this.usingBundle=c.bundlePolicy==="max-bundle",c.rtcpMuxPolicy==="negotiate")throw Pe("NotSupportedError","rtcpMuxPolicy 'negotiate' is not supported");switch(c.rtcpMuxPolicy||(c.rtcpMuxPolicy="require"),c.iceTransportPolicy){case"all":case"relay":break;default:c.iceTransportPolicy="all";break}switch(c.bundlePolicy){case"balanced":case"max-compat":case"max-bundle":break;default:c.bundlePolicy="balanced";break}if(c.iceServers=jp(c.iceServers||[],t),this._iceGatherers=[],c.iceCandidatePoolSize)for(var l=c.iceCandidatePoolSize;l>0;l--)this._iceGatherers.push(new i.RTCIceGatherer({iceServers:c.iceServers,gatherPolicy:c.iceTransportPolicy}));else c.iceCandidatePoolSize=0;this._config=c,this.transceivers=[],this._sdpSessionId=j.generateSessionId(),this._sdpSessionVersion=0,this._dtlsRole=void 0,this._isClosed=!1};Object.defineProperty(s.prototype,"localDescription",{configurable:!0,get:function(){return this._localDescription}}),Object.defineProperty(s.prototype,"remoteDescription",{configurable:!0,get:function(){return this._remoteDescription}}),s.prototype.onicecandidate=null,s.prototype.onaddstream=null,s.prototype.ontrack=null,s.prototype.onremovestream=null,s.prototype.onsignalingstatechange=null,s.prototype.oniceconnectionstatechange=null,s.prototype.onconnectionstatechange=null,s.prototype.onicegatheringstatechange=null,s.prototype.onnegotiationneeded=null,s.prototype.ondatachannel=null,s.prototype._dispatchEvent=function(c,d){this._isClosed||(this.dispatchEvent(d),typeof this["on"+c]=="function"&&this["on"+c](d))},s.prototype._emitGatheringStateChange=function(){var c=new Event("icegatheringstatechange");this._dispatchEvent("icegatheringstatechange",c)},s.prototype.getConfiguration=function(){return this._config},s.prototype.getLocalStreams=function(){return this.localStreams},s.prototype.getRemoteStreams=function(){return this.remoteStreams},s.prototype._createTransceiver=function(c,d){var u=this.transceivers.length>0,l={track:null,iceGatherer:null,iceTransport:null,dtlsTransport:null,localCapabilities:null,remoteCapabilities:null,rtpSender:null,rtpReceiver:null,kind:c,mid:null,sendEncodingParameters:null,recvEncodingParameters:null,stream:null,associatedRemoteMediaStreams:[],wantReceive:!0};if(this.usingBundle&&u)l.iceTransport=this.transceivers[0].iceTransport,l.dtlsTransport=this.transceivers[0].dtlsTransport;else{var h=this._createIceAndDtlsTransports();l.iceTransport=h.iceTransport,l.dtlsTransport=h.dtlsTransport}return d||this.transceivers.push(l),l},s.prototype.addTrack=function(c,d){if(this._isClosed)throw Pe("InvalidStateError","Attempted to call addTrack on a closed peerconnection.");var u=this.transceivers.find(function(I){return I.track===c});if(u)throw Pe("InvalidAccessError","Track already exists.");for(var l,h=0;h<this.transceivers.length;h++)!this.transceivers[h].track&&this.transceivers[h].kind===c.kind&&(l=this.transceivers[h]);return l||(l=this._createTransceiver(c.kind)),this._maybeFireNegotiationNeeded(),this.localStreams.indexOf(d)===-1&&this.localStreams.push(d),l.track=c,l.stream=d,l.rtpSender=new i.RTCRtpSender(c,l.dtlsTransport),l.rtpSender},s.prototype.addStream=function(c){var d=this;if(t>=15025)c.getTracks().forEach(function(l){d.addTrack(l,c)});else{var u=c.clone();c.getTracks().forEach(function(l,h){var I=u.getTracks()[h];l.addEventListener("enabled",function(T){I.enabled=T.enabled})}),u.getTracks().forEach(function(l){d.addTrack(l,u)})}},s.prototype.removeTrack=function(c){if(this._isClosed)throw Pe("InvalidStateError","Attempted to call removeTrack on a closed peerconnection.");if(!(c instanceof i.RTCRtpSender))throw new TypeError("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.");var d=this.transceivers.find(function(h){return h.rtpSender===c});if(!d)throw Pe("InvalidAccessError","Sender was not created by this connection.");var u=d.stream;d.rtpSender.stop(),d.rtpSender=null,d.track=null,d.stream=null;var l=this.transceivers.map(function(h){return h.stream});l.indexOf(u)===-1&&this.localStreams.indexOf(u)>-1&&this.localStreams.splice(this.localStreams.indexOf(u),1),this._maybeFireNegotiationNeeded()},s.prototype.removeStream=function(c){var d=this;c.getTracks().forEach(function(u){var l=d.getSenders().find(function(h){return h.track===u});l&&d.removeTrack(l)})},s.prototype.getSenders=function(){return this.transceivers.filter(function(c){return!!c.rtpSender}).map(function(c){return c.rtpSender})},s.prototype.getReceivers=function(){return this.transceivers.filter(function(c){return!!c.rtpReceiver}).map(function(c){return c.rtpReceiver})},s.prototype._createIceGatherer=function(c,d){var u=this;if(d&&c>0)return this.transceivers[0].iceGatherer;if(this._iceGatherers.length)return this._iceGatherers.shift();var l=new i.RTCIceGatherer({iceServers:this._config.iceServers,gatherPolicy:this._config.iceTransportPolicy});return Object.defineProperty(l,"state",{value:"new",writable:!0}),this.transceivers[c].bufferedCandidateEvents=[],this.transceivers[c].bufferCandidates=function(h){var I=!h.candidate||Object.keys(h.candidate).length===0;l.state=I?"completed":"gathering",u.transceivers[c].bufferedCandidateEvents!==null&&u.transceivers[c].bufferedCandidateEvents.push(h)},l.addEventListener("localcandidate",this.transceivers[c].bufferCandidates),l},s.prototype._gather=function(c,d){var u=this,l=this.transceivers[d].iceGatherer;if(!l.onlocalcandidate){var h=this.transceivers[d].bufferedCandidateEvents;this.transceivers[d].bufferedCandidateEvents=null,l.removeEventListener("localcandidate",this.transceivers[d].bufferCandidates),l.onlocalcandidate=function(I){if(!(u.usingBundle&&d>0)){var T=new Event("icecandidate");T.candidate={sdpMid:c,sdpMLineIndex:d};var N=I.candidate,H=!N||Object.keys(N).length===0;if(H)(l.state==="new"||l.state==="gathering")&&(l.state="completed");else{l.state==="new"&&(l.state="gathering"),N.component=1,N.ufrag=l.getLocalParameters().usernameFragment;var U=j.writeCandidate(N);T.candidate=Object.assign(T.candidate,j.parseCandidate(U)),T.candidate.candidate=U,T.candidate.toJSON=function(){return{candidate:T.candidate.candidate,sdpMid:T.candidate.sdpMid,sdpMLineIndex:T.candidate.sdpMLineIndex,usernameFragment:T.candidate.usernameFragment}}}var G=j.getMediaSections(u._localDescription.sdp);H?G[T.candidate.sdpMLineIndex]+=`a=end-of-candidates\r
49
- `:G[T.candidate.sdpMLineIndex]+="a="+T.candidate.candidate+`\r
50
- `,u._localDescription.sdp=j.getDescription(u._localDescription.sdp)+G.join("");var Ie=u.transceivers.every(function(A){return A.iceGatherer&&A.iceGatherer.state==="completed"});u.iceGatheringState!=="gathering"&&(u.iceGatheringState="gathering",u._emitGatheringStateChange()),H||u._dispatchEvent("icecandidate",T),Ie&&(u._dispatchEvent("icecandidate",new Event("icecandidate")),u.iceGatheringState="complete",u._emitGatheringStateChange())}},i.setTimeout(function(){h.forEach(function(I){l.onlocalcandidate(I)})},0)}},s.prototype._createIceAndDtlsTransports=function(){var c=this,d=new i.RTCIceTransport(null);d.onicestatechange=function(){c._updateIceConnectionState(),c._updateConnectionState()};var u=new i.RTCDtlsTransport(d);return u.ondtlsstatechange=function(){c._updateConnectionState()},u.onerror=function(){Object.defineProperty(u,"state",{value:"failed",writable:!0}),c._updateConnectionState()},{iceTransport:d,dtlsTransport:u}},s.prototype._disposeIceAndDtlsTransports=function(c){var d=this.transceivers[c].iceGatherer;d&&(delete d.onlocalcandidate,delete this.transceivers[c].iceGatherer);var u=this.transceivers[c].iceTransport;u&&(delete u.onicestatechange,delete this.transceivers[c].iceTransport);var l=this.transceivers[c].dtlsTransport;l&&(delete l.ondtlsstatechange,delete l.onerror,delete this.transceivers[c].dtlsTransport)},s.prototype._transceive=function(c,d,u){var l=Un(c.localCapabilities,c.remoteCapabilities);d&&c.rtpSender&&(l.encodings=c.sendEncodingParameters,l.rtcp={cname:j.localCName,compound:c.rtcpParameters.compound},c.recvEncodingParameters.length&&(l.rtcp.ssrc=c.recvEncodingParameters[0].ssrc),c.rtpSender.send(l)),u&&c.rtpReceiver&&l.codecs.length>0&&(c.kind==="video"&&c.recvEncodingParameters&&t<15019&&c.recvEncodingParameters.forEach(function(h){delete h.rtx}),c.recvEncodingParameters.length?l.encodings=c.recvEncodingParameters:l.encodings=[{}],l.rtcp={compound:c.rtcpParameters.compound},c.rtcpParameters.cname&&(l.rtcp.cname=c.rtcpParameters.cname),c.sendEncodingParameters.length&&(l.rtcp.ssrc=c.sendEncodingParameters[0].ssrc),c.rtpReceiver.receive(l))},s.prototype.setLocalDescription=function(c){var d=this;if(["offer","answer"].indexOf(c.type)===-1)return Promise.reject(Pe("TypeError",'Unsupported type "'+c.type+'"'));if(!md("setLocalDescription",c.type,d.signalingState)||d._isClosed)return Promise.reject(Pe("InvalidStateError","Can not set local "+c.type+" in state "+d.signalingState));var u,l;if(c.type==="offer")u=j.splitSections(c.sdp),l=u.shift(),u.forEach(function(I,T){var N=j.parseRtpParameters(I);d.transceivers[T].localCapabilities=N}),d.transceivers.forEach(function(I,T){d._gather(I.mid,T)});else if(c.type==="answer"){u=j.splitSections(d._remoteDescription.sdp),l=u.shift();var h=j.matchPrefix(l,"a=ice-lite").length>0;u.forEach(function(I,T){var N=d.transceivers[T],H=N.iceGatherer,U=N.iceTransport,G=N.dtlsTransport,Ie=N.localCapabilities,A=N.remoteCapabilities,V=j.isRejected(I)&&j.matchPrefix(I,"a=bundle-only").length===0;if(!V&&!N.rejected){var y=j.getIceParameters(I,l),Y=j.getDtlsParameters(I,l);h&&(Y.role="server"),(!d.usingBundle||T===0)&&(d._gather(N.mid,T),U.state==="new"&&U.start(H,y,h?"controlling":"controlled"),G.state==="new"&&G.start(Y));var re=Un(Ie,A);d._transceive(N,re.codecs.length>0,!1)}})}return d._localDescription={type:c.type,sdp:c.sdp},c.type==="offer"?d._updateSignalingState("have-local-offer"):d._updateSignalingState("stable"),Promise.resolve()},s.prototype.setRemoteDescription=function(c){var d=this;if(["offer","answer"].indexOf(c.type)===-1)return Promise.reject(Pe("TypeError",'Unsupported type "'+c.type+'"'));if(!md("setRemoteDescription",c.type,d.signalingState)||d._isClosed)return Promise.reject(Pe("InvalidStateError","Can not set remote "+c.type+" in state "+d.signalingState));var u={};d.remoteStreams.forEach(function(U){u[U.id]=U});var l=[],h=j.splitSections(c.sdp),I=h.shift(),T=j.matchPrefix(I,"a=ice-lite").length>0,N=j.matchPrefix(I,"a=group:BUNDLE ").length>0;d.usingBundle=N;var H=j.matchPrefix(I,"a=ice-options:")[0];return H?d.canTrickleIceCandidates=H.substr(14).split(" ").indexOf("trickle")>=0:d.canTrickleIceCandidates=!1,h.forEach(function(U,G){var Ie=j.splitLines(U),A=j.getKind(U),V=j.isRejected(U)&&j.matchPrefix(U,"a=bundle-only").length===0,y=Ie[0].substr(2).split(" ")[2],Y=j.getDirection(U,I),re=j.parseMsid(U),Ae=j.getMid(U)||j.generateIdentifier();if(V||A==="application"&&(y==="DTLS/SCTP"||y==="UDP/DTLS/SCTP")){d.transceivers[G]={mid:Ae,kind:A,protocol:y,rejected:!0};return}!V&&d.transceivers[G]&&d.transceivers[G].rejected&&(d.transceivers[G]=d._createTransceiver(A,!0));var W,x,k,R,g,eo,to,Rr,Mt,Kc=j.parseRtpParameters(U),jc,io;V||(jc=j.getIceParameters(U,I),io=j.getDtlsParameters(U,I),io.role="client"),to=j.parseRtpEncodingParameters(U);var Jc=j.parseRtcpParameters(U),Yc=j.matchPrefix(U,"a=end-of-candidates",I).length>0,Wi=j.matchPrefix(U,"a=candidate:").map(function(Fe){return j.parseCandidate(Fe)}).filter(function(Fe){return Fe.component===1});if((c.type==="offer"||c.type==="answer")&&!V&&N&&G>0&&d.transceivers[G]&&(d._disposeIceAndDtlsTransports(G),d.transceivers[G].iceGatherer=d.transceivers[0].iceGatherer,d.transceivers[G].iceTransport=d.transceivers[0].iceTransport,d.transceivers[G].dtlsTransport=d.transceivers[0].dtlsTransport,d.transceivers[G].rtpSender&&d.transceivers[G].rtpSender.setTransport(d.transceivers[0].dtlsTransport),d.transceivers[G].rtpReceiver&&d.transceivers[G].rtpReceiver.setTransport(d.transceivers[0].dtlsTransport)),c.type==="offer"&&!V){W=d.transceivers[G]||d._createTransceiver(A),W.mid=Ae,W.iceGatherer||(W.iceGatherer=d._createIceGatherer(G,N)),Wi.length&&W.iceTransport.state==="new"&&(Yc&&(!N||G===0)?W.iceTransport.setRemoteCandidates(Wi):Wi.forEach(function(Fe){fo(W.iceTransport,Fe)})),Rr=i.RTCRtpReceiver.getCapabilities(A),t<15019&&(Rr.codecs=Rr.codecs.filter(function(Fe){return Fe.name!=="rtx"})),eo=W.sendEncodingParameters||[{ssrc:(2*G+2)*1001}];var ro=!1;if(Y==="sendrecv"||Y==="sendonly"){if(ro=!W.rtpReceiver,g=W.rtpReceiver||new i.RTCRtpReceiver(W.dtlsTransport,A),ro){var K;Mt=g.track,re&&re.stream==="-"||(re?(u[re.stream]||(u[re.stream]=new i.MediaStream,Object.defineProperty(u[re.stream],"id",{get:function(){return re.stream}})),Object.defineProperty(Mt,"id",{get:function(){return re.track}}),K=u[re.stream]):(u.default||(u.default=new i.MediaStream),K=u.default)),K&&(e(Mt,K),W.associatedRemoteMediaStreams.push(K)),l.push([Mt,g,K])}}else W.rtpReceiver&&W.rtpReceiver.track&&(W.associatedRemoteMediaStreams.forEach(function(Fe){var Xc=Fe.getTracks().find(function(ap){return ap.id===W.rtpReceiver.track.id});Xc&&r(Xc,Fe)}),W.associatedRemoteMediaStreams=[]);W.localCapabilities=Rr,W.remoteCapabilities=Kc,W.rtpReceiver=g,W.rtcpParameters=Jc,W.sendEncodingParameters=eo,W.recvEncodingParameters=to,d._transceive(d.transceivers[G],!1,ro)}else if(c.type==="answer"&&!V){W=d.transceivers[G],x=W.iceGatherer,k=W.iceTransport,R=W.dtlsTransport,g=W.rtpReceiver,eo=W.sendEncodingParameters,Rr=W.localCapabilities,d.transceivers[G].recvEncodingParameters=to,d.transceivers[G].remoteCapabilities=Kc,d.transceivers[G].rtcpParameters=Jc,Wi.length&&k.state==="new"&&((T||Yc)&&(!N||G===0)?k.setRemoteCandidates(Wi):Wi.forEach(function(Fe){fo(W.iceTransport,Fe)})),(!N||G===0)&&(k.state==="new"&&k.start(x,jc,"controlling"),R.state==="new"&&R.start(io));var sp=Un(W.localCapabilities,W.remoteCapabilities),op=sp.codecs.filter(function(Fe){return Fe.name.toLowerCase()==="rtx"}).length;!op&&W.sendEncodingParameters[0].rtx&&delete W.sendEncodingParameters[0].rtx,d._transceive(W,Y==="sendrecv"||Y==="recvonly",Y==="sendrecv"||Y==="sendonly"),g&&(Y==="sendrecv"||Y==="sendonly")?(Mt=g.track,re?(u[re.stream]||(u[re.stream]=new i.MediaStream),e(Mt,u[re.stream]),l.push([Mt,g,u[re.stream]])):(u.default||(u.default=new i.MediaStream),e(Mt,u.default),l.push([Mt,g,u.default]))):delete W.rtpReceiver}}),d._dtlsRole===void 0&&(d._dtlsRole=c.type==="offer"?"active":"passive"),d._remoteDescription={type:c.type,sdp:c.sdp},c.type==="offer"?d._updateSignalingState("have-remote-offer"):d._updateSignalingState("stable"),Object.keys(u).forEach(function(U){var G=u[U];if(G.getTracks().length){if(d.remoteStreams.indexOf(G)===-1){d.remoteStreams.push(G);var Ie=new Event("addstream");Ie.stream=G,i.setTimeout(function(){d._dispatchEvent("addstream",Ie)})}l.forEach(function(A){var V=A[0],y=A[1];G.id===A[2].id&&n(d,V,y,[G])})}}),l.forEach(function(U){U[2]||n(d,U[0],U[1],[])}),i.setTimeout(function(){!(d&&d.transceivers)||d.transceivers.forEach(function(U){U.iceTransport&&U.iceTransport.state==="new"&&U.iceTransport.getRemoteCandidates().length>0&&(console.warn("Timeout for addRemoteCandidate. Consider sending an end-of-candidates notification"),U.iceTransport.addRemoteCandidate({}))})},4e3),Promise.resolve()},s.prototype.close=function(){this.transceivers.forEach(function(c){c.iceTransport&&c.iceTransport.stop(),c.dtlsTransport&&c.dtlsTransport.stop(),c.rtpSender&&c.rtpSender.stop(),c.rtpReceiver&&c.rtpReceiver.stop()}),this._isClosed=!0,this._updateSignalingState("closed")},s.prototype._updateSignalingState=function(c){this.signalingState=c;var d=new Event("signalingstatechange");this._dispatchEvent("signalingstatechange",d)},s.prototype._maybeFireNegotiationNeeded=function(){var c=this;this.signalingState!=="stable"||this.needNegotiation===!0||(this.needNegotiation=!0,i.setTimeout(function(){if(c.needNegotiation){c.needNegotiation=!1;var d=new Event("negotiationneeded");c._dispatchEvent("negotiationneeded",d)}},0))},s.prototype._updateIceConnectionState=function(){var c,d={new:0,closed:0,checking:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach(function(l){l.iceTransport&&!l.rejected&&d[l.iceTransport.state]++}),c="new",d.failed>0?c="failed":d.checking>0?c="checking":d.disconnected>0?c="disconnected":d.new>0?c="new":d.connected>0?c="connected":d.completed>0&&(c="completed"),c!==this.iceConnectionState){this.iceConnectionState=c;var u=new Event("iceconnectionstatechange");this._dispatchEvent("iceconnectionstatechange",u)}},s.prototype._updateConnectionState=function(){var c,d={new:0,closed:0,connecting:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach(function(l){l.iceTransport&&l.dtlsTransport&&!l.rejected&&(d[l.iceTransport.state]++,d[l.dtlsTransport.state]++)}),d.connected+=d.completed,c="new",d.failed>0?c="failed":d.connecting>0?c="connecting":d.disconnected>0?c="disconnected":d.new>0?c="new":d.connected>0&&(c="connected"),c!==this.connectionState){this.connectionState=c;var u=new Event("connectionstatechange");this._dispatchEvent("connectionstatechange",u)}},s.prototype.createOffer=function(){var c=this;if(c._isClosed)return Promise.reject(Pe("InvalidStateError","Can not call createOffer after close"));var d=c.transceivers.filter(function(T){return T.kind==="audio"}).length,u=c.transceivers.filter(function(T){return T.kind==="video"}).length,l=arguments[0];if(l){if(l.mandatory||l.optional)throw new TypeError("Legacy mandatory/optional constraints not supported.");l.offerToReceiveAudio!==void 0&&(l.offerToReceiveAudio===!0?d=1:l.offerToReceiveAudio===!1?d=0:d=l.offerToReceiveAudio),l.offerToReceiveVideo!==void 0&&(l.offerToReceiveVideo===!0?u=1:l.offerToReceiveVideo===!1?u=0:u=l.offerToReceiveVideo)}for(c.transceivers.forEach(function(T){T.kind==="audio"?(d--,d<0&&(T.wantReceive=!1)):T.kind==="video"&&(u--,u<0&&(T.wantReceive=!1))});d>0||u>0;)d>0&&(c._createTransceiver("audio"),d--),u>0&&(c._createTransceiver("video"),u--);var h=j.writeSessionBoilerplate(c._sdpSessionId,c._sdpSessionVersion++);c.transceivers.forEach(function(T,N){var H=T.track,U=T.kind,G=T.mid||j.generateIdentifier();T.mid=G,T.iceGatherer||(T.iceGatherer=c._createIceGatherer(N,c.usingBundle));var Ie=i.RTCRtpSender.getCapabilities(U);t<15019&&(Ie.codecs=Ie.codecs.filter(function(V){return V.name!=="rtx"})),Ie.codecs.forEach(function(V){V.name==="H264"&&V.parameters["level-asymmetry-allowed"]===void 0&&(V.parameters["level-asymmetry-allowed"]="1"),T.remoteCapabilities&&T.remoteCapabilities.codecs&&T.remoteCapabilities.codecs.forEach(function(y){V.name.toLowerCase()===y.name.toLowerCase()&&V.clockRate===y.clockRate&&(V.preferredPayloadType=y.payloadType)})}),Ie.headerExtensions.forEach(function(V){var y=T.remoteCapabilities&&T.remoteCapabilities.headerExtensions||[];y.forEach(function(Y){V.uri===Y.uri&&(V.id=Y.id)})});var A=T.sendEncodingParameters||[{ssrc:(2*N+1)*1001}];H&&t>=15019&&U==="video"&&!A[0].rtx&&(A[0].rtx={ssrc:A[0].ssrc+1}),T.wantReceive&&(T.rtpReceiver=new i.RTCRtpReceiver(T.dtlsTransport,U)),T.localCapabilities=Ie,T.sendEncodingParameters=A}),c._config.bundlePolicy!=="max-compat"&&(h+="a=group:BUNDLE "+c.transceivers.map(function(T){return T.mid}).join(" ")+`\r
46
+ `)}return s+="a=ssrc:"+i.sendEncodingParameters[0].ssrc+" cname:"+K.localCName+`\r
47
+ `,i.rtpSender&&i.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+i.sendEncodingParameters[0].rtx.ssrc+" cname:"+K.localCName+`\r
48
+ `),s}function ih(i,t){var e=!1;return i=JSON.parse(JSON.stringify(i)),i.filter(function(r){if(r&&(r.urls||r.url)){var n=r.urls||r.url;r.url&&!r.urls&&console.warn("RTCIceServer.url is deprecated! Use urls instead.");var s=typeof n=="string";return s&&(n=[n]),n=n.filter(function(o){var a=o.indexOf("turn:")===0&&o.indexOf("transport=udp")!==-1&&o.indexOf("turn:[")===-1&&!e;return a?(e=!0,!0):o.indexOf("stun:")===0&&t>=14393&&o.indexOf("?transport=udp")===-1}),delete r.url,r.urls=s?n[0]:n,!!n.length}})}function cs(i,t){var e={codecs:[],headerExtensions:[],fecMechanisms:[]},r=function(s,o){s=parseInt(s,10);for(var a=0;a<o.length;a++)if(o[a].payloadType===s||o[a].preferredPayloadType===s)return o[a]},n=function(s,o,a,c){var d=r(s.parameters.apt,a),u=r(o.parameters.apt,c);return d&&u&&d.name.toLowerCase()===u.name.toLowerCase()};return i.codecs.forEach(function(s){for(var o=0;o<t.codecs.length;o++){var a=t.codecs[o];if(s.name.toLowerCase()===a.name.toLowerCase()&&s.clockRate===a.clockRate){if(s.name.toLowerCase()==="rtx"&&s.parameters&&a.parameters.apt&&!n(s,a,i.codecs,t.codecs))continue;a=JSON.parse(JSON.stringify(a)),a.numChannels=Math.min(s.numChannels,a.numChannels),e.codecs.push(a),a.rtcpFeedback=a.rtcpFeedback.filter(function(c){for(var d=0;d<s.rtcpFeedback.length;d++)if(s.rtcpFeedback[d].type===c.type&&s.rtcpFeedback[d].parameter===c.parameter)return!0;return!1});break}}}),i.headerExtensions.forEach(function(s){for(var o=0;o<t.headerExtensions.length;o++){var a=t.headerExtensions[o];if(s.uri===a.uri){e.headerExtensions.push(a);break}}}),e}function Bd(i,t,e){return{offer:{setLocalDescription:["stable","have-local-offer"],setRemoteDescription:["stable","have-remote-offer"]},answer:{setLocalDescription:["have-remote-offer","have-local-pranswer"],setRemoteDescription:["have-local-offer","have-remote-pranswer"]}}[t][i].indexOf(e)!==-1}function Wo(i,t){var e=i.getRemoteCandidates().find(function(r){return t.foundation===r.foundation&&t.ip===r.ip&&t.port===r.port&&t.priority===r.priority&&t.protocol===r.protocol&&t.type===r.type});return e||i.addRemoteCandidate(t),!e}function Pe(i,t){var e=new Error(t);return e.name=i,e.code={NotSupportedError:9,InvalidStateError:11,InvalidAccessError:15,TypeError:void 0,OperationError:void 0}[i],e}$d.exports=function(i,t){function e(c,d){d.addTrack(c),d.dispatchEvent(new i.MediaStreamTrackEvent("addtrack",{track:c}))}function r(c,d){d.removeTrack(c),d.dispatchEvent(new i.MediaStreamTrackEvent("removetrack",{track:c}))}function n(c,d,u,l){var h=new Event("track");h.track=d,h.receiver=u,h.transceiver={receiver:u},h.streams=l,i.setTimeout(function(){c._dispatchEvent("track",h)})}var s=function(c){var d=this,u=document.createDocumentFragment();if(["addEventListener","removeEventListener","dispatchEvent"].forEach(function(h){d[h]=u[h].bind(u)}),this.canTrickleIceCandidates=null,this.needNegotiation=!1,this.localStreams=[],this.remoteStreams=[],this._localDescription=null,this._remoteDescription=null,this.signalingState="stable",this.iceConnectionState="new",this.connectionState="new",this.iceGatheringState="new",c=JSON.parse(JSON.stringify(c||{})),this.usingBundle=c.bundlePolicy==="max-bundle",c.rtcpMuxPolicy==="negotiate")throw Pe("NotSupportedError","rtcpMuxPolicy 'negotiate' is not supported");switch(c.rtcpMuxPolicy||(c.rtcpMuxPolicy="require"),c.iceTransportPolicy){case"all":case"relay":break;default:c.iceTransportPolicy="all";break}switch(c.bundlePolicy){case"balanced":case"max-compat":case"max-bundle":break;default:c.bundlePolicy="balanced";break}if(c.iceServers=ih(c.iceServers||[],t),this._iceGatherers=[],c.iceCandidatePoolSize)for(var l=c.iceCandidatePoolSize;l>0;l--)this._iceGatherers.push(new i.RTCIceGatherer({iceServers:c.iceServers,gatherPolicy:c.iceTransportPolicy}));else c.iceCandidatePoolSize=0;this._config=c,this.transceivers=[],this._sdpSessionId=K.generateSessionId(),this._sdpSessionVersion=0,this._dtlsRole=void 0,this._isClosed=!1};Object.defineProperty(s.prototype,"localDescription",{configurable:!0,get:function(){return this._localDescription}}),Object.defineProperty(s.prototype,"remoteDescription",{configurable:!0,get:function(){return this._remoteDescription}}),s.prototype.onicecandidate=null,s.prototype.onaddstream=null,s.prototype.ontrack=null,s.prototype.onremovestream=null,s.prototype.onsignalingstatechange=null,s.prototype.oniceconnectionstatechange=null,s.prototype.onconnectionstatechange=null,s.prototype.onicegatheringstatechange=null,s.prototype.onnegotiationneeded=null,s.prototype.ondatachannel=null,s.prototype._dispatchEvent=function(c,d){this._isClosed||(this.dispatchEvent(d),typeof this["on"+c]=="function"&&this["on"+c](d))},s.prototype._emitGatheringStateChange=function(){var c=new Event("icegatheringstatechange");this._dispatchEvent("icegatheringstatechange",c)},s.prototype.getConfiguration=function(){return this._config},s.prototype.getLocalStreams=function(){return this.localStreams},s.prototype.getRemoteStreams=function(){return this.remoteStreams},s.prototype._createTransceiver=function(c,d){var u=this.transceivers.length>0,l={track:null,iceGatherer:null,iceTransport:null,dtlsTransport:null,localCapabilities:null,remoteCapabilities:null,rtpSender:null,rtpReceiver:null,kind:c,mid:null,sendEncodingParameters:null,recvEncodingParameters:null,stream:null,associatedRemoteMediaStreams:[],wantReceive:!0};if(this.usingBundle&&u)l.iceTransport=this.transceivers[0].iceTransport,l.dtlsTransport=this.transceivers[0].dtlsTransport;else{var h=this._createIceAndDtlsTransports();l.iceTransport=h.iceTransport,l.dtlsTransport=h.dtlsTransport}return d||this.transceivers.push(l),l},s.prototype.addTrack=function(c,d){if(this._isClosed)throw Pe("InvalidStateError","Attempted to call addTrack on a closed peerconnection.");var u=this.transceivers.find(function(I){return I.track===c});if(u)throw Pe("InvalidAccessError","Track already exists.");for(var l,h=0;h<this.transceivers.length;h++)!this.transceivers[h].track&&this.transceivers[h].kind===c.kind&&(l=this.transceivers[h]);return l||(l=this._createTransceiver(c.kind)),this._maybeFireNegotiationNeeded(),this.localStreams.indexOf(d)===-1&&this.localStreams.push(d),l.track=c,l.stream=d,l.rtpSender=new i.RTCRtpSender(c,l.dtlsTransport),l.rtpSender},s.prototype.addStream=function(c){var d=this;if(t>=15025)c.getTracks().forEach(function(l){d.addTrack(l,c)});else{var u=c.clone();c.getTracks().forEach(function(l,h){var I=u.getTracks()[h];l.addEventListener("enabled",function(T){I.enabled=T.enabled})}),u.getTracks().forEach(function(l){d.addTrack(l,u)})}},s.prototype.removeTrack=function(c){if(this._isClosed)throw Pe("InvalidStateError","Attempted to call removeTrack on a closed peerconnection.");if(!(c instanceof i.RTCRtpSender))throw new TypeError("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.");var d=this.transceivers.find(function(h){return h.rtpSender===c});if(!d)throw Pe("InvalidAccessError","Sender was not created by this connection.");var u=d.stream;d.rtpSender.stop(),d.rtpSender=null,d.track=null,d.stream=null;var l=this.transceivers.map(function(h){return h.stream});l.indexOf(u)===-1&&this.localStreams.indexOf(u)>-1&&this.localStreams.splice(this.localStreams.indexOf(u),1),this._maybeFireNegotiationNeeded()},s.prototype.removeStream=function(c){var d=this;c.getTracks().forEach(function(u){var l=d.getSenders().find(function(h){return h.track===u});l&&d.removeTrack(l)})},s.prototype.getSenders=function(){return this.transceivers.filter(function(c){return!!c.rtpSender}).map(function(c){return c.rtpSender})},s.prototype.getReceivers=function(){return this.transceivers.filter(function(c){return!!c.rtpReceiver}).map(function(c){return c.rtpReceiver})},s.prototype._createIceGatherer=function(c,d){var u=this;if(d&&c>0)return this.transceivers[0].iceGatherer;if(this._iceGatherers.length)return this._iceGatherers.shift();var l=new i.RTCIceGatherer({iceServers:this._config.iceServers,gatherPolicy:this._config.iceTransportPolicy});return Object.defineProperty(l,"state",{value:"new",writable:!0}),this.transceivers[c].bufferedCandidateEvents=[],this.transceivers[c].bufferCandidates=function(h){var I=!h.candidate||Object.keys(h.candidate).length===0;l.state=I?"completed":"gathering",u.transceivers[c].bufferedCandidateEvents!==null&&u.transceivers[c].bufferedCandidateEvents.push(h)},l.addEventListener("localcandidate",this.transceivers[c].bufferCandidates),l},s.prototype._gather=function(c,d){var u=this,l=this.transceivers[d].iceGatherer;if(!l.onlocalcandidate){var h=this.transceivers[d].bufferedCandidateEvents;this.transceivers[d].bufferedCandidateEvents=null,l.removeEventListener("localcandidate",this.transceivers[d].bufferCandidates),l.onlocalcandidate=function(I){if(!(u.usingBundle&&d>0)){var T=new Event("icecandidate");T.candidate={sdpMid:c,sdpMLineIndex:d};var N=I.candidate,$=!N||Object.keys(N).length===0;if($)(l.state==="new"||l.state==="gathering")&&(l.state="completed");else{l.state==="new"&&(l.state="gathering"),N.component=1,N.ufrag=l.getLocalParameters().usernameFragment;var x=K.writeCandidate(N);T.candidate=Object.assign(T.candidate,K.parseCandidate(x)),T.candidate.candidate=x,T.candidate.toJSON=function(){return{candidate:T.candidate.candidate,sdpMid:T.candidate.sdpMid,sdpMLineIndex:T.candidate.sdpMLineIndex,usernameFragment:T.candidate.usernameFragment}}}var F=K.getMediaSections(u._localDescription.sdp);$?F[T.candidate.sdpMLineIndex]+=`a=end-of-candidates\r
49
+ `:F[T.candidate.sdpMLineIndex]+="a="+T.candidate.candidate+`\r
50
+ `,u._localDescription.sdp=K.getDescription(u._localDescription.sdp)+F.join("");var ge=u.transceivers.every(function(A){return A.iceGatherer&&A.iceGatherer.state==="completed"});u.iceGatheringState!=="gathering"&&(u.iceGatheringState="gathering",u._emitGatheringStateChange()),$||u._dispatchEvent("icecandidate",T),ge&&(u._dispatchEvent("icecandidate",new Event("icecandidate")),u.iceGatheringState="complete",u._emitGatheringStateChange())}},i.setTimeout(function(){h.forEach(function(I){l.onlocalcandidate(I)})},0)}},s.prototype._createIceAndDtlsTransports=function(){var c=this,d=new i.RTCIceTransport(null);d.onicestatechange=function(){c._updateIceConnectionState(),c._updateConnectionState()};var u=new i.RTCDtlsTransport(d);return u.ondtlsstatechange=function(){c._updateConnectionState()},u.onerror=function(){Object.defineProperty(u,"state",{value:"failed",writable:!0}),c._updateConnectionState()},{iceTransport:d,dtlsTransport:u}},s.prototype._disposeIceAndDtlsTransports=function(c){var d=this.transceivers[c].iceGatherer;d&&(delete d.onlocalcandidate,delete this.transceivers[c].iceGatherer);var u=this.transceivers[c].iceTransport;u&&(delete u.onicestatechange,delete this.transceivers[c].iceTransport);var l=this.transceivers[c].dtlsTransport;l&&(delete l.ondtlsstatechange,delete l.onerror,delete this.transceivers[c].dtlsTransport)},s.prototype._transceive=function(c,d,u){var l=cs(c.localCapabilities,c.remoteCapabilities);d&&c.rtpSender&&(l.encodings=c.sendEncodingParameters,l.rtcp={cname:K.localCName,compound:c.rtcpParameters.compound},c.recvEncodingParameters.length&&(l.rtcp.ssrc=c.recvEncodingParameters[0].ssrc),c.rtpSender.send(l)),u&&c.rtpReceiver&&l.codecs.length>0&&(c.kind==="video"&&c.recvEncodingParameters&&t<15019&&c.recvEncodingParameters.forEach(function(h){delete h.rtx}),c.recvEncodingParameters.length?l.encodings=c.recvEncodingParameters:l.encodings=[{}],l.rtcp={compound:c.rtcpParameters.compound},c.rtcpParameters.cname&&(l.rtcp.cname=c.rtcpParameters.cname),c.sendEncodingParameters.length&&(l.rtcp.ssrc=c.sendEncodingParameters[0].ssrc),c.rtpReceiver.receive(l))},s.prototype.setLocalDescription=function(c){var d=this;if(["offer","answer"].indexOf(c.type)===-1)return Promise.reject(Pe("TypeError",'Unsupported type "'+c.type+'"'));if(!Bd("setLocalDescription",c.type,d.signalingState)||d._isClosed)return Promise.reject(Pe("InvalidStateError","Can not set local "+c.type+" in state "+d.signalingState));var u,l;if(c.type==="offer")u=K.splitSections(c.sdp),l=u.shift(),u.forEach(function(I,T){var N=K.parseRtpParameters(I);d.transceivers[T].localCapabilities=N}),d.transceivers.forEach(function(I,T){d._gather(I.mid,T)});else if(c.type==="answer"){u=K.splitSections(d._remoteDescription.sdp),l=u.shift();var h=K.matchPrefix(l,"a=ice-lite").length>0;u.forEach(function(I,T){var N=d.transceivers[T],$=N.iceGatherer,x=N.iceTransport,F=N.dtlsTransport,ge=N.localCapabilities,A=N.remoteCapabilities,U=K.isRejected(I)&&K.matchPrefix(I,"a=bundle-only").length===0;if(!U&&!N.rejected){var y=K.getIceParameters(I,l),J=K.getDtlsParameters(I,l);h&&(J.role="server"),(!d.usingBundle||T===0)&&(d._gather(N.mid,T),x.state==="new"&&x.start($,y,h?"controlling":"controlled"),F.state==="new"&&F.start(J));var ie=cs(ge,A);d._transceive(N,ie.codecs.length>0,!1)}})}return d._localDescription={type:c.type,sdp:c.sdp},c.type==="offer"?d._updateSignalingState("have-local-offer"):d._updateSignalingState("stable"),Promise.resolve()},s.prototype.setRemoteDescription=function(c){var d=this;if(["offer","answer"].indexOf(c.type)===-1)return Promise.reject(Pe("TypeError",'Unsupported type "'+c.type+'"'));if(!Bd("setRemoteDescription",c.type,d.signalingState)||d._isClosed)return Promise.reject(Pe("InvalidStateError","Can not set remote "+c.type+" in state "+d.signalingState));var u={};d.remoteStreams.forEach(function(x){u[x.id]=x});var l=[],h=K.splitSections(c.sdp),I=h.shift(),T=K.matchPrefix(I,"a=ice-lite").length>0,N=K.matchPrefix(I,"a=group:BUNDLE ").length>0;d.usingBundle=N;var $=K.matchPrefix(I,"a=ice-options:")[0];return $?d.canTrickleIceCandidates=$.substr(14).split(" ").indexOf("trickle")>=0:d.canTrickleIceCandidates=!1,h.forEach(function(x,F){var ge=K.splitLines(x),A=K.getKind(x),U=K.isRejected(x)&&K.matchPrefix(x,"a=bundle-only").length===0,y=ge[0].substr(2).split(" ")[2],J=K.getDirection(x,I),ie=K.parseMsid(x),Re=K.getMid(x)||K.generateIdentifier();if(U||A==="application"&&(y==="DTLS/SCTP"||y==="UDP/DTLS/SCTP")){d.transceivers[F]={mid:Re,kind:A,protocol:y,rejected:!0};return}!U&&d.transceivers[F]&&d.transceivers[F].rejected&&(d.transceivers[F]=d._createTransceiver(A,!0));var G,k,L,R,g,Oo,Po,Kr,Ut,fd=K.parseRtpParameters(x),Ed,Mo;U||(Ed=K.getIceParameters(x,I),Mo=K.getDtlsParameters(x,I),Mo.role="client"),Po=K.parseRtpEncodingParameters(x);var Td=K.parseRtcpParameters(x),Sd=K.matchPrefix(x,"a=end-of-candidates",I).length>0,rr=K.matchPrefix(x,"a=candidate:").map(function(Ge){return K.parseCandidate(Ge)}).filter(function(Ge){return Ge.component===1});if((c.type==="offer"||c.type==="answer")&&!U&&N&&F>0&&d.transceivers[F]&&(d._disposeIceAndDtlsTransports(F),d.transceivers[F].iceGatherer=d.transceivers[0].iceGatherer,d.transceivers[F].iceTransport=d.transceivers[0].iceTransport,d.transceivers[F].dtlsTransport=d.transceivers[0].dtlsTransport,d.transceivers[F].rtpSender&&d.transceivers[F].rtpSender.setTransport(d.transceivers[0].dtlsTransport),d.transceivers[F].rtpReceiver&&d.transceivers[F].rtpReceiver.setTransport(d.transceivers[0].dtlsTransport)),c.type==="offer"&&!U){G=d.transceivers[F]||d._createTransceiver(A),G.mid=Re,G.iceGatherer||(G.iceGatherer=d._createIceGatherer(F,N)),rr.length&&G.iceTransport.state==="new"&&(Sd&&(!N||F===0)?G.iceTransport.setRemoteCandidates(rr):rr.forEach(function(Ge){Wo(G.iceTransport,Ge)})),Kr=i.RTCRtpReceiver.getCapabilities(A),t<15019&&(Kr.codecs=Kr.codecs.filter(function(Ge){return Ge.name!=="rtx"})),Oo=G.sendEncodingParameters||[{ssrc:(2*F+2)*1001}];var Lo=!1;if(J==="sendrecv"||J==="sendonly"){if(Lo=!G.rtpReceiver,g=G.rtpReceiver||new i.RTCRtpReceiver(G.dtlsTransport,A),Lo){var W;Ut=g.track,ie&&ie.stream==="-"||(ie?(u[ie.stream]||(u[ie.stream]=new i.MediaStream,Object.defineProperty(u[ie.stream],"id",{get:function(){return ie.stream}})),Object.defineProperty(Ut,"id",{get:function(){return ie.track}}),W=u[ie.stream]):(u.default||(u.default=new i.MediaStream),W=u.default)),W&&(e(Ut,W),G.associatedRemoteMediaStreams.push(W)),l.push([Ut,g,W])}}else G.rtpReceiver&&G.rtpReceiver.track&&(G.associatedRemoteMediaStreams.forEach(function(Ge){var gd=Ge.getTracks().find(function(Ep){return Ep.id===G.rtpReceiver.track.id});gd&&r(gd,Ge)}),G.associatedRemoteMediaStreams=[]);G.localCapabilities=Kr,G.remoteCapabilities=fd,G.rtpReceiver=g,G.rtcpParameters=Td,G.sendEncodingParameters=Oo,G.recvEncodingParameters=Po,d._transceive(d.transceivers[F],!1,Lo)}else if(c.type==="answer"&&!U){G=d.transceivers[F],k=G.iceGatherer,L=G.iceTransport,R=G.dtlsTransport,g=G.rtpReceiver,Oo=G.sendEncodingParameters,Kr=G.localCapabilities,d.transceivers[F].recvEncodingParameters=Po,d.transceivers[F].remoteCapabilities=fd,d.transceivers[F].rtcpParameters=Td,rr.length&&L.state==="new"&&((T||Sd)&&(!N||F===0)?L.setRemoteCandidates(rr):rr.forEach(function(Ge){Wo(G.iceTransport,Ge)})),(!N||F===0)&&(L.state==="new"&&L.start(k,Ed,"controlling"),R.state==="new"&&R.start(Mo));var _p=cs(G.localCapabilities,G.remoteCapabilities),fp=_p.codecs.filter(function(Ge){return Ge.name.toLowerCase()==="rtx"}).length;!fp&&G.sendEncodingParameters[0].rtx&&delete G.sendEncodingParameters[0].rtx,d._transceive(G,J==="sendrecv"||J==="recvonly",J==="sendrecv"||J==="sendonly"),g&&(J==="sendrecv"||J==="sendonly")?(Ut=g.track,ie?(u[ie.stream]||(u[ie.stream]=new i.MediaStream),e(Ut,u[ie.stream]),l.push([Ut,g,u[ie.stream]])):(u.default||(u.default=new i.MediaStream),e(Ut,u.default),l.push([Ut,g,u.default]))):delete G.rtpReceiver}}),d._dtlsRole===void 0&&(d._dtlsRole=c.type==="offer"?"active":"passive"),d._remoteDescription={type:c.type,sdp:c.sdp},c.type==="offer"?d._updateSignalingState("have-remote-offer"):d._updateSignalingState("stable"),Object.keys(u).forEach(function(x){var F=u[x];if(F.getTracks().length){if(d.remoteStreams.indexOf(F)===-1){d.remoteStreams.push(F);var ge=new Event("addstream");ge.stream=F,i.setTimeout(function(){d._dispatchEvent("addstream",ge)})}l.forEach(function(A){var U=A[0],y=A[1];F.id===A[2].id&&n(d,U,y,[F])})}}),l.forEach(function(x){x[2]||n(d,x[0],x[1],[])}),i.setTimeout(function(){!(d&&d.transceivers)||d.transceivers.forEach(function(x){x.iceTransport&&x.iceTransport.state==="new"&&x.iceTransport.getRemoteCandidates().length>0&&(console.warn("Timeout for addRemoteCandidate. Consider sending an end-of-candidates notification"),x.iceTransport.addRemoteCandidate({}))})},4e3),Promise.resolve()},s.prototype.close=function(){this.transceivers.forEach(function(c){c.iceTransport&&c.iceTransport.stop(),c.dtlsTransport&&c.dtlsTransport.stop(),c.rtpSender&&c.rtpSender.stop(),c.rtpReceiver&&c.rtpReceiver.stop()}),this._isClosed=!0,this._updateSignalingState("closed")},s.prototype._updateSignalingState=function(c){this.signalingState=c;var d=new Event("signalingstatechange");this._dispatchEvent("signalingstatechange",d)},s.prototype._maybeFireNegotiationNeeded=function(){var c=this;this.signalingState!=="stable"||this.needNegotiation===!0||(this.needNegotiation=!0,i.setTimeout(function(){if(c.needNegotiation){c.needNegotiation=!1;var d=new Event("negotiationneeded");c._dispatchEvent("negotiationneeded",d)}},0))},s.prototype._updateIceConnectionState=function(){var c,d={new:0,closed:0,checking:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach(function(l){l.iceTransport&&!l.rejected&&d[l.iceTransport.state]++}),c="new",d.failed>0?c="failed":d.checking>0?c="checking":d.disconnected>0?c="disconnected":d.new>0?c="new":d.connected>0?c="connected":d.completed>0&&(c="completed"),c!==this.iceConnectionState){this.iceConnectionState=c;var u=new Event("iceconnectionstatechange");this._dispatchEvent("iceconnectionstatechange",u)}},s.prototype._updateConnectionState=function(){var c,d={new:0,closed:0,connecting:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach(function(l){l.iceTransport&&l.dtlsTransport&&!l.rejected&&(d[l.iceTransport.state]++,d[l.dtlsTransport.state]++)}),d.connected+=d.completed,c="new",d.failed>0?c="failed":d.connecting>0?c="connecting":d.disconnected>0?c="disconnected":d.new>0?c="new":d.connected>0&&(c="connected"),c!==this.connectionState){this.connectionState=c;var u=new Event("connectionstatechange");this._dispatchEvent("connectionstatechange",u)}},s.prototype.createOffer=function(){var c=this;if(c._isClosed)return Promise.reject(Pe("InvalidStateError","Can not call createOffer after close"));var d=c.transceivers.filter(function(T){return T.kind==="audio"}).length,u=c.transceivers.filter(function(T){return T.kind==="video"}).length,l=arguments[0];if(l){if(l.mandatory||l.optional)throw new TypeError("Legacy mandatory/optional constraints not supported.");l.offerToReceiveAudio!==void 0&&(l.offerToReceiveAudio===!0?d=1:l.offerToReceiveAudio===!1?d=0:d=l.offerToReceiveAudio),l.offerToReceiveVideo!==void 0&&(l.offerToReceiveVideo===!0?u=1:l.offerToReceiveVideo===!1?u=0:u=l.offerToReceiveVideo)}for(c.transceivers.forEach(function(T){T.kind==="audio"?(d--,d<0&&(T.wantReceive=!1)):T.kind==="video"&&(u--,u<0&&(T.wantReceive=!1))});d>0||u>0;)d>0&&(c._createTransceiver("audio"),d--),u>0&&(c._createTransceiver("video"),u--);var h=K.writeSessionBoilerplate(c._sdpSessionId,c._sdpSessionVersion++);c.transceivers.forEach(function(T,N){var $=T.track,x=T.kind,F=T.mid||K.generateIdentifier();T.mid=F,T.iceGatherer||(T.iceGatherer=c._createIceGatherer(N,c.usingBundle));var ge=i.RTCRtpSender.getCapabilities(x);t<15019&&(ge.codecs=ge.codecs.filter(function(U){return U.name!=="rtx"})),ge.codecs.forEach(function(U){U.name==="H264"&&U.parameters["level-asymmetry-allowed"]===void 0&&(U.parameters["level-asymmetry-allowed"]="1"),T.remoteCapabilities&&T.remoteCapabilities.codecs&&T.remoteCapabilities.codecs.forEach(function(y){U.name.toLowerCase()===y.name.toLowerCase()&&U.clockRate===y.clockRate&&(U.preferredPayloadType=y.payloadType)})}),ge.headerExtensions.forEach(function(U){var y=T.remoteCapabilities&&T.remoteCapabilities.headerExtensions||[];y.forEach(function(J){U.uri===J.uri&&(U.id=J.id)})});var A=T.sendEncodingParameters||[{ssrc:(2*N+1)*1001}];$&&t>=15019&&x==="video"&&!A[0].rtx&&(A[0].rtx={ssrc:A[0].ssrc+1}),T.wantReceive&&(T.rtpReceiver=new i.RTCRtpReceiver(T.dtlsTransport,x)),T.localCapabilities=ge,T.sendEncodingParameters=A}),c._config.bundlePolicy!=="max-compat"&&(h+="a=group:BUNDLE "+c.transceivers.map(function(T){return T.mid}).join(" ")+`\r
51
51
  `),h+=`a=ice-options:trickle\r
52
- `,c.transceivers.forEach(function(T,N){h+=hd(T,T.localCapabilities,"offer",T.stream,c._dtlsRole),h+=`a=rtcp-rsize\r
53
- `,T.iceGatherer&&c.iceGatheringState!=="new"&&(N===0||!c.usingBundle)&&(T.iceGatherer.getLocalCandidates().forEach(function(H){H.component=1,h+="a="+j.writeCandidate(H)+`\r
52
+ `,c.transceivers.forEach(function(T,N){h+=wd(T,T.localCapabilities,"offer",T.stream,c._dtlsRole),h+=`a=rtcp-rsize\r
53
+ `,T.iceGatherer&&c.iceGatheringState!=="new"&&(N===0||!c.usingBundle)&&(T.iceGatherer.getLocalCandidates().forEach(function($){$.component=1,h+="a="+K.writeCandidate($)+`\r
54
54
  `}),T.iceGatherer.state==="completed"&&(h+=`a=end-of-candidates\r
55
- `))});var I=new i.RTCSessionDescription({type:"offer",sdp:h});return Promise.resolve(I)},s.prototype.createAnswer=function(){var c=this;if(c._isClosed)return Promise.reject(Pe("InvalidStateError","Can not call createAnswer after close"));if(!(c.signalingState==="have-remote-offer"||c.signalingState==="have-local-pranswer"))return Promise.reject(Pe("InvalidStateError","Can not call createAnswer in signalingState "+c.signalingState));var d=j.writeSessionBoilerplate(c._sdpSessionId,c._sdpSessionVersion++);c.usingBundle&&(d+="a=group:BUNDLE "+c.transceivers.map(function(h){return h.mid}).join(" ")+`\r
55
+ `))});var I=new i.RTCSessionDescription({type:"offer",sdp:h});return Promise.resolve(I)},s.prototype.createAnswer=function(){var c=this;if(c._isClosed)return Promise.reject(Pe("InvalidStateError","Can not call createAnswer after close"));if(!(c.signalingState==="have-remote-offer"||c.signalingState==="have-local-pranswer"))return Promise.reject(Pe("InvalidStateError","Can not call createAnswer in signalingState "+c.signalingState));var d=K.writeSessionBoilerplate(c._sdpSessionId,c._sdpSessionVersion++);c.usingBundle&&(d+="a=group:BUNDLE "+c.transceivers.map(function(h){return h.mid}).join(" ")+`\r
56
56
  `),d+=`a=ice-options:trickle\r
57
- `;var u=j.getMediaSections(c._remoteDescription.sdp).length;c.transceivers.forEach(function(h,I){if(!(I+1>u)){if(h.rejected){h.kind==="application"?h.protocol==="DTLS/SCTP"?d+=`m=application 0 DTLS/SCTP 5000\r
57
+ `;var u=K.getMediaSections(c._remoteDescription.sdp).length;c.transceivers.forEach(function(h,I){if(!(I+1>u)){if(h.rejected){h.kind==="application"?h.protocol==="DTLS/SCTP"?d+=`m=application 0 DTLS/SCTP 5000\r
58
58
  `:d+="m=application 0 "+h.protocol+` webrtc-datachannel\r
59
59
  `:h.kind==="audio"?d+=`m=audio 0 UDP/TLS/RTP/SAVPF 0\r
60
60
  a=rtpmap:0 PCMU/8000\r
@@ -63,41 +63,40 @@ a=rtpmap:120 VP8/90000\r
63
63
  `),d+=`c=IN IP4 0.0.0.0\r
64
64
  a=inactive\r
65
65
  a=mid:`+h.mid+`\r
66
- `;return}if(h.stream){var T;h.kind==="audio"?T=h.stream.getAudioTracks()[0]:h.kind==="video"&&(T=h.stream.getVideoTracks()[0]),T&&t>=15019&&h.kind==="video"&&!h.sendEncodingParameters[0].rtx&&(h.sendEncodingParameters[0].rtx={ssrc:h.sendEncodingParameters[0].ssrc+1})}var N=Un(h.localCapabilities,h.remoteCapabilities),H=N.codecs.filter(function(U){return U.name.toLowerCase()==="rtx"}).length;!H&&h.sendEncodingParameters[0].rtx&&delete h.sendEncodingParameters[0].rtx,d+=hd(h,N,"answer",h.stream,c._dtlsRole),h.rtcpParameters&&h.rtcpParameters.reducedSize&&(d+=`a=rtcp-rsize\r
67
- `)}});var l=new i.RTCSessionDescription({type:"answer",sdp:d});return Promise.resolve(l)},s.prototype.addIceCandidate=function(c){var d=this,u;return c&&!(c.sdpMLineIndex!==void 0||c.sdpMid)?Promise.reject(new TypeError("sdpMLineIndex or sdpMid required")):new Promise(function(l,h){if(d._remoteDescription)if(!c||c.candidate==="")for(var I=0;I<d.transceivers.length&&!(!d.transceivers[I].rejected&&(d.transceivers[I].iceTransport.addRemoteCandidate({}),u=j.getMediaSections(d._remoteDescription.sdp),u[I]+=`a=end-of-candidates\r
68
- `,d._remoteDescription.sdp=j.getDescription(d._remoteDescription.sdp)+u.join(""),d.usingBundle));I++);else{var T=c.sdpMLineIndex;if(c.sdpMid){for(var N=0;N<d.transceivers.length;N++)if(d.transceivers[N].mid===c.sdpMid){T=N;break}}var H=d.transceivers[T];if(H){if(H.rejected)return l();var U=Object.keys(c.candidate).length>0?j.parseCandidate(c.candidate):{};if(U.protocol==="tcp"&&(U.port===0||U.port===9)||U.component&&U.component!==1)return l();if((T===0||T>0&&H.iceTransport!==d.transceivers[0].iceTransport)&&!fo(H.iceTransport,U))return h(Pe("OperationError","Can not add ICE candidate"));var G=c.candidate.trim();G.indexOf("a=")===0&&(G=G.substr(2)),u=j.getMediaSections(d._remoteDescription.sdp),u[T]+="a="+(U.type?G:"end-of-candidates")+`\r
69
- `,d._remoteDescription.sdp=j.getDescription(d._remoteDescription.sdp)+u.join("")}else return h(Pe("OperationError","Can not add ICE candidate"))}else return h(Pe("InvalidStateError","Can not add ICE candidate without a remote description"));l()})},s.prototype.getStats=function(c){if(c&&c instanceof i.MediaStreamTrack){var d=null;if(this.transceivers.forEach(function(l){l.rtpSender&&l.rtpSender.track===c?d=l.rtpSender:l.rtpReceiver&&l.rtpReceiver.track===c&&(d=l.rtpReceiver)}),!d)throw Pe("InvalidAccessError","Invalid selector.");return d.getStats()}var u=[];return this.transceivers.forEach(function(l){["rtpSender","rtpReceiver","iceGatherer","iceTransport","dtlsTransport"].forEach(function(h){l[h]&&u.push(l[h].getStats())})}),Promise.all(u).then(function(l){var h=new Map;return l.forEach(function(I){I.forEach(function(T){h.set(T.id,T)})}),h})};var o=["RTCRtpSender","RTCRtpReceiver","RTCIceGatherer","RTCIceTransport","RTCDtlsTransport"];o.forEach(function(c){var d=i[c];if(d&&d.prototype&&d.prototype.getStats){var u=d.prototype.getStats;d.prototype.getStats=function(){return u.apply(this).then(function(l){var h=new Map;return Object.keys(l).forEach(function(I){l[I].type=Kp(l[I]),h.set(I,l[I])}),h})}}});var a=["createOffer","createAnswer"];return a.forEach(function(c){var d=s.prototype[c];s.prototype[c]=function(){var u=arguments;return typeof u[0]=="function"||typeof u[1]=="function"?d.apply(this,[arguments[2]]).then(function(l){typeof u[0]=="function"&&u[0].apply(null,[l])},function(l){typeof u[1]=="function"&&u[1].apply(null,[l])}):d.apply(this,arguments)}}),a=["setLocalDescription","setRemoteDescription","addIceCandidate"],a.forEach(function(c){var d=s.prototype[c];s.prototype[c]=function(){var u=arguments;return typeof u[1]=="function"||typeof u[2]=="function"?d.apply(this,arguments).then(function(){typeof u[1]=="function"&&u[1].apply(null)},function(l){typeof u[2]=="function"&&u[2].apply(null,[l])}):d.apply(this,arguments)}}),["getStats"].forEach(function(c){var d=s.prototype[c];s.prototype[c]=function(){var u=arguments;return typeof u[1]=="function"?d.apply(this,arguments).then(function(){typeof u[1]=="function"&&u[1].apply(null)}):d.apply(this,arguments)}}),s}});var Ed=_e(qt=>{"use strict";var Nf=_(f());Object.defineProperty(qt,"__esModule",{value:!0});qt.shimGetDisplayMedia=qt.shimGetUserMedia=void 0;var Jp=ud();Object.defineProperty(qt,"shimGetUserMedia",{enumerable:!0,get:function(){return Jp.shimGetUserMedia}});var Yp=ld();Object.defineProperty(qt,"shimGetDisplayMedia",{enumerable:!0,get:function(){return Yp.shimGetDisplayMedia}});qt.shimPeerConnection=ih;qt.shimReplaceTrack=rh;var Xp=ft(),zp=th(Xp),qp=pd(),Qp=fd(),Zp=eh(Qp);function eh(i){return i&&i.__esModule?i:{default:i}}function th(i){if(i&&i.__esModule)return i;var t={};if(i!=null)for(var e in i)Object.prototype.hasOwnProperty.call(i,e)&&(t[e]=i[e]);return t.default=i,t}function ih(i,t){if(i.RTCIceGatherer&&(i.RTCIceCandidate||(i.RTCIceCandidate=function(s){return s}),i.RTCSessionDescription||(i.RTCSessionDescription=function(s){return s}),t.version<15025)){var e=Object.getOwnPropertyDescriptor(i.MediaStreamTrack.prototype,"enabled");Object.defineProperty(i.MediaStreamTrack.prototype,"enabled",{set:function(s){e.set.call(this,s);var o=new Event("enabled");o.enabled=s,this.dispatchEvent(o)}})}i.RTCRtpSender&&!("dtmf"in i.RTCRtpSender.prototype)&&Object.defineProperty(i.RTCRtpSender.prototype,"dtmf",{get:function(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=new i.RTCDtmfSender(this):this.track.kind==="video"&&(this._dtmf=null)),this._dtmf}}),i.RTCDtmfSender&&!i.RTCDTMFSender&&(i.RTCDTMFSender=i.RTCDtmfSender);var r=(0,Zp.default)(i,t.version);i.RTCPeerConnection=function(s){return s&&s.iceServers&&(s.iceServers=(0,qp.filterIceServers)(s.iceServers,t.version),zp.log("ICE servers after filtering:",s.iceServers)),new r(s)},i.RTCPeerConnection.prototype=r.prototype}function rh(i){i.RTCRtpSender&&!("replaceTrack"in i.RTCRtpSender.prototype)&&(i.RTCRtpSender.prototype.replaceTrack=i.RTCRtpSender.prototype.setTrack)}});var Td=_e(To=>{"use strict";var Df=_(f());Object.defineProperty(To,"__esModule",{value:!0});var Eo=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(i){return typeof i}:function(i){return i&&typeof Symbol=="function"&&i.constructor===Symbol&&i!==Symbol.prototype?"symbol":typeof i};To.shimGetUserMedia=ah;var nh=ft(),sh=oh(nh);function oh(i){if(i&&i.__esModule)return i;var t={};if(i!=null)for(var e in i)Object.prototype.hasOwnProperty.call(i,e)&&(t[e]=i[e]);return t.default=i,t}function ah(i,t){var e=i&&i.navigator,r=i&&i.MediaStreamTrack;if(e.getUserMedia=function(c,d,u){sh.deprecated("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),e.mediaDevices.getUserMedia(c).then(d,u)},!(t.version>55&&"autoGainControl"in e.mediaDevices.getSupportedConstraints())){var n=function(d,u,l){u in d&&!(l in d)&&(d[l]=d[u],delete d[u])},s=e.mediaDevices.getUserMedia.bind(e.mediaDevices);if(e.mediaDevices.getUserMedia=function(c){return(typeof c=="undefined"?"undefined":Eo(c))==="object"&&Eo(c.audio)==="object"&&(c=JSON.parse(JSON.stringify(c)),n(c.audio,"autoGainControl","mozAutoGainControl"),n(c.audio,"noiseSuppression","mozNoiseSuppression")),s(c)},r&&r.prototype.getSettings){var o=r.prototype.getSettings;r.prototype.getSettings=function(){var c=o.apply(this,arguments);return n(c,"mozAutoGainControl","autoGainControl"),n(c,"mozNoiseSuppression","noiseSuppression"),c}}if(r&&r.prototype.applyConstraints){var a=r.prototype.applyConstraints;r.prototype.applyConstraints=function(c){return this.kind==="audio"&&(typeof c=="undefined"?"undefined":Eo(c))==="object"&&(c=JSON.parse(JSON.stringify(c)),n(c,"autoGainControl","mozAutoGainControl"),n(c,"noiseSuppression","mozNoiseSuppression")),a.apply(this,[c])}}}}});var Sd=_e(So=>{"use strict";var Pf=_(f());Object.defineProperty(So,"__esModule",{value:!0});So.shimGetDisplayMedia=ch;function ch(i,t){i.navigator.mediaDevices&&"getDisplayMedia"in i.navigator.mediaDevices||!i.navigator.mediaDevices||(i.navigator.mediaDevices.getDisplayMedia=function(r){if(!(r&&r.video)){var n=new DOMException("getDisplayMedia without video constraints is undefined");return n.name="NotFoundError",n.code=8,Promise.reject(n)}return r.video===!0?r.video={mediaSource:t}:r.video.mediaSource=t,i.navigator.mediaDevices.getUserMedia(r)})}});var Id=_e(Me=>{"use strict";var Lf=_(f());Object.defineProperty(Me,"__esModule",{value:!0});Me.shimGetDisplayMedia=Me.shimGetUserMedia=void 0;var Qt=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(i){return typeof i}:function(i){return i&&typeof Symbol=="function"&&i.constructor===Symbol&&i!==Symbol.prototype?"symbol":typeof i},dh=Td();Object.defineProperty(Me,"shimGetUserMedia",{enumerable:!0,get:function(){return dh.shimGetUserMedia}});var uh=Sd();Object.defineProperty(Me,"shimGetDisplayMedia",{enumerable:!0,get:function(){return uh.shimGetDisplayMedia}});Me.shimOnTrack=mh;Me.shimPeerConnection=_h;Me.shimSenderGetStats=fh;Me.shimReceiverGetStats=Eh;Me.shimRemoveStream=Th;Me.shimRTCDataChannel=Sh;Me.shimAddTransceiver=gh;Me.shimGetParameters=Ih;Me.shimCreateOffer=Rh;Me.shimCreateAnswer=Ah;var lh=ft(),gd=ph(lh);function ph(i){if(i&&i.__esModule)return i;var t={};if(i!=null)for(var e in i)Object.prototype.hasOwnProperty.call(i,e)&&(t[e]=i[e]);return t.default=i,t}function hh(i,t,e){return t in i?Object.defineProperty(i,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):i[t]=e,i}function mh(i){(typeof i=="undefined"?"undefined":Qt(i))==="object"&&i.RTCTrackEvent&&"receiver"in i.RTCTrackEvent.prototype&&!("transceiver"in i.RTCTrackEvent.prototype)&&Object.defineProperty(i.RTCTrackEvent.prototype,"transceiver",{get:function(){return{receiver:this.receiver}}})}function _h(i,t){if(!((typeof i=="undefined"?"undefined":Qt(i))!=="object"||!(i.RTCPeerConnection||i.mozRTCPeerConnection))){!i.RTCPeerConnection&&i.mozRTCPeerConnection&&(i.RTCPeerConnection=i.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(n){var s=i.RTCPeerConnection.prototype[n],o=hh({},n,function(){return arguments[0]=new(n==="addIceCandidate"?i.RTCIceCandidate:i.RTCSessionDescription)(arguments[0]),s.apply(this,arguments)});i.RTCPeerConnection.prototype[n]=o[n]});var e={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},r=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){var s=Array.prototype.slice.call(arguments),o=s[0],a=s[1],c=s[2];return r.apply(this,[o||null]).then(function(d){if(t.version<53&&!a)try{d.forEach(function(u){u.type=e[u.type]||u.type})}catch(u){if(u.name!=="TypeError")throw u;d.forEach(function(l,h){d.set(h,Object.assign({},l,{type:e[l.type]||l.type}))})}return d}).then(a,c)}}}function fh(i){if(!!((typeof i=="undefined"?"undefined":Qt(i))==="object"&&i.RTCPeerConnection&&i.RTCRtpSender)&&!(i.RTCRtpSender&&"getStats"in i.RTCRtpSender.prototype)){var t=i.RTCPeerConnection.prototype.getSenders;t&&(i.RTCPeerConnection.prototype.getSenders=function(){var n=this,s=t.apply(this,[]);return s.forEach(function(o){return o._pc=n}),s});var e=i.RTCPeerConnection.prototype.addTrack;e&&(i.RTCPeerConnection.prototype.addTrack=function(){var n=e.apply(this,arguments);return n._pc=this,n}),i.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}}function Eh(i){if(!!((typeof i=="undefined"?"undefined":Qt(i))==="object"&&i.RTCPeerConnection&&i.RTCRtpSender)&&!(i.RTCRtpSender&&"getStats"in i.RTCRtpReceiver.prototype)){var t=i.RTCPeerConnection.prototype.getReceivers;t&&(i.RTCPeerConnection.prototype.getReceivers=function(){var r=this,n=t.apply(this,[]);return n.forEach(function(s){return s._pc=r}),n}),gd.wrapPeerConnectionEvent(i,"track",function(e){return e.receiver._pc=e.srcElement,e}),i.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}}function Th(i){!i.RTCPeerConnection||"removeStream"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.removeStream=function(e){var r=this;gd.deprecated("removeStream","removeTrack"),this.getSenders().forEach(function(n){n.track&&e.getTracks().includes(n.track)&&r.removeTrack(n)})})}function Sh(i){i.DataChannel&&!i.RTCDataChannel&&(i.RTCDataChannel=i.DataChannel)}function gh(i){if(!!((typeof i=="undefined"?"undefined":Qt(i))==="object"&&i.RTCPeerConnection)){var t=i.RTCPeerConnection.prototype.addTransceiver;t&&(i.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];var r=arguments[1],n=r&&"sendEncodings"in r;n&&r.sendEncodings.forEach(function(c){if("rid"in c){var d=/^[a-z0-9]{0,16}$/i;if(!d.test(c.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in c&&!(parseFloat(c.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in c&&!(parseFloat(c.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});var s=t.apply(this,arguments);if(n){var o=s.sender,a=o.getParameters();(!("encodings"in a)||a.encodings.length===1&&Object.keys(a.encodings[0]).length===0)&&(a.encodings=r.sendEncodings,o.sendEncodings=r.sendEncodings,this.setParametersPromises.push(o.setParameters(a).then(function(){delete o.sendEncodings}).catch(function(){delete o.sendEncodings})))}return s})}}function Ih(i){if(!!((typeof i=="undefined"?"undefined":Qt(i))==="object"&&i.RTCRtpSender)){var t=i.RTCRtpSender.prototype.getParameters;t&&(i.RTCRtpSender.prototype.getParameters=function(){var r=t.apply(this,arguments);return"encodings"in r||(r.encodings=[].concat(this.sendEncodings||[{}])),r})}}function Rh(i){if(!!((typeof i=="undefined"?"undefined":Qt(i))==="object"&&i.RTCPeerConnection)){var t=i.RTCPeerConnection.prototype.createOffer;i.RTCPeerConnection.prototype.createOffer=function(){var r=this,n=arguments;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(function(){return t.apply(r,n)}).finally(function(){r.setParametersPromises=[]}):t.apply(this,arguments)}}}function Ah(i){if(!!((typeof i=="undefined"?"undefined":Qt(i))==="object"&&i.RTCPeerConnection)){var t=i.RTCPeerConnection.prototype.createAnswer;i.RTCPeerConnection.prototype.createAnswer=function(){var r=this,n=arguments;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(function(){return t.apply(r,n)}).finally(function(){r.setParametersPromises=[]}):t.apply(this,arguments)}}}});var Cd=_e(dt=>{"use strict";var xf=_(f());Object.defineProperty(dt,"__esModule",{value:!0});var Nr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(i){return typeof i}:function(i){return i&&typeof Symbol=="function"&&i.constructor===Symbol&&i!==Symbol.prototype?"symbol":typeof i};dt.shimLocalStreamsAPI=vh;dt.shimRemoteStreamsAPI=Nh;dt.shimCallbacksAPI=bh;dt.shimGetUserMedia=Dh;dt.shimConstraints=Ad;dt.shimRTCIceServerUrls=Oh;dt.shimTrackEventTransceiver=Ph;dt.shimCreateOfferLegacy=Mh;dt.shimAudioContext=Lh;var Ch=ft(),Rd=yh(Ch);function yh(i){if(i&&i.__esModule)return i;var t={};if(i!=null)for(var e in i)Object.prototype.hasOwnProperty.call(i,e)&&(t[e]=i[e]);return t.default=i,t}function vh(i){if(!((typeof i=="undefined"?"undefined":Nr(i))!=="object"||!i.RTCPeerConnection)){if("getLocalStreams"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in i.RTCPeerConnection.prototype)){var t=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addStream=function(r){var n=this;this._localStreams||(this._localStreams=[]),this._localStreams.includes(r)||this._localStreams.push(r),r.getAudioTracks().forEach(function(s){return t.call(n,s,r)}),r.getVideoTracks().forEach(function(s){return t.call(n,s,r)})},i.RTCPeerConnection.prototype.addTrack=function(r){for(var n=this,s=arguments.length,o=Array(s>1?s-1:0),a=1;a<s;a++)o[a-1]=arguments[a];return o&&o.forEach(function(c){n._localStreams?n._localStreams.includes(c)||n._localStreams.push(c):n._localStreams=[c]}),t.apply(this,arguments)}}"removeStream"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.removeStream=function(r){var n=this;this._localStreams||(this._localStreams=[]);var s=this._localStreams.indexOf(r);if(s!==-1){this._localStreams.splice(s,1);var o=r.getTracks();this.getSenders().forEach(function(a){o.includes(a.track)&&n.removeTrack(a)})}})}}function Nh(i){if(!((typeof i=="undefined"?"undefined":Nr(i))!=="object"||!i.RTCPeerConnection)&&("getRemoteStreams"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in i.RTCPeerConnection.prototype))){Object.defineProperty(i.RTCPeerConnection.prototype,"onaddstream",{get:function(){return this._onaddstream},set:function(r){var n=this;this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=r),this.addEventListener("track",this._onaddstreampoly=function(s){s.streams.forEach(function(o){if(n._remoteStreams||(n._remoteStreams=[]),!n._remoteStreams.includes(o)){n._remoteStreams.push(o);var a=new Event("addstream");a.stream=o,n.dispatchEvent(a)}})})}});var t=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){var r=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(n){n.streams.forEach(function(s){if(r._remoteStreams||(r._remoteStreams=[]),!(r._remoteStreams.indexOf(s)>=0)){r._remoteStreams.push(s);var o=new Event("addstream");o.stream=s,r.dispatchEvent(o)}})}),t.apply(r,arguments)}}}function bh(i){if(!((typeof i=="undefined"?"undefined":Nr(i))!=="object"||!i.RTCPeerConnection)){var t=i.RTCPeerConnection.prototype,e=t.createOffer,r=t.createAnswer,n=t.setLocalDescription,s=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(d,u){var l=arguments.length>=2?arguments[2]:arguments[0],h=e.apply(this,[l]);return u?(h.then(d,u),Promise.resolve()):h},t.createAnswer=function(d,u){var l=arguments.length>=2?arguments[2]:arguments[0],h=r.apply(this,[l]);return u?(h.then(d,u),Promise.resolve()):h};var a=function(d,u,l){var h=n.apply(this,[d]);return l?(h.then(u,l),Promise.resolve()):h};t.setLocalDescription=a,a=function(d,u,l){var h=s.apply(this,[d]);return l?(h.then(u,l),Promise.resolve()):h},t.setRemoteDescription=a,a=function(d,u,l){var h=o.apply(this,[d]);return l?(h.then(u,l),Promise.resolve()):h},t.addIceCandidate=a}}function Dh(i){var t=i&&i.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){var e=t.mediaDevices,r=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=function(n){return r(Ad(n))}}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(s,o,a){t.mediaDevices.getUserMedia(s).then(o,a)}.bind(t))}function Ad(i){return i&&i.video!==void 0?Object.assign({},i,{video:Rd.compactObject(i.video)}):i}function Oh(i){if(!!i.RTCPeerConnection){var t=i.RTCPeerConnection;i.RTCPeerConnection=function(r,n){if(r&&r.iceServers){for(var s=[],o=0;o<r.iceServers.length;o++){var a=r.iceServers[o];!a.hasOwnProperty("urls")&&a.hasOwnProperty("url")?(Rd.deprecated("RTCIceServer.url","RTCIceServer.urls"),a=JSON.parse(JSON.stringify(a)),a.urls=a.url,delete a.url,s.push(a)):s.push(r.iceServers[o])}r.iceServers=s}return new t(r,n)},i.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(i.RTCPeerConnection,"generateCertificate",{get:function(){return t.generateCertificate}})}}function Ph(i){(typeof i=="undefined"?"undefined":Nr(i))==="object"&&i.RTCTrackEvent&&"receiver"in i.RTCTrackEvent.prototype&&!("transceiver"in i.RTCTrackEvent.prototype)&&Object.defineProperty(i.RTCTrackEvent.prototype,"transceiver",{get:function(){return{receiver:this.receiver}}})}function Mh(i){var t=i.RTCPeerConnection.prototype.createOffer;i.RTCPeerConnection.prototype.createOffer=function(r){if(r){typeof r.offerToReceiveAudio!="undefined"&&(r.offerToReceiveAudio=!!r.offerToReceiveAudio);var n=this.getTransceivers().find(function(o){return o.receiver.track.kind==="audio"});r.offerToReceiveAudio===!1&&n?n.direction==="sendrecv"?n.setDirection?n.setDirection("sendonly"):n.direction="sendonly":n.direction==="recvonly"&&(n.setDirection?n.setDirection("inactive"):n.direction="inactive"):r.offerToReceiveAudio===!0&&!n&&this.addTransceiver("audio"),typeof r.offerToReceiveVideo!="undefined"&&(r.offerToReceiveVideo=!!r.offerToReceiveVideo);var s=this.getTransceivers().find(function(o){return o.receiver.track.kind==="video"});r.offerToReceiveVideo===!1&&s?s.direction==="sendrecv"?s.setDirection?s.setDirection("sendonly"):s.direction="sendonly":s.direction==="recvonly"&&(s.setDirection?s.setDirection("inactive"):s.direction="inactive"):r.offerToReceiveVideo===!0&&!s&&this.addTransceiver("video")}return t.apply(this,arguments)}}function Lh(i){(typeof i=="undefined"?"undefined":Nr(i))!=="object"||i.AudioContext||(i.AudioContext=i.webkitAudioContext)}});var vd=_e(Zt=>{"use strict";var Vf=_(f());Object.defineProperty(Zt,"__esModule",{value:!0});var kh=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(i){return typeof i}:function(i){return i&&typeof Symbol=="function"&&i.constructor===Symbol&&i!==Symbol.prototype?"symbol":typeof i};Zt.shimRTCIceCandidate=Bh;Zt.shimMaxMessageSize=$h;Zt.shimSendThrowTypeError=Hh;Zt.shimConnectionState=Fh;Zt.removeExtmapAllowMixed=Gh;Zt.shimAddIceCandidateNullOrEmpty=Wh;var xh=_o(),Vn=wh(xh),Uh=ft(),yd=Vh(Uh);function Vh(i){if(i&&i.__esModule)return i;var t={};if(i!=null)for(var e in i)Object.prototype.hasOwnProperty.call(i,e)&&(t[e]=i[e]);return t.default=i,t}function wh(i){return i&&i.__esModule?i:{default:i}}function Bh(i){if(!(!i.RTCIceCandidate||i.RTCIceCandidate&&"foundation"in i.RTCIceCandidate.prototype)){var t=i.RTCIceCandidate;i.RTCIceCandidate=function(r){if((typeof r=="undefined"?"undefined":kh(r))==="object"&&r.candidate&&r.candidate.indexOf("a=")===0&&(r=JSON.parse(JSON.stringify(r)),r.candidate=r.candidate.substr(2)),r.candidate&&r.candidate.length){var n=new t(r),s=Vn.default.parseCandidate(r.candidate),o=Object.assign(n,s);return o.toJSON=function(){return{candidate:o.candidate,sdpMid:o.sdpMid,sdpMLineIndex:o.sdpMLineIndex,usernameFragment:o.usernameFragment}},o}return new t(r)},i.RTCIceCandidate.prototype=t.prototype,yd.wrapPeerConnectionEvent(i,"icecandidate",function(e){return e.candidate&&Object.defineProperty(e,"candidate",{value:new i.RTCIceCandidate(e.candidate),writable:"false"}),e})}}function $h(i,t){if(!!i.RTCPeerConnection){"sctp"in i.RTCPeerConnection.prototype||Object.defineProperty(i.RTCPeerConnection.prototype,"sctp",{get:function(){return typeof this._sctp=="undefined"?null:this._sctp}});var e=function(c){if(!c||!c.sdp)return!1;var d=Vn.default.splitSections(c.sdp);return d.shift(),d.some(function(u){var l=Vn.default.parseMLine(u);return l&&l.kind==="application"&&l.protocol.indexOf("SCTP")!==-1})},r=function(c){var d=c.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(d===null||d.length<2)return-1;var u=parseInt(d[1],10);return u!==u?-1:u},n=function(c){var d=65536;return t.browser==="firefox"&&(t.version<57?c===-1?d=16384:d=2147483637:t.version<60?d=t.version===57?65535:65536:d=2147483637),d},s=function(c,d){var u=65536;t.browser==="firefox"&&t.version===57&&(u=65535);var l=Vn.default.matchPrefix(c.sdp,"a=max-message-size:");return l.length>0?u=parseInt(l[0].substr(19),10):t.browser==="firefox"&&d!==-1&&(u=2147483637),u},o=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,t.browser==="chrome"&&t.version>=76){var c=this.getConfiguration(),d=c.sdpSemantics;d==="plan-b"&&Object.defineProperty(this,"sctp",{get:function(){return typeof this._sctp=="undefined"?null:this._sctp},enumerable:!0,configurable:!0})}if(e(arguments[0])){var u=r(arguments[0]),l=n(u),h=s(arguments[0],u),I=void 0;l===0&&h===0?I=Number.POSITIVE_INFINITY:l===0||h===0?I=Math.max(l,h):I=Math.min(l,h);var T={};Object.defineProperty(T,"maxMessageSize",{get:function(){return I}}),this._sctp=T}return o.apply(this,arguments)}}}function Hh(i){if(!(i.RTCPeerConnection&&"createDataChannel"in i.RTCPeerConnection.prototype))return;function t(r,n){var s=r.send;r.send=function(){var a=arguments[0],c=a.length||a.size||a.byteLength;if(r.readyState==="open"&&n.sctp&&c>n.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+n.sctp.maxMessageSize+" bytes)");return s.apply(r,arguments)}}var e=i.RTCPeerConnection.prototype.createDataChannel;i.RTCPeerConnection.prototype.createDataChannel=function(){var n=e.apply(this,arguments);return t(n,this),n},yd.wrapPeerConnectionEvent(i,"datachannel",function(r){return t(r.channel,r.target),r})}function Fh(i){if(!(!i.RTCPeerConnection||"connectionState"in i.RTCPeerConnection.prototype)){var t=i.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get:function(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get:function(){return this._onconnectionstatechange||null},set:function(r){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),r&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=r)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(function(e){var r=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=function(n){var s=n.target;if(s._lastConnectionState!==s.connectionState){s._lastConnectionState=s.connectionState;var o=new Event("connectionstatechange",n);s.dispatchEvent(o)}return n},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),r.apply(this,arguments)}})}}function Gh(i,t){if(!!i.RTCPeerConnection&&!(t.browser==="chrome"&&t.version>=71)&&!(t.browser==="safari"&&t.version>=605)){var e=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(n){if(n&&n.sdp&&n.sdp.indexOf(`
66
+ `;return}if(h.stream){var T;h.kind==="audio"?T=h.stream.getAudioTracks()[0]:h.kind==="video"&&(T=h.stream.getVideoTracks()[0]),T&&t>=15019&&h.kind==="video"&&!h.sendEncodingParameters[0].rtx&&(h.sendEncodingParameters[0].rtx={ssrc:h.sendEncodingParameters[0].ssrc+1})}var N=cs(h.localCapabilities,h.remoteCapabilities),$=N.codecs.filter(function(x){return x.name.toLowerCase()==="rtx"}).length;!$&&h.sendEncodingParameters[0].rtx&&delete h.sendEncodingParameters[0].rtx,d+=wd(h,N,"answer",h.stream,c._dtlsRole),h.rtcpParameters&&h.rtcpParameters.reducedSize&&(d+=`a=rtcp-rsize\r
67
+ `)}});var l=new i.RTCSessionDescription({type:"answer",sdp:d});return Promise.resolve(l)},s.prototype.addIceCandidate=function(c){var d=this,u;return c&&!(c.sdpMLineIndex!==void 0||c.sdpMid)?Promise.reject(new TypeError("sdpMLineIndex or sdpMid required")):new Promise(function(l,h){if(d._remoteDescription)if(!c||c.candidate==="")for(var I=0;I<d.transceivers.length&&!(!d.transceivers[I].rejected&&(d.transceivers[I].iceTransport.addRemoteCandidate({}),u=K.getMediaSections(d._remoteDescription.sdp),u[I]+=`a=end-of-candidates\r
68
+ `,d._remoteDescription.sdp=K.getDescription(d._remoteDescription.sdp)+u.join(""),d.usingBundle));I++);else{var T=c.sdpMLineIndex;if(c.sdpMid){for(var N=0;N<d.transceivers.length;N++)if(d.transceivers[N].mid===c.sdpMid){T=N;break}}var $=d.transceivers[T];if($){if($.rejected)return l();var x=Object.keys(c.candidate).length>0?K.parseCandidate(c.candidate):{};if(x.protocol==="tcp"&&(x.port===0||x.port===9)||x.component&&x.component!==1)return l();if((T===0||T>0&&$.iceTransport!==d.transceivers[0].iceTransport)&&!Wo($.iceTransport,x))return h(Pe("OperationError","Can not add ICE candidate"));var F=c.candidate.trim();F.indexOf("a=")===0&&(F=F.substr(2)),u=K.getMediaSections(d._remoteDescription.sdp),u[T]+="a="+(x.type?F:"end-of-candidates")+`\r
69
+ `,d._remoteDescription.sdp=K.getDescription(d._remoteDescription.sdp)+u.join("")}else return h(Pe("OperationError","Can not add ICE candidate"))}else return h(Pe("InvalidStateError","Can not add ICE candidate without a remote description"));l()})},s.prototype.getStats=function(c){if(c&&c instanceof i.MediaStreamTrack){var d=null;if(this.transceivers.forEach(function(l){l.rtpSender&&l.rtpSender.track===c?d=l.rtpSender:l.rtpReceiver&&l.rtpReceiver.track===c&&(d=l.rtpReceiver)}),!d)throw Pe("InvalidAccessError","Invalid selector.");return d.getStats()}var u=[];return this.transceivers.forEach(function(l){["rtpSender","rtpReceiver","iceGatherer","iceTransport","dtlsTransport"].forEach(function(h){l[h]&&u.push(l[h].getStats())})}),Promise.all(u).then(function(l){var h=new Map;return l.forEach(function(I){I.forEach(function(T){h.set(T.id,T)})}),h})};var o=["RTCRtpSender","RTCRtpReceiver","RTCIceGatherer","RTCIceTransport","RTCDtlsTransport"];o.forEach(function(c){var d=i[c];if(d&&d.prototype&&d.prototype.getStats){var u=d.prototype.getStats;d.prototype.getStats=function(){return u.apply(this).then(function(l){var h=new Map;return Object.keys(l).forEach(function(I){l[I].type=th(l[I]),h.set(I,l[I])}),h})}}});var a=["createOffer","createAnswer"];return a.forEach(function(c){var d=s.prototype[c];s.prototype[c]=function(){var u=arguments;return typeof u[0]=="function"||typeof u[1]=="function"?d.apply(this,[arguments[2]]).then(function(l){typeof u[0]=="function"&&u[0].apply(null,[l])},function(l){typeof u[1]=="function"&&u[1].apply(null,[l])}):d.apply(this,arguments)}}),a=["setLocalDescription","setRemoteDescription","addIceCandidate"],a.forEach(function(c){var d=s.prototype[c];s.prototype[c]=function(){var u=arguments;return typeof u[1]=="function"||typeof u[2]=="function"?d.apply(this,arguments).then(function(){typeof u[1]=="function"&&u[1].apply(null)},function(l){typeof u[2]=="function"&&u[2].apply(null,[l])}):d.apply(this,arguments)}}),["getStats"].forEach(function(c){var d=s.prototype[c];s.prototype[c]=function(){var u=arguments;return typeof u[1]=="function"?d.apply(this,arguments).then(function(){typeof u[1]=="function"&&u[1].apply(null)}):d.apply(this,arguments)}}),s}});var Fd=fe(ii=>{"use strict";var cE=_(f());Object.defineProperty(ii,"__esModule",{value:!0});ii.shimGetDisplayMedia=ii.shimGetUserMedia=void 0;var rh=xd();Object.defineProperty(ii,"shimGetUserMedia",{enumerable:!0,get:function(){return rh.shimGetUserMedia}});var nh=Ud();Object.defineProperty(ii,"shimGetDisplayMedia",{enumerable:!0,get:function(){return nh.shimGetDisplayMedia}});ii.shimPeerConnection=ph;ii.shimReplaceTrack=hh;var sh=It(),oh=lh(sh),ah=Vd(),ch=Hd(),dh=uh(ch);function uh(i){return i&&i.__esModule?i:{default:i}}function lh(i){if(i&&i.__esModule)return i;var t={};if(i!=null)for(var e in i)Object.prototype.hasOwnProperty.call(i,e)&&(t[e]=i[e]);return t.default=i,t}function ph(i,t){if(i.RTCIceGatherer&&(i.RTCIceCandidate||(i.RTCIceCandidate=function(s){return s}),i.RTCSessionDescription||(i.RTCSessionDescription=function(s){return s}),t.version<15025)){var e=Object.getOwnPropertyDescriptor(i.MediaStreamTrack.prototype,"enabled");Object.defineProperty(i.MediaStreamTrack.prototype,"enabled",{set:function(s){e.set.call(this,s);var o=new Event("enabled");o.enabled=s,this.dispatchEvent(o)}})}i.RTCRtpSender&&!("dtmf"in i.RTCRtpSender.prototype)&&Object.defineProperty(i.RTCRtpSender.prototype,"dtmf",{get:function(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=new i.RTCDtmfSender(this):this.track.kind==="video"&&(this._dtmf=null)),this._dtmf}}),i.RTCDtmfSender&&!i.RTCDTMFSender&&(i.RTCDTMFSender=i.RTCDtmfSender);var r=(0,dh.default)(i,t.version);i.RTCPeerConnection=function(s){return s&&s.iceServers&&(s.iceServers=(0,ah.filterIceServers)(s.iceServers,t.version),oh.log("ICE servers after filtering:",s.iceServers)),new r(s)},i.RTCPeerConnection.prototype=r.prototype}function hh(i){i.RTCRtpSender&&!("replaceTrack"in i.RTCRtpSender.prototype)&&(i.RTCRtpSender.prototype.replaceTrack=i.RTCRtpSender.prototype.setTrack)}});var Gd=fe(jo=>{"use strict";var uE=_(f());Object.defineProperty(jo,"__esModule",{value:!0});var Ko=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(i){return typeof i}:function(i){return i&&typeof Symbol=="function"&&i.constructor===Symbol&&i!==Symbol.prototype?"symbol":typeof i};jo.shimGetUserMedia=Eh;var mh=It(),_h=fh(mh);function fh(i){if(i&&i.__esModule)return i;var t={};if(i!=null)for(var e in i)Object.prototype.hasOwnProperty.call(i,e)&&(t[e]=i[e]);return t.default=i,t}function Eh(i,t){var e=i&&i.navigator,r=i&&i.MediaStreamTrack;if(e.getUserMedia=function(c,d,u){_h.deprecated("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),e.mediaDevices.getUserMedia(c).then(d,u)},!(t.version>55&&"autoGainControl"in e.mediaDevices.getSupportedConstraints())){var n=function(d,u,l){u in d&&!(l in d)&&(d[l]=d[u],delete d[u])},s=e.mediaDevices.getUserMedia.bind(e.mediaDevices);if(e.mediaDevices.getUserMedia=function(c){return(typeof c=="undefined"?"undefined":Ko(c))==="object"&&Ko(c.audio)==="object"&&(c=JSON.parse(JSON.stringify(c)),n(c.audio,"autoGainControl","mozAutoGainControl"),n(c.audio,"noiseSuppression","mozNoiseSuppression")),s(c)},r&&r.prototype.getSettings){var o=r.prototype.getSettings;r.prototype.getSettings=function(){var c=o.apply(this,arguments);return n(c,"mozAutoGainControl","autoGainControl"),n(c,"mozNoiseSuppression","noiseSuppression"),c}}if(r&&r.prototype.applyConstraints){var a=r.prototype.applyConstraints;r.prototype.applyConstraints=function(c){return this.kind==="audio"&&(typeof c=="undefined"?"undefined":Ko(c))==="object"&&(c=JSON.parse(JSON.stringify(c)),n(c,"autoGainControl","mozAutoGainControl"),n(c,"noiseSuppression","mozNoiseSuppression")),a.apply(this,[c])}}}}});var Wd=fe(Jo=>{"use strict";var pE=_(f());Object.defineProperty(Jo,"__esModule",{value:!0});Jo.shimGetDisplayMedia=Th;function Th(i,t){i.navigator.mediaDevices&&"getDisplayMedia"in i.navigator.mediaDevices||!i.navigator.mediaDevices||(i.navigator.mediaDevices.getDisplayMedia=function(r){if(!(r&&r.video)){var n=new DOMException("getDisplayMedia without video constraints is undefined");return n.name="NotFoundError",n.code=8,Promise.reject(n)}return r.video===!0?r.video={mediaSource:t}:r.video.mediaSource=t,i.navigator.mediaDevices.getUserMedia(r)})}});var jd=fe(Me=>{"use strict";var mE=_(f());Object.defineProperty(Me,"__esModule",{value:!0});Me.shimGetDisplayMedia=Me.shimGetUserMedia=void 0;var ri=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(i){return typeof i}:function(i){return i&&typeof Symbol=="function"&&i.constructor===Symbol&&i!==Symbol.prototype?"symbol":typeof i},Sh=Gd();Object.defineProperty(Me,"shimGetUserMedia",{enumerable:!0,get:function(){return Sh.shimGetUserMedia}});var gh=Wd();Object.defineProperty(Me,"shimGetDisplayMedia",{enumerable:!0,get:function(){return gh.shimGetDisplayMedia}});Me.shimOnTrack=Ch;Me.shimPeerConnection=yh;Me.shimSenderGetStats=vh;Me.shimReceiverGetStats=Nh;Me.shimRemoveStream=bh;Me.shimRTCDataChannel=Dh;Me.shimAddTransceiver=Oh;Me.shimGetParameters=Ph;Me.shimCreateOffer=Mh;Me.shimCreateAnswer=Lh;var Ih=It(),Kd=Rh(Ih);function Rh(i){if(i&&i.__esModule)return i;var t={};if(i!=null)for(var e in i)Object.prototype.hasOwnProperty.call(i,e)&&(t[e]=i[e]);return t.default=i,t}function Ah(i,t,e){return t in i?Object.defineProperty(i,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):i[t]=e,i}function Ch(i){(typeof i=="undefined"?"undefined":ri(i))==="object"&&i.RTCTrackEvent&&"receiver"in i.RTCTrackEvent.prototype&&!("transceiver"in i.RTCTrackEvent.prototype)&&Object.defineProperty(i.RTCTrackEvent.prototype,"transceiver",{get:function(){return{receiver:this.receiver}}})}function yh(i,t){if(!((typeof i=="undefined"?"undefined":ri(i))!=="object"||!(i.RTCPeerConnection||i.mozRTCPeerConnection))){!i.RTCPeerConnection&&i.mozRTCPeerConnection&&(i.RTCPeerConnection=i.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(n){var s=i.RTCPeerConnection.prototype[n],o=Ah({},n,function(){return arguments[0]=new(n==="addIceCandidate"?i.RTCIceCandidate:i.RTCSessionDescription)(arguments[0]),s.apply(this,arguments)});i.RTCPeerConnection.prototype[n]=o[n]});var e={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},r=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){var s=Array.prototype.slice.call(arguments),o=s[0],a=s[1],c=s[2];return r.apply(this,[o||null]).then(function(d){if(t.version<53&&!a)try{d.forEach(function(u){u.type=e[u.type]||u.type})}catch(u){if(u.name!=="TypeError")throw u;d.forEach(function(l,h){d.set(h,Object.assign({},l,{type:e[l.type]||l.type}))})}return d}).then(a,c)}}}function vh(i){if(!!((typeof i=="undefined"?"undefined":ri(i))==="object"&&i.RTCPeerConnection&&i.RTCRtpSender)&&!(i.RTCRtpSender&&"getStats"in i.RTCRtpSender.prototype)){var t=i.RTCPeerConnection.prototype.getSenders;t&&(i.RTCPeerConnection.prototype.getSenders=function(){var n=this,s=t.apply(this,[]);return s.forEach(function(o){return o._pc=n}),s});var e=i.RTCPeerConnection.prototype.addTrack;e&&(i.RTCPeerConnection.prototype.addTrack=function(){var n=e.apply(this,arguments);return n._pc=this,n}),i.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}}function Nh(i){if(!!((typeof i=="undefined"?"undefined":ri(i))==="object"&&i.RTCPeerConnection&&i.RTCRtpSender)&&!(i.RTCRtpSender&&"getStats"in i.RTCRtpReceiver.prototype)){var t=i.RTCPeerConnection.prototype.getReceivers;t&&(i.RTCPeerConnection.prototype.getReceivers=function(){var r=this,n=t.apply(this,[]);return n.forEach(function(s){return s._pc=r}),n}),Kd.wrapPeerConnectionEvent(i,"track",function(e){return e.receiver._pc=e.srcElement,e}),i.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}}function bh(i){!i.RTCPeerConnection||"removeStream"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.removeStream=function(e){var r=this;Kd.deprecated("removeStream","removeTrack"),this.getSenders().forEach(function(n){n.track&&e.getTracks().includes(n.track)&&r.removeTrack(n)})})}function Dh(i){i.DataChannel&&!i.RTCDataChannel&&(i.RTCDataChannel=i.DataChannel)}function Oh(i){if(!!((typeof i=="undefined"?"undefined":ri(i))==="object"&&i.RTCPeerConnection)){var t=i.RTCPeerConnection.prototype.addTransceiver;t&&(i.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];var r=arguments[1],n=r&&"sendEncodings"in r;n&&r.sendEncodings.forEach(function(c){if("rid"in c){var d=/^[a-z0-9]{0,16}$/i;if(!d.test(c.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in c&&!(parseFloat(c.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in c&&!(parseFloat(c.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});var s=t.apply(this,arguments);if(n){var o=s.sender,a=o.getParameters();(!("encodings"in a)||a.encodings.length===1&&Object.keys(a.encodings[0]).length===0)&&(a.encodings=r.sendEncodings,o.sendEncodings=r.sendEncodings,this.setParametersPromises.push(o.setParameters(a).then(function(){delete o.sendEncodings}).catch(function(){delete o.sendEncodings})))}return s})}}function Ph(i){if(!!((typeof i=="undefined"?"undefined":ri(i))==="object"&&i.RTCRtpSender)){var t=i.RTCRtpSender.prototype.getParameters;t&&(i.RTCRtpSender.prototype.getParameters=function(){var r=t.apply(this,arguments);return"encodings"in r||(r.encodings=[].concat(this.sendEncodings||[{}])),r})}}function Mh(i){if(!!((typeof i=="undefined"?"undefined":ri(i))==="object"&&i.RTCPeerConnection)){var t=i.RTCPeerConnection.prototype.createOffer;i.RTCPeerConnection.prototype.createOffer=function(){var r=this,n=arguments;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(function(){return t.apply(r,n)}).finally(function(){r.setParametersPromises=[]}):t.apply(this,arguments)}}}function Lh(i){if(!!((typeof i=="undefined"?"undefined":ri(i))==="object"&&i.RTCPeerConnection)){var t=i.RTCPeerConnection.prototype.createAnswer;i.RTCPeerConnection.prototype.createAnswer=function(){var r=this,n=arguments;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(function(){return t.apply(r,n)}).finally(function(){r.setParametersPromises=[]}):t.apply(this,arguments)}}}});var Xd=fe(lt=>{"use strict";var fE=_(f());Object.defineProperty(lt,"__esModule",{value:!0});var qr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(i){return typeof i}:function(i){return i&&typeof Symbol=="function"&&i.constructor===Symbol&&i!==Symbol.prototype?"symbol":typeof i};lt.shimLocalStreamsAPI=Uh;lt.shimRemoteStreamsAPI=Vh;lt.shimCallbacksAPI=wh;lt.shimGetUserMedia=Bh;lt.shimConstraints=Yd;lt.shimRTCIceServerUrls=$h;lt.shimTrackEventTransceiver=Hh;lt.shimCreateOfferLegacy=Fh;lt.shimAudioContext=Gh;var kh=It(),Jd=xh(kh);function xh(i){if(i&&i.__esModule)return i;var t={};if(i!=null)for(var e in i)Object.prototype.hasOwnProperty.call(i,e)&&(t[e]=i[e]);return t.default=i,t}function Uh(i){if(!((typeof i=="undefined"?"undefined":qr(i))!=="object"||!i.RTCPeerConnection)){if("getLocalStreams"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in i.RTCPeerConnection.prototype)){var t=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addStream=function(r){var n=this;this._localStreams||(this._localStreams=[]),this._localStreams.includes(r)||this._localStreams.push(r),r.getAudioTracks().forEach(function(s){return t.call(n,s,r)}),r.getVideoTracks().forEach(function(s){return t.call(n,s,r)})},i.RTCPeerConnection.prototype.addTrack=function(r){for(var n=this,s=arguments.length,o=Array(s>1?s-1:0),a=1;a<s;a++)o[a-1]=arguments[a];return o&&o.forEach(function(c){n._localStreams?n._localStreams.includes(c)||n._localStreams.push(c):n._localStreams=[c]}),t.apply(this,arguments)}}"removeStream"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.removeStream=function(r){var n=this;this._localStreams||(this._localStreams=[]);var s=this._localStreams.indexOf(r);if(s!==-1){this._localStreams.splice(s,1);var o=r.getTracks();this.getSenders().forEach(function(a){o.includes(a.track)&&n.removeTrack(a)})}})}}function Vh(i){if(!((typeof i=="undefined"?"undefined":qr(i))!=="object"||!i.RTCPeerConnection)&&("getRemoteStreams"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in i.RTCPeerConnection.prototype))){Object.defineProperty(i.RTCPeerConnection.prototype,"onaddstream",{get:function(){return this._onaddstream},set:function(r){var n=this;this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=r),this.addEventListener("track",this._onaddstreampoly=function(s){s.streams.forEach(function(o){if(n._remoteStreams||(n._remoteStreams=[]),!n._remoteStreams.includes(o)){n._remoteStreams.push(o);var a=new Event("addstream");a.stream=o,n.dispatchEvent(a)}})})}});var t=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){var r=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(n){n.streams.forEach(function(s){if(r._remoteStreams||(r._remoteStreams=[]),!(r._remoteStreams.indexOf(s)>=0)){r._remoteStreams.push(s);var o=new Event("addstream");o.stream=s,r.dispatchEvent(o)}})}),t.apply(r,arguments)}}}function wh(i){if(!((typeof i=="undefined"?"undefined":qr(i))!=="object"||!i.RTCPeerConnection)){var t=i.RTCPeerConnection.prototype,e=t.createOffer,r=t.createAnswer,n=t.setLocalDescription,s=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(d,u){var l=arguments.length>=2?arguments[2]:arguments[0],h=e.apply(this,[l]);return u?(h.then(d,u),Promise.resolve()):h},t.createAnswer=function(d,u){var l=arguments.length>=2?arguments[2]:arguments[0],h=r.apply(this,[l]);return u?(h.then(d,u),Promise.resolve()):h};var a=function(d,u,l){var h=n.apply(this,[d]);return l?(h.then(u,l),Promise.resolve()):h};t.setLocalDescription=a,a=function(d,u,l){var h=s.apply(this,[d]);return l?(h.then(u,l),Promise.resolve()):h},t.setRemoteDescription=a,a=function(d,u,l){var h=o.apply(this,[d]);return l?(h.then(u,l),Promise.resolve()):h},t.addIceCandidate=a}}function Bh(i){var t=i&&i.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){var e=t.mediaDevices,r=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=function(n){return r(Yd(n))}}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(s,o,a){t.mediaDevices.getUserMedia(s).then(o,a)}.bind(t))}function Yd(i){return i&&i.video!==void 0?Object.assign({},i,{video:Jd.compactObject(i.video)}):i}function $h(i){if(!!i.RTCPeerConnection){var t=i.RTCPeerConnection;i.RTCPeerConnection=function(r,n){if(r&&r.iceServers){for(var s=[],o=0;o<r.iceServers.length;o++){var a=r.iceServers[o];!a.hasOwnProperty("urls")&&a.hasOwnProperty("url")?(Jd.deprecated("RTCIceServer.url","RTCIceServer.urls"),a=JSON.parse(JSON.stringify(a)),a.urls=a.url,delete a.url,s.push(a)):s.push(r.iceServers[o])}r.iceServers=s}return new t(r,n)},i.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(i.RTCPeerConnection,"generateCertificate",{get:function(){return t.generateCertificate}})}}function Hh(i){(typeof i=="undefined"?"undefined":qr(i))==="object"&&i.RTCTrackEvent&&"receiver"in i.RTCTrackEvent.prototype&&!("transceiver"in i.RTCTrackEvent.prototype)&&Object.defineProperty(i.RTCTrackEvent.prototype,"transceiver",{get:function(){return{receiver:this.receiver}}})}function Fh(i){var t=i.RTCPeerConnection.prototype.createOffer;i.RTCPeerConnection.prototype.createOffer=function(r){if(r){typeof r.offerToReceiveAudio!="undefined"&&(r.offerToReceiveAudio=!!r.offerToReceiveAudio);var n=this.getTransceivers().find(function(o){return o.receiver.track.kind==="audio"});r.offerToReceiveAudio===!1&&n?n.direction==="sendrecv"?n.setDirection?n.setDirection("sendonly"):n.direction="sendonly":n.direction==="recvonly"&&(n.setDirection?n.setDirection("inactive"):n.direction="inactive"):r.offerToReceiveAudio===!0&&!n&&this.addTransceiver("audio"),typeof r.offerToReceiveVideo!="undefined"&&(r.offerToReceiveVideo=!!r.offerToReceiveVideo);var s=this.getTransceivers().find(function(o){return o.receiver.track.kind==="video"});r.offerToReceiveVideo===!1&&s?s.direction==="sendrecv"?s.setDirection?s.setDirection("sendonly"):s.direction="sendonly":s.direction==="recvonly"&&(s.setDirection?s.setDirection("inactive"):s.direction="inactive"):r.offerToReceiveVideo===!0&&!s&&this.addTransceiver("video")}return t.apply(this,arguments)}}function Gh(i){(typeof i=="undefined"?"undefined":qr(i))!=="object"||i.AudioContext||(i.AudioContext=i.webkitAudioContext)}});var qd=fe(ni=>{"use strict";var TE=_(f());Object.defineProperty(ni,"__esModule",{value:!0});var Wh=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(i){return typeof i}:function(i){return i&&typeof Symbol=="function"&&i.constructor===Symbol&&i!==Symbol.prototype?"symbol":typeof i};ni.shimRTCIceCandidate=Xh;ni.shimMaxMessageSize=zh;ni.shimSendThrowTypeError=qh;ni.shimConnectionState=Qh;ni.removeExtmapAllowMixed=Zh;ni.shimAddIceCandidateNullOrEmpty=em;var Kh=Go(),ds=Yh(Kh),jh=It(),zd=Jh(jh);function Jh(i){if(i&&i.__esModule)return i;var t={};if(i!=null)for(var e in i)Object.prototype.hasOwnProperty.call(i,e)&&(t[e]=i[e]);return t.default=i,t}function Yh(i){return i&&i.__esModule?i:{default:i}}function Xh(i){if(!(!i.RTCIceCandidate||i.RTCIceCandidate&&"foundation"in i.RTCIceCandidate.prototype)){var t=i.RTCIceCandidate;i.RTCIceCandidate=function(r){if((typeof r=="undefined"?"undefined":Wh(r))==="object"&&r.candidate&&r.candidate.indexOf("a=")===0&&(r=JSON.parse(JSON.stringify(r)),r.candidate=r.candidate.substr(2)),r.candidate&&r.candidate.length){var n=new t(r),s=ds.default.parseCandidate(r.candidate),o=Object.assign(n,s);return o.toJSON=function(){return{candidate:o.candidate,sdpMid:o.sdpMid,sdpMLineIndex:o.sdpMLineIndex,usernameFragment:o.usernameFragment}},o}return new t(r)},i.RTCIceCandidate.prototype=t.prototype,zd.wrapPeerConnectionEvent(i,"icecandidate",function(e){return e.candidate&&Object.defineProperty(e,"candidate",{value:new i.RTCIceCandidate(e.candidate),writable:"false"}),e})}}function zh(i,t){if(!!i.RTCPeerConnection){"sctp"in i.RTCPeerConnection.prototype||Object.defineProperty(i.RTCPeerConnection.prototype,"sctp",{get:function(){return typeof this._sctp=="undefined"?null:this._sctp}});var e=function(c){if(!c||!c.sdp)return!1;var d=ds.default.splitSections(c.sdp);return d.shift(),d.some(function(u){var l=ds.default.parseMLine(u);return l&&l.kind==="application"&&l.protocol.indexOf("SCTP")!==-1})},r=function(c){var d=c.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(d===null||d.length<2)return-1;var u=parseInt(d[1],10);return u!==u?-1:u},n=function(c){var d=65536;return t.browser==="firefox"&&(t.version<57?c===-1?d=16384:d=2147483637:t.version<60?d=t.version===57?65535:65536:d=2147483637),d},s=function(c,d){var u=65536;t.browser==="firefox"&&t.version===57&&(u=65535);var l=ds.default.matchPrefix(c.sdp,"a=max-message-size:");return l.length>0?u=parseInt(l[0].substr(19),10):t.browser==="firefox"&&d!==-1&&(u=2147483637),u},o=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,t.browser==="chrome"&&t.version>=76){var c=this.getConfiguration(),d=c.sdpSemantics;d==="plan-b"&&Object.defineProperty(this,"sctp",{get:function(){return typeof this._sctp=="undefined"?null:this._sctp},enumerable:!0,configurable:!0})}if(e(arguments[0])){var u=r(arguments[0]),l=n(u),h=s(arguments[0],u),I=void 0;l===0&&h===0?I=Number.POSITIVE_INFINITY:l===0||h===0?I=Math.max(l,h):I=Math.min(l,h);var T={};Object.defineProperty(T,"maxMessageSize",{get:function(){return I}}),this._sctp=T}return o.apply(this,arguments)}}}function qh(i){if(!(i.RTCPeerConnection&&"createDataChannel"in i.RTCPeerConnection.prototype))return;function t(r,n){var s=r.send;r.send=function(){var a=arguments[0],c=a.length||a.size||a.byteLength;if(r.readyState==="open"&&n.sctp&&c>n.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+n.sctp.maxMessageSize+" bytes)");return s.apply(r,arguments)}}var e=i.RTCPeerConnection.prototype.createDataChannel;i.RTCPeerConnection.prototype.createDataChannel=function(){var n=e.apply(this,arguments);return t(n,this),n},zd.wrapPeerConnectionEvent(i,"datachannel",function(r){return t(r.channel,r.target),r})}function Qh(i){if(!(!i.RTCPeerConnection||"connectionState"in i.RTCPeerConnection.prototype)){var t=i.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get:function(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get:function(){return this._onconnectionstatechange||null},set:function(r){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),r&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=r)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(function(e){var r=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=function(n){var s=n.target;if(s._lastConnectionState!==s.connectionState){s._lastConnectionState=s.connectionState;var o=new Event("connectionstatechange",n);s.dispatchEvent(o)}return n},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),r.apply(this,arguments)}})}}function Zh(i,t){if(!!i.RTCPeerConnection&&!(t.browser==="chrome"&&t.version>=71)&&!(t.browser==="safari"&&t.version>=605)){var e=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(n){if(n&&n.sdp&&n.sdp.indexOf(`
70
70
  a=extmap-allow-mixed`)!==-1){var s=n.sdp.split(`
71
71
  `).filter(function(o){return o.trim()!=="a=extmap-allow-mixed"}).join(`
72
- `);i.RTCSessionDescription&&n instanceof i.RTCSessionDescription?arguments[0]=new i.RTCSessionDescription({type:n.type,sdp:s}):n.sdp=s}return e.apply(this,arguments)}}}function Wh(i,t){if(!!(i.RTCPeerConnection&&i.RTCPeerConnection.prototype)){var e=i.RTCPeerConnection.prototype.addIceCandidate;!e||e.length===0||(i.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(t.browser==="chrome"&&t.version<78||t.browser==="firefox"&&t.version<68||t.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():e.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}}});var Nd=_e(go=>{"use strict";var Bf=_(f());Object.defineProperty(go,"__esModule",{value:!0});go.adapterFactory=qh;var Kh=ft(),br=Ki(Kh),jh=dd(),it=Ki(jh),Jh=Ed(),Ti=Ki(Jh),Yh=Id(),Ge=Ki(Yh),Xh=Cd(),Et=Ki(Xh),zh=vd(),Ce=Ki(zh);function Ki(i){if(i&&i.__esModule)return i;var t={};if(i!=null)for(var e in i)Object.prototype.hasOwnProperty.call(i,e)&&(t[e]=i[e]);return t.default=i,t}function qh(){var i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=i.window,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimEdge:!0,shimSafari:!0},r=br.log,n=br.detectBrowser(t),s={browserDetails:n,commonShim:Ce,extractVersion:br.extractVersion,disableLog:br.disableLog,disableWarnings:br.disableWarnings};switch(n.browser){case"chrome":if(!it||!it.shimPeerConnection||!e.shimChrome)return r("Chrome shim is not included in this adapter release."),s;if(n.version===null)return r("Chrome shim can not determine version, not shimming."),s;r("adapter.js shimming chrome."),s.browserShim=it,Ce.shimAddIceCandidateNullOrEmpty(t,n),it.shimGetUserMedia(t,n),it.shimMediaStream(t,n),it.shimPeerConnection(t,n),it.shimOnTrack(t,n),it.shimAddTrackRemoveTrack(t,n),it.shimGetSendersWithDtmf(t,n),it.shimGetStats(t,n),it.shimSenderReceiverGetStats(t,n),it.fixNegotiationNeeded(t,n),Ce.shimRTCIceCandidate(t,n),Ce.shimConnectionState(t,n),Ce.shimMaxMessageSize(t,n),Ce.shimSendThrowTypeError(t,n),Ce.removeExtmapAllowMixed(t,n);break;case"firefox":if(!Ge||!Ge.shimPeerConnection||!e.shimFirefox)return r("Firefox shim is not included in this adapter release."),s;r("adapter.js shimming firefox."),s.browserShim=Ge,Ce.shimAddIceCandidateNullOrEmpty(t,n),Ge.shimGetUserMedia(t,n),Ge.shimPeerConnection(t,n),Ge.shimOnTrack(t,n),Ge.shimRemoveStream(t,n),Ge.shimSenderGetStats(t,n),Ge.shimReceiverGetStats(t,n),Ge.shimRTCDataChannel(t,n),Ge.shimAddTransceiver(t,n),Ge.shimGetParameters(t,n),Ge.shimCreateOffer(t,n),Ge.shimCreateAnswer(t,n),Ce.shimRTCIceCandidate(t,n),Ce.shimConnectionState(t,n),Ce.shimMaxMessageSize(t,n),Ce.shimSendThrowTypeError(t,n);break;case"edge":if(!Ti||!Ti.shimPeerConnection||!e.shimEdge)return r("MS edge shim is not included in this adapter release."),s;r("adapter.js shimming edge."),s.browserShim=Ti,Ti.shimGetUserMedia(t,n),Ti.shimGetDisplayMedia(t,n),Ti.shimPeerConnection(t,n),Ti.shimReplaceTrack(t,n),Ce.shimMaxMessageSize(t,n),Ce.shimSendThrowTypeError(t,n);break;case"safari":if(!Et||!e.shimSafari)return r("Safari shim is not included in this adapter release."),s;r("adapter.js shimming safari."),s.browserShim=Et,Ce.shimAddIceCandidateNullOrEmpty(t,n),Et.shimRTCIceServerUrls(t,n),Et.shimCreateOfferLegacy(t,n),Et.shimCallbacksAPI(t,n),Et.shimLocalStreamsAPI(t,n),Et.shimRemoteStreamsAPI(t,n),Et.shimTrackEventTransceiver(t,n),Et.shimGetUserMedia(t,n),Et.shimAudioContext(t,n),Ce.shimRTCIceCandidate(t,n),Ce.shimMaxMessageSize(t,n),Ce.shimSendThrowTypeError(t,n),Ce.removeExtmapAllowMixed(t,n);break;default:r("Unsupported browser!");break}return s}});var f=_e(Io=>{"use strict";Object.defineProperty(Io,"__esModule",{value:!0});var Qh=Nd(),Zh=(0,Qh.adapterFactory)({window:typeof window=="undefined"?void 0:window});Io.default=Zh});var nt=_e((GE,Zo)=>{"use strict";var WE=_(f()),Cm=Object.prototype.hasOwnProperty,we="~";function en(){}Object.create&&(en.prototype=Object.create(null),new en().__proto__||(we=!1));function ym(i,t,e){this.fn=i,this.context=t,this.once=e||!1}function du(i,t,e,r,n){if(typeof e!="function")throw new TypeError("The listener must be a function");var s=new ym(e,r||i,n),o=we?we+t:t;return i._events[o]?i._events[o].fn?i._events[o]=[i._events[o],s]:i._events[o].push(s):(i._events[o]=s,i._eventsCount++),i}function ms(i,t){--i._eventsCount===0?i._events=new en:delete i._events[t]}function ke(){this._events=new en,this._eventsCount=0}ke.prototype.eventNames=function(){var t=[],e,r;if(this._eventsCount===0)return t;for(r in e=this._events)Cm.call(e,r)&&t.push(we?r.slice(1):r);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(e)):t};ke.prototype.listeners=function(t){var e=we?we+t:t,r=this._events[e];if(!r)return[];if(r.fn)return[r.fn];for(var n=0,s=r.length,o=new Array(s);n<s;n++)o[n]=r[n].fn;return o};ke.prototype.listenerCount=function(t){var e=we?we+t:t,r=this._events[e];return r?r.fn?1:r.length:0};ke.prototype.emit=function(t,e,r,n,s,o){var a=we?we+t:t;if(!this._events[a])return!1;var c=this._events[a],d=arguments.length,u,l;if(c.fn){switch(c.once&&this.removeListener(t,c.fn,void 0,!0),d){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,e),!0;case 3:return c.fn.call(c.context,e,r),!0;case 4:return c.fn.call(c.context,e,r,n),!0;case 5:return c.fn.call(c.context,e,r,n,s),!0;case 6:return c.fn.call(c.context,e,r,n,s,o),!0}for(l=1,u=new Array(d-1);l<d;l++)u[l-1]=arguments[l];c.fn.apply(c.context,u)}else{var h=c.length,I;for(l=0;l<h;l++)switch(c[l].once&&this.removeListener(t,c[l].fn,void 0,!0),d){case 1:c[l].fn.call(c[l].context);break;case 2:c[l].fn.call(c[l].context,e);break;case 3:c[l].fn.call(c[l].context,e,r);break;case 4:c[l].fn.call(c[l].context,e,r,n);break;default:if(!u)for(I=1,u=new Array(d-1);I<d;I++)u[I-1]=arguments[I];c[l].fn.apply(c[l].context,u)}}return!0};ke.prototype.on=function(t,e,r){return du(this,t,e,r,!1)};ke.prototype.once=function(t,e,r){return du(this,t,e,r,!0)};ke.prototype.removeListener=function(t,e,r,n){var s=we?we+t:t;if(!this._events[s])return this;if(!e)return ms(this,s),this;var o=this._events[s];if(o.fn)o.fn===e&&(!n||o.once)&&(!r||o.context===r)&&ms(this,s);else{for(var a=0,c=[],d=o.length;a<d;a++)(o[a].fn!==e||n&&!o[a].once||r&&o[a].context!==r)&&c.push(o[a]);c.length?this._events[s]=c.length===1?c[0]:c:ms(this,s)}return this};ke.prototype.removeAllListeners=function(t){var e;return t?(e=we?we+t:t,this._events[e]&&ms(this,e)):(this._events=new en,this._eventsCount=0),this};ke.prototype.off=ke.prototype.removeListener;ke.prototype.addListener=ke.prototype.on;ke.prefixed=we;ke.EventEmitter=ke;typeof Zo!="undefined"&&(Zo.exports=ke)});var Sc=_e((RD,Al)=>{var AD=_(f()),Rl=Al.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(i){return i.encoding?"rtpmap:%d %s/%s/%s":i.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(i){return i.address!=null?"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(i){return i.subtype!=null?"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(i){return"extmap:%d"+(i.direction?"/%s":"%v")+(i["encrypt-uri"]?" %s":"%v")+" %s"+(i.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(i){return i.sessionConfig!=null?"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(i){var t="candidate:%s %d %s %d %s %d typ %s";return t+=i.raddr!=null?" raddr %s rport %d":"%v%v",t+=i.tcptype!=null?" tcptype %s":"%v",i.generation!=null&&(t+=" generation %d"),t+=i["network-id"]!=null?" network-id %d":"%v",t+=i["network-cost"]!=null?" network-cost %d":"%v",t}},{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(i){var t="ssrc:%d";return i.attribute!=null&&(t+=" %s",i.value!=null&&(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(i){return i.maxMessageSize!=null?"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(i){return i.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(i){return"imageattr:%s %s %s"+(i.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(i){return"simulcast:%s %s"+(i.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(i){return"ts-refclk:%s"+(i.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(i){var t="mediaclk:";return t+=i.id!=null?"id=%s %s":"%v%s",t+=i.mediaClockValue!=null?"=%s":"",t+=i.rateNumerator!=null?" rate=%s":"",t+=i.rateDenominator!=null?"/%s":"",t}},{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(Rl).forEach(function(i){var t=Rl[i];t.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var vl=_e(jt=>{var yD=_(f()),Sr=function(i){return String(Number(i))===i?Number(i):i},O_=function(i,t,e,r){if(r&&!e)t[r]=Sr(i[1]);else for(var n=0;n<e.length;n+=1)i[n+1]!=null&&(t[e[n]]=Sr(i[n+1]))},P_=function(i,t,e){var r=i.name&&i.names;i.push&&!t[i.push]?t[i.push]=[]:r&&!t[i.name]&&(t[i.name]={});var n=i.push?{}:r?t[i.name]:t;O_(e.match(i.reg),n,i.names,i.name),i.push&&t[i.push].push(n)},Cl=Sc(),M_=RegExp.prototype.test.bind(/^([a-z])=(.*)/);jt.parse=function(i){var t={},e=[],r=t;return i.split(/(\r\n|\r|\n)/).filter(M_).forEach(function(n){var s=n[0],o=n.slice(2);s==="m"&&(e.push({rtp:[],fmtp:[]}),r=e[e.length-1]);for(var a=0;a<(Cl[s]||[]).length;a+=1){var c=Cl[s][a];if(c.reg.test(o))return P_(c,r,o)}}),t.media=e,t};var yl=function(i,t){var e=t.split(/=(.+)/,2);return e.length===2?i[e[0]]=Sr(e[1]):e.length===1&&t.length>1&&(i[e[0]]=void 0),i};jt.parseParams=function(i){return i.split(/;\s?/).reduce(yl,{})};jt.parseFmtpConfig=jt.parseParams;jt.parsePayloads=function(i){return i.toString().split(" ").map(Number)};jt.parseRemoteCandidates=function(i){for(var t=[],e=i.split(" ").map(Sr),r=0;r<e.length;r+=3)t.push({component:e[r],ip:e[r+1],port:e[r+2]});return t};jt.parseImageAttributes=function(i){return i.split(" ").map(function(t){return t.substring(1,t.length-1).split(",").reduce(yl,{})})};jt.parseSimulcastStreamList=function(i){return i.split(";").map(function(t){return t.split(",").map(function(e){var r,n=!1;return e[0]!=="~"?r=Sr(e):(r=Sr(e.substring(1,e.length)),n=!0),{scid:r,paused:n}})})}});var bl=_e((vD,Nl)=>{var ND=_(f()),gc=Sc(),L_=/%[sdv%]/g,k_=function(i){var t=1,e=arguments,r=e.length;return i.replace(L_,function(n){if(t>=r)return n;var s=e[t];switch(t+=1,n){case"%%":return"%";case"%s":return String(s);case"%d":return Number(s);case"%v":return""}})},Sn=function(i,t,e){var r=t.format instanceof Function?t.format(t.push?e:e[t.name]):t.format,n=[i+"="+r];if(t.names)for(var s=0;s<t.names.length;s+=1){var o=t.names[s];t.name?n.push(e[t.name][o]):n.push(e[t.names[s]])}else n.push(e[t.name]);return k_.apply(null,n)},x_=["v","o","s","i","u","e","p","c","b","t","r","z","a"],U_=["i","c","b","a"];Nl.exports=function(i,t){t=t||{},i.version==null&&(i.version=0),i.name==null&&(i.name=" "),i.media.forEach(function(s){s.payloads==null&&(s.payloads="")});var e=t.outerOrder||x_,r=t.innerOrder||U_,n=[];return e.forEach(function(s){gc[s].forEach(function(o){o.name in i&&i[o.name]!=null?n.push(Sn(s,o,i)):o.push in i&&i[o.push]!=null&&i[o.push].forEach(function(a){n.push(Sn(s,o,a))})})}),i.media.forEach(function(s){n.push(Sn("m",gc.m[0],s)),r.forEach(function(o){gc[o].forEach(function(a){a.name in s&&s[a.name]!=null?n.push(Sn(o,a,s)):a.push in s&&s[a.push]!=null&&s[a.push].forEach(function(c){n.push(Sn(o,a,c))})})})}),n.join(`\r
72
+ `);i.RTCSessionDescription&&n instanceof i.RTCSessionDescription?arguments[0]=new i.RTCSessionDescription({type:n.type,sdp:s}):n.sdp=s}return e.apply(this,arguments)}}}function em(i,t){if(!!(i.RTCPeerConnection&&i.RTCPeerConnection.prototype)){var e=i.RTCPeerConnection.prototype.addIceCandidate;!e||e.length===0||(i.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(t.browser==="chrome"&&t.version<78||t.browser==="firefox"&&t.version<68||t.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():e.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}}});var Qd=fe(Yo=>{"use strict";var gE=_(f());Object.defineProperty(Yo,"__esModule",{value:!0});Yo.adapterFactory=am;var tm=It(),Qr=nr(tm),im=kd(),it=nr(im),rm=Fd(),yi=nr(rm),nm=jd(),We=nr(nm),sm=Xd(),Rt=nr(sm),om=qd(),Ae=nr(om);function nr(i){if(i&&i.__esModule)return i;var t={};if(i!=null)for(var e in i)Object.prototype.hasOwnProperty.call(i,e)&&(t[e]=i[e]);return t.default=i,t}function am(){var i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=i.window,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimEdge:!0,shimSafari:!0},r=Qr.log,n=Qr.detectBrowser(t),s={browserDetails:n,commonShim:Ae,extractVersion:Qr.extractVersion,disableLog:Qr.disableLog,disableWarnings:Qr.disableWarnings};switch(n.browser){case"chrome":if(!it||!it.shimPeerConnection||!e.shimChrome)return r("Chrome shim is not included in this adapter release."),s;if(n.version===null)return r("Chrome shim can not determine version, not shimming."),s;r("adapter.js shimming chrome."),s.browserShim=it,Ae.shimAddIceCandidateNullOrEmpty(t,n),it.shimGetUserMedia(t,n),it.shimMediaStream(t,n),it.shimPeerConnection(t,n),it.shimOnTrack(t,n),it.shimAddTrackRemoveTrack(t,n),it.shimGetSendersWithDtmf(t,n),it.shimGetStats(t,n),it.shimSenderReceiverGetStats(t,n),it.fixNegotiationNeeded(t,n),Ae.shimRTCIceCandidate(t,n),Ae.shimConnectionState(t,n),Ae.shimMaxMessageSize(t,n),Ae.shimSendThrowTypeError(t,n),Ae.removeExtmapAllowMixed(t,n);break;case"firefox":if(!We||!We.shimPeerConnection||!e.shimFirefox)return r("Firefox shim is not included in this adapter release."),s;r("adapter.js shimming firefox."),s.browserShim=We,Ae.shimAddIceCandidateNullOrEmpty(t,n),We.shimGetUserMedia(t,n),We.shimPeerConnection(t,n),We.shimOnTrack(t,n),We.shimRemoveStream(t,n),We.shimSenderGetStats(t,n),We.shimReceiverGetStats(t,n),We.shimRTCDataChannel(t,n),We.shimAddTransceiver(t,n),We.shimGetParameters(t,n),We.shimCreateOffer(t,n),We.shimCreateAnswer(t,n),Ae.shimRTCIceCandidate(t,n),Ae.shimConnectionState(t,n),Ae.shimMaxMessageSize(t,n),Ae.shimSendThrowTypeError(t,n);break;case"edge":if(!yi||!yi.shimPeerConnection||!e.shimEdge)return r("MS edge shim is not included in this adapter release."),s;r("adapter.js shimming edge."),s.browserShim=yi,yi.shimGetUserMedia(t,n),yi.shimGetDisplayMedia(t,n),yi.shimPeerConnection(t,n),yi.shimReplaceTrack(t,n),Ae.shimMaxMessageSize(t,n),Ae.shimSendThrowTypeError(t,n);break;case"safari":if(!Rt||!e.shimSafari)return r("Safari shim is not included in this adapter release."),s;r("adapter.js shimming safari."),s.browserShim=Rt,Ae.shimAddIceCandidateNullOrEmpty(t,n),Rt.shimRTCIceServerUrls(t,n),Rt.shimCreateOfferLegacy(t,n),Rt.shimCallbacksAPI(t,n),Rt.shimLocalStreamsAPI(t,n),Rt.shimRemoteStreamsAPI(t,n),Rt.shimTrackEventTransceiver(t,n),Rt.shimGetUserMedia(t,n),Rt.shimAudioContext(t,n),Ae.shimRTCIceCandidate(t,n),Ae.shimMaxMessageSize(t,n),Ae.shimSendThrowTypeError(t,n),Ae.removeExtmapAllowMixed(t,n);break;default:r("Unsupported browser!");break}return s}});var f=fe(Xo=>{"use strict";Object.defineProperty(Xo,"__esModule",{value:!0});var cm=Qd(),dm=(0,cm.adapterFactory)({window:typeof window=="undefined"?void 0:window});Xo.default=dm});var rt=fe((RE,zo)=>{"use strict";var AE=_(f()),um=Object.prototype.hasOwnProperty,Be="~";function Zr(){}Object.create&&(Zr.prototype=Object.create(null),new Zr().__proto__||(Be=!1));function lm(i,t,e){this.fn=i,this.context=t,this.once=e||!1}function Zd(i,t,e,r,n){if(typeof e!="function")throw new TypeError("The listener must be a function");var s=new lm(e,r||i,n),o=Be?Be+t:t;return i._events[o]?i._events[o].fn?i._events[o]=[i._events[o],s]:i._events[o].push(s):(i._events[o]=s,i._eventsCount++),i}function us(i,t){--i._eventsCount===0?i._events=new Zr:delete i._events[t]}function Le(){this._events=new Zr,this._eventsCount=0}Le.prototype.eventNames=function(){var t=[],e,r;if(this._eventsCount===0)return t;for(r in e=this._events)um.call(e,r)&&t.push(Be?r.slice(1):r);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(e)):t};Le.prototype.listeners=function(t){var e=Be?Be+t:t,r=this._events[e];if(!r)return[];if(r.fn)return[r.fn];for(var n=0,s=r.length,o=new Array(s);n<s;n++)o[n]=r[n].fn;return o};Le.prototype.listenerCount=function(t){var e=Be?Be+t:t,r=this._events[e];return r?r.fn?1:r.length:0};Le.prototype.emit=function(t,e,r,n,s,o){var a=Be?Be+t:t;if(!this._events[a])return!1;var c=this._events[a],d=arguments.length,u,l;if(c.fn){switch(c.once&&this.removeListener(t,c.fn,void 0,!0),d){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,e),!0;case 3:return c.fn.call(c.context,e,r),!0;case 4:return c.fn.call(c.context,e,r,n),!0;case 5:return c.fn.call(c.context,e,r,n,s),!0;case 6:return c.fn.call(c.context,e,r,n,s,o),!0}for(l=1,u=new Array(d-1);l<d;l++)u[l-1]=arguments[l];c.fn.apply(c.context,u)}else{var h=c.length,I;for(l=0;l<h;l++)switch(c[l].once&&this.removeListener(t,c[l].fn,void 0,!0),d){case 1:c[l].fn.call(c[l].context);break;case 2:c[l].fn.call(c[l].context,e);break;case 3:c[l].fn.call(c[l].context,e,r);break;case 4:c[l].fn.call(c[l].context,e,r,n);break;default:if(!u)for(I=1,u=new Array(d-1);I<d;I++)u[I-1]=arguments[I];c[l].fn.apply(c[l].context,u)}}return!0};Le.prototype.on=function(t,e,r){return Zd(this,t,e,r,!1)};Le.prototype.once=function(t,e,r){return Zd(this,t,e,r,!0)};Le.prototype.removeListener=function(t,e,r,n){var s=Be?Be+t:t;if(!this._events[s])return this;if(!e)return us(this,s),this;var o=this._events[s];if(o.fn)o.fn===e&&(!n||o.once)&&(!r||o.context===r)&&us(this,s);else{for(var a=0,c=[],d=o.length;a<d;a++)(o[a].fn!==e||n&&!o[a].once||r&&o[a].context!==r)&&c.push(o[a]);c.length?this._events[s]=c.length===1?c[0]:c:us(this,s)}return this};Le.prototype.removeAllListeners=function(t){var e;return t?(e=Be?Be+t:t,this._events[e]&&us(this,e)):(this._events=new Zr,this._eventsCount=0),this};Le.prototype.off=Le.prototype.removeListener;Le.prototype.addListener=Le.prototype.on;Le.prefixed=Be;Le.EventEmitter=Le;typeof zo!="undefined"&&(zo.exports=Le)});var Wc=fe((_O,Ll)=>{var fO=_(f()),Ml=Ll.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(i){return i.encoding?"rtpmap:%d %s/%s/%s":i.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(i){return i.address!=null?"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(i){return i.subtype!=null?"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(i){return"extmap:%d"+(i.direction?"/%s":"%v")+(i["encrypt-uri"]?" %s":"%v")+" %s"+(i.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(i){return i.sessionConfig!=null?"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(i){var t="candidate:%s %d %s %d %s %d typ %s";return t+=i.raddr!=null?" raddr %s rport %d":"%v%v",t+=i.tcptype!=null?" tcptype %s":"%v",i.generation!=null&&(t+=" generation %d"),t+=i["network-id"]!=null?" network-id %d":"%v",t+=i["network-cost"]!=null?" network-cost %d":"%v",t}},{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(i){var t="ssrc:%d";return i.attribute!=null&&(t+=" %s",i.value!=null&&(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(i){return i.maxMessageSize!=null?"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(i){return i.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(i){return"imageattr:%s %s %s"+(i.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(i){return"simulcast:%s %s"+(i.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(i){return"ts-refclk:%s"+(i.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(i){var t="mediaclk:";return t+=i.id!=null?"id=%s %s":"%v%s",t+=i.mediaClockValue!=null?"=%s":"",t+=i.rateNumerator!=null?" rate=%s":"",t+=i.rateDenominator!=null?"/%s":"",t}},{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(Ml).forEach(function(i){var t=Ml[i];t.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var Ul=fe(qt=>{var TO=_(f()),Fr=function(i){return String(Number(i))===i?Number(i):i},lf=function(i,t,e,r){if(r&&!e)t[r]=Fr(i[1]);else for(var n=0;n<e.length;n+=1)i[n+1]!=null&&(t[e[n]]=Fr(i[n+1]))},pf=function(i,t,e){var r=i.name&&i.names;i.push&&!t[i.push]?t[i.push]=[]:r&&!t[i.name]&&(t[i.name]={});var n=i.push?{}:r?t[i.name]:t;lf(e.match(i.reg),n,i.names,i.name),i.push&&t[i.push].push(n)},kl=Wc(),hf=RegExp.prototype.test.bind(/^([a-z])=(.*)/);qt.parse=function(i){var t={},e=[],r=t;return i.split(/(\r\n|\r|\n)/).filter(hf).forEach(function(n){var s=n[0],o=n.slice(2);s==="m"&&(e.push({rtp:[],fmtp:[]}),r=e[e.length-1]);for(var a=0;a<(kl[s]||[]).length;a+=1){var c=kl[s][a];if(c.reg.test(o))return pf(c,r,o)}}),t.media=e,t};var xl=function(i,t){var e=t.split(/=(.+)/,2);return e.length===2?i[e[0]]=Fr(e[1]):e.length===1&&t.length>1&&(i[e[0]]=void 0),i};qt.parseParams=function(i){return i.split(/;\s?/).reduce(xl,{})};qt.parseFmtpConfig=qt.parseParams;qt.parsePayloads=function(i){return i.toString().split(" ").map(Number)};qt.parseRemoteCandidates=function(i){for(var t=[],e=i.split(" ").map(Fr),r=0;r<e.length;r+=3)t.push({component:e[r],ip:e[r+1],port:e[r+2]});return t};qt.parseImageAttributes=function(i){return i.split(" ").map(function(t){return t.substring(1,t.length-1).split(",").reduce(xl,{})})};qt.parseSimulcastStreamList=function(i){return i.split(";").map(function(t){return t.split(",").map(function(e){var r,n=!1;return e[0]!=="~"?r=Fr(e):(r=Fr(e.substring(1,e.length)),n=!0),{scid:r,paused:n}})})}});var wl=fe((SO,Vl)=>{var gO=_(f()),Kc=Wc(),mf=/%[sdv%]/g,_f=function(i){var t=1,e=arguments,r=e.length;return i.replace(mf,function(n){if(t>=r)return n;var s=e[t];switch(t+=1,n){case"%%":return"%";case"%s":return String(s);case"%d":return Number(s);case"%v":return""}})},Kn=function(i,t,e){var r=t.format instanceof Function?t.format(t.push?e:e[t.name]):t.format,n=[i+"="+r];if(t.names)for(var s=0;s<t.names.length;s+=1){var o=t.names[s];t.name?n.push(e[t.name][o]):n.push(e[t.names[s]])}else n.push(e[t.name]);return _f.apply(null,n)},ff=["v","o","s","i","u","e","p","c","b","t","r","z","a"],Ef=["i","c","b","a"];Vl.exports=function(i,t){t=t||{},i.version==null&&(i.version=0),i.name==null&&(i.name=" "),i.media.forEach(function(s){s.payloads==null&&(s.payloads="")});var e=t.outerOrder||ff,r=t.innerOrder||Ef,n=[];return e.forEach(function(s){Kc[s].forEach(function(o){o.name in i&&i[o.name]!=null?n.push(Kn(s,o,i)):o.push in i&&i[o.push]!=null&&i[o.push].forEach(function(a){n.push(Kn(s,o,a))})})}),i.media.forEach(function(s){n.push(Kn("m",Kc.m[0],s)),r.forEach(function(o){Kc[o].forEach(function(a){a.name in s&&s[a.name]!=null?n.push(Kn(o,a,s)):a.push in s&&s[a.push]!=null&&s[a.push].forEach(function(c){n.push(Kn(o,a,c))})})})}),n.join(`\r
73
73
  `)+`\r
74
- `}});var Ic=_e(Jt=>{var DD=_(f()),wi=vl(),V_=bl();Jt.write=V_;Jt.parse=wi.parse;Jt.parseParams=wi.parseParams;Jt.parseFmtpConfig=wi.parseFmtpConfig;Jt.parsePayloads=wi.parsePayloads;Jt.parseRemoteCandidates=wi.parseRemoteCandidates;Jt.parseImageAttributes=wi.parseImageAttributes;Jt.parseSimulcastStreamList=wi.parseSimulcastStreamList});var kc=_e((Bl,Js)=>{var uM=_(f());(function(i){"use strict";function t(A,V){var y=(A&65535)+(V&65535),Y=(A>>16)+(V>>16)+(y>>16);return Y<<16|y&65535}function e(A,V){return A<<V|A>>>32-V}function r(A,V,y,Y,re,Ae){return t(e(t(t(V,A),t(Y,Ae)),re),y)}function n(A,V,y,Y,re,Ae,W){return r(V&y|~V&Y,A,V,re,Ae,W)}function s(A,V,y,Y,re,Ae,W){return r(V&Y|y&~Y,A,V,re,Ae,W)}function o(A,V,y,Y,re,Ae,W){return r(V^y^Y,A,V,re,Ae,W)}function a(A,V,y,Y,re,Ae,W){return r(y^(V|~Y),A,V,re,Ae,W)}function c(A,V){A[V>>5]|=128<<V%32,A[(V+64>>>9<<4)+14]=V;var y,Y,re,Ae,W,x=1732584193,k=-271733879,R=-1732584194,g=271733878;for(y=0;y<A.length;y+=16)Y=x,re=k,Ae=R,W=g,x=n(x,k,R,g,A[y],7,-680876936),g=n(g,x,k,R,A[y+1],12,-389564586),R=n(R,g,x,k,A[y+2],17,606105819),k=n(k,R,g,x,A[y+3],22,-1044525330),x=n(x,k,R,g,A[y+4],7,-176418897),g=n(g,x,k,R,A[y+5],12,1200080426),R=n(R,g,x,k,A[y+6],17,-1473231341),k=n(k,R,g,x,A[y+7],22,-45705983),x=n(x,k,R,g,A[y+8],7,1770035416),g=n(g,x,k,R,A[y+9],12,-1958414417),R=n(R,g,x,k,A[y+10],17,-42063),k=n(k,R,g,x,A[y+11],22,-1990404162),x=n(x,k,R,g,A[y+12],7,1804603682),g=n(g,x,k,R,A[y+13],12,-40341101),R=n(R,g,x,k,A[y+14],17,-1502002290),k=n(k,R,g,x,A[y+15],22,1236535329),x=s(x,k,R,g,A[y+1],5,-165796510),g=s(g,x,k,R,A[y+6],9,-1069501632),R=s(R,g,x,k,A[y+11],14,643717713),k=s(k,R,g,x,A[y],20,-373897302),x=s(x,k,R,g,A[y+5],5,-701558691),g=s(g,x,k,R,A[y+10],9,38016083),R=s(R,g,x,k,A[y+15],14,-660478335),k=s(k,R,g,x,A[y+4],20,-405537848),x=s(x,k,R,g,A[y+9],5,568446438),g=s(g,x,k,R,A[y+14],9,-1019803690),R=s(R,g,x,k,A[y+3],14,-187363961),k=s(k,R,g,x,A[y+8],20,1163531501),x=s(x,k,R,g,A[y+13],5,-1444681467),g=s(g,x,k,R,A[y+2],9,-51403784),R=s(R,g,x,k,A[y+7],14,1735328473),k=s(k,R,g,x,A[y+12],20,-1926607734),x=o(x,k,R,g,A[y+5],4,-378558),g=o(g,x,k,R,A[y+8],11,-2022574463),R=o(R,g,x,k,A[y+11],16,1839030562),k=o(k,R,g,x,A[y+14],23,-35309556),x=o(x,k,R,g,A[y+1],4,-1530992060),g=o(g,x,k,R,A[y+4],11,1272893353),R=o(R,g,x,k,A[y+7],16,-155497632),k=o(k,R,g,x,A[y+10],23,-1094730640),x=o(x,k,R,g,A[y+13],4,681279174),g=o(g,x,k,R,A[y],11,-358537222),R=o(R,g,x,k,A[y+3],16,-722521979),k=o(k,R,g,x,A[y+6],23,76029189),x=o(x,k,R,g,A[y+9],4,-640364487),g=o(g,x,k,R,A[y+12],11,-421815835),R=o(R,g,x,k,A[y+15],16,530742520),k=o(k,R,g,x,A[y+2],23,-995338651),x=a(x,k,R,g,A[y],6,-198630844),g=a(g,x,k,R,A[y+7],10,1126891415),R=a(R,g,x,k,A[y+14],15,-1416354905),k=a(k,R,g,x,A[y+5],21,-57434055),x=a(x,k,R,g,A[y+12],6,1700485571),g=a(g,x,k,R,A[y+3],10,-1894986606),R=a(R,g,x,k,A[y+10],15,-1051523),k=a(k,R,g,x,A[y+1],21,-2054922799),x=a(x,k,R,g,A[y+8],6,1873313359),g=a(g,x,k,R,A[y+15],10,-30611744),R=a(R,g,x,k,A[y+6],15,-1560198380),k=a(k,R,g,x,A[y+13],21,1309151649),x=a(x,k,R,g,A[y+4],6,-145523070),g=a(g,x,k,R,A[y+11],10,-1120210379),R=a(R,g,x,k,A[y+2],15,718787259),k=a(k,R,g,x,A[y+9],21,-343485551),x=t(x,Y),k=t(k,re),R=t(R,Ae),g=t(g,W);return[x,k,R,g]}function d(A){var V,y="",Y=A.length*32;for(V=0;V<Y;V+=8)y+=String.fromCharCode(A[V>>5]>>>V%32&255);return y}function u(A){var V,y=[];for(y[(A.length>>2)-1]=void 0,V=0;V<y.length;V+=1)y[V]=0;var Y=A.length*8;for(V=0;V<Y;V+=8)y[V>>5]|=(A.charCodeAt(V/8)&255)<<V%32;return y}function l(A){return d(c(u(A),A.length*8))}function h(A,V){var y,Y=u(A),re=[],Ae=[],W;for(re[15]=Ae[15]=void 0,Y.length>16&&(Y=c(Y,A.length*8)),y=0;y<16;y+=1)re[y]=Y[y]^909522486,Ae[y]=Y[y]^1549556828;return W=c(re.concat(u(V)),512+V.length*8),d(c(Ae.concat(W),512+128))}function I(A){var V="0123456789abcdef",y="",Y,re;for(re=0;re<A.length;re+=1)Y=A.charCodeAt(re),y+=V.charAt(Y>>>4&15)+V.charAt(Y&15);return y}function T(A){return unescape(encodeURIComponent(A))}function N(A){return l(T(A))}function H(A){return I(N(A))}function U(A,V){return h(T(A),T(V))}function G(A,V){return I(U(A,V))}function Ie(A,V,y){return V?y?U(V,A):G(V,A):y?N(A):H(A)}typeof define=="function"&&define.amd?define(function(){return Ie}):typeof Js=="object"&&Js.exports?Js.exports=Ie:i.md5=Ie})(Bl)});var cx=_(f());var ob=_(f());var uT=_(f(),1);var Kf=_(f(),1),ji="4.15.00.1600",We="5.0.0";function bd(i){We=i;let[t,e,r]=i.split(".").map(n=>parseInt(n,10));ji=`${t}.${Math.min(15,e)}.${Math.min(15,r)}.${e.toString().padStart(2,"0")}${r.toString().padStart(2,"0")}`}var wn=typeof importScripts!="undefined",Bn=typeof registerProcessor!="undefined";var $n="",Hn=i=>$n=i,Ro="web.sdk.qcloud.com",Dd="web.sdk.tencent.cn",Od="web.sdk.cloud.tencent.cn",Fn="https://console.cloud.tencent.com/trtc",Ji=`https://${Ro}/trtc/webrtc/v5/doc`,Yi=`${Ji}/zh-cn/`,Pd="https://yun.tim.qq.com",Md="https://videoapi-sgp.im.qcloud.com",Ld="trtc_error_assistance",Xi={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport"},ei={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},Tt=(o=>(o[o.TRACE=0]="TRACE",o[o.DEBUG=1]="DEBUG",o[o.INFO=2]="INFO",o[o.WARN=3]="WARN",o[o.ERROR=4]="ERROR",o[o.NONE=5]="NONE",o))(Tt||{});var Si={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5},Ao=7*24*3600*1e3;var Co={standard:{sampleRate:48e3,channelCount:1,bitrate:40},"standard-stereo":{sampleRate:48e3,channelCount:2,bitrate:64},high:{sampleRate:48e3,channelCount:1,bitrate:192},"high-stereo":{sampleRate:48e3,channelCount:2,bitrate:192}},zi={"120p":{width:160,height:120,frameRate:15,bitrate:200},"180p":{width:320,height:180,frameRate:15,bitrate:350},"240p":{width:320,height:240,frameRate:15,bitrate:400},"360p":{width:640,height:360,frameRate:15,bitrate:800},"480p":{width:640,height:480,frameRate:15,bitrate:900},"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}},yo={"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}},m={CANVAS:"canvas",AUDIO:"audio",VIDEO:"video",SCREEN:"screen",SMALL:"small",BIG:"big",AUXILIARY:"auxiliary",SMALL_VIDEO:"smallVideo",FACING_MODE_USER:"user",FACING_MODE_ENVIRONMENT:"environment",MUTE:"mute",UNMUTE:"unmute",ENDED:"ended",PLAYING:"playing",PAUSE:"pause",ERROR:"error",LOADEDDATA:"loadeddata",AUDIO_INPUT:"audioinput",VIDEO_INPUT:"videoinput",DETAIL:"detail",TEXT:"text",MAIN:"main",BACKUP:"backup",BANNED:"banned",KICK:"kick",USER_TIME_OUT:"user_time_out",ROOM_DISBAND:"room_disband",SEI_MESSAGE:"sei-message",ADD:"add",REMOVE:"remove",REPLACE:"replace",TRACK:"track",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",TRANSCEIVER_DIRECTION_SENDONLY:"sendonly",TRANSCEIVER_DIRECTION_RECVONLY:"recvonly"},se={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},vo={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"};var Dr=1,kd=2,Gn=4,Or=8,No=64,bo=16,Wn="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",xd="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",Ud=m.MAIN,Kn=m.AUXILIARY;var St="unknown",fe={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},Vd=1/0;function wd(i){Vd=i}function ti(){return Vd}var jn=30,Lt={JOIN:"join",DELTA_JOIN:"delta-join",REJOIN:"rejoin",LEAVE:"leave",DELTA_LEAVE:"delta-leave",PUBLISH:"publish",DELTA_PUBLISH:"delta-publish",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",UPLINK_CONNECTION:"uplink-connection",UPLINK_RECONNECTION:"uplink-reconnection",DOWNLINK_CONNECTION:"downlink-connection",DOWNLINK_RECONNECTION:"downlink-reconnection",ON_TRACK:"ontrack",ICE_CONNECTION_STATE:"iceConnectionState",LOCAL_STREAM_INITIALIZE:"stream-initialize",SIGNAL_CONNECTION:"websocketConnectionState",SIGNAL_RECONNECTION:"websocketReconnectionState",UPDATE_STREAM:"update-stream",RECOVER_LOCAL_AUDIO_TRACK:"recover-local-audio-track",RECOVER_LOCAL_VIDEO_TRACK:"recover-local-video-track",RECOVER_SUBSCRIPTION:"recover-subscription",START_MIX_TRANSCODE:"start-mix-transcode",STOP_MIX_TRANSCODE:"stop-mix-transcode",PLAYER_ERROR:"player-error",SCHEDULE:"schedule",LOAD_WORKLET:"load-worklet",VIDEO_FROZEN_COUNT:"videoFrozenCount"};var Bd=1e4,$d=1e4,gi="unified-plan",Pr="plan-b",Ii={MODE:{MANUAL:"manual",PRESET_LAYOUT:"preset-layout"},PLACE_HOLDER:{REMOTE:"$PLACE_HOLDER_REMOTE$"},STREAM_TYPE:{IT_AUDIO_VIDEO:0,IT_PICTURE:2,IT_CANVAS:3,IT_PURE_AUDIO:4,IT_PURE_VIDEO:5}},D={String:"string",Number:"number",Boolean:"boolean",Array:"array",Object:"object"},qi=1028;var Do=500;var Hf=m.BIG,Ff=m.SMALL,Jn=10*1e3,Mr={MAIN:"schedule.rtc.qq.com",BACKUP:"schedule.rtc.qcloud.com",MAIN_OVERSEA:"schedule.rtc.tencentcloud.com",BACKUP_OVERSEA:"schedule-ecdn.rtc.tencentcloud.com"};var Hd=5,Qi="default",Yn=Qi;var Gf=Object.keys(Tt),Fd=["normal leave","timeout leave","kick","role change"],Lr=10,kr=2e3,kt="ric",ii="raf",Gd="interval",xr="timeout";var sT=_(f(),1);var Yf=_(f(),1);var Wd=new Date().getTime(),Oo=0,Kd=function(i){Wd=i,Oo=Wd-new Date().getTime();let t=new Date;t.setTime(i),M.info(`baseTime from server: ${t} offset: ${Oo}`)},Ur=function(){return new Date().getTime()+Oo},Xn=function(){let i=new Date;return i.setTime(Ur()),i.toLocaleString()};var Ke={};oo(Ke,{bytes2ms:()=>pm,catchEmitterError:()=>Qo,copyProperties:()=>lm,deepMerge:()=>yt,fibonacci:()=>ir,formatedTime:()=>gm,getConstructorName:()=>ps,getContainerFromElement:()=>hs,getEnv:()=>dm,getInternalVersion:()=>_m,getLoggerUrl:()=>Ci,getMuteStateFromFlag:()=>oi,getNetworkQuality:()=>Em,getNetworkType:()=>us,getOSType:()=>nu,getReconnectionTimeout:()=>rt,getSysInfo:()=>um,getTerminalType:()=>ru,getTurnServer:()=>Tm,getValueType:()=>Te,glog:()=>au,ipv4ToUint32:()=>Zr,isArray:()=>Ve,isArrayOrObject:()=>zr,isAudioWorkletSupported:()=>zo,isBoolean:()=>be,isConstructor:()=>qr,isEmpty:()=>Qr,isFunction:()=>ue,isLangChinese:()=>Ct,isMediaStreamTrack:()=>mm,isNumber:()=>de,isObject:()=>yi,isOverseaSdkAppId:()=>ds,isPlainObject:()=>ni,isPromise:()=>ls,isRemoteTrack:()=>si,isString:()=>oe,isUndefined:()=>b,ms2bytes:()=>hm,ms2samples:()=>ou,performanceNow:()=>q,promiseAny:()=>qo,samples2ms:()=>su,tryCatchFunction:()=>Xo});var bE=_(f(),1);var sE=_(f(),1);var gt=typeof navigator=="undefined"?"":navigator.userAgent,ie=i=>new RegExp(i,"i").test(gt),ye=i=>{if(ie(i)){let t=new RegExp(`${i}\\/([\\d.]+)`),e=gt.match(t);if(e&&e[1])return e[1]}return""},Po=i=>{if(ie(i)){let t=new RegExp(`${i}\\/(\\d+)`),e=gt.match(t);if(e&&e[1])return parseFloat(e[1])}return NaN},jd=/AppleWebKit\/([\d.]+)/i.exec(gt),em=jd?parseFloat(jd[1]):NaN,wr=ie("iPad"),Jd=typeof navigator!="undefined"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&ie("Macintosh"),Ri=ie("iPhone")&&!wr,tm=ie("iPod"),It=Ri||wr||tm||Jd,ut=ie("Android"),Yd=function(){if(ut){let i=gt.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(i){let t=i[1]&&parseFloat(i[1]),e=i[2]&&parseFloat(i[2]);if(t&&e)return parseFloat(`${i[1]}.${i[2]}`);if(t)return t}}return NaN}(),zf=ut&&ie("webkit")&&Yd<2.3,qf=ut&&Yd<5&&em<537,pe=ie("Firefox"),Mo=ye("Firefox"),Xd=Po("Firefox"),Br=ie("Edge"),Lo=ye("Edge"),$r=ie("Edg"),ko=ye("Edg"),zd=Po("Edg"),zn=ie("SogouMobileBrowser"),xo=ye("SogouMobileBrowser"),qn=ie("MetaSr\\s"),Uo=ye("MetaSr\\s"),xt=ie("TBS"),Vo=ye("TBS"),Qn=ie("XWEB"),wo=ye("XWEB"),Qf=ie("MSIE\\s8\\.0"),im=ie("MSIE\\/\\d+"),Zf=function(){if(im){let i=/MSIE\s(\d+)\.\d/.exec(gt),t=i&&parseFloat(i[1]);return!t&&/Trident\/7.0/i.test(gt)&&/rv:11.0/.test(gt)&&(t=11),t}return NaN}(),Hr=ie("(micromessenger|webbrowser)"),Bo=ye("MicroMessenger"),Fr=!xt&&ie("MQQBrowser")&&ie("COVC"),Gr=!xt&&ie("MQQBrowser")&&!ie("COVC"),Vr=Gr||Fr?ye("MQQBrowser"):"",Zn=!xt&&ie(" QQBrowser"),$o=ye(" QQBrowser"),es=!xt&&ie("QQBrowserLite"),Ho=ye("QQBrowserLite"),ts=!xt&&ie("MQBHD"),Fo=ye("MQBHD"),Wr=ie("Windows"),Ut=!It&&ie("MAC OS X"),Kr=!ut&&ie("Linux"),eE=ie("MicroMessenger"),qd=ie("UCBrowser"),tE=ie("Electron"),is=ie("MiuiBrowser"),Go=ye("MiuiBrowser"),rs=ie("HuaweiBrowser"),iE=ie("Huawei"),Wo=ye("HuaweiBrowser"),ns=ie("SamsungBrowser"),Ko=ye("SamsungBrowser"),ss=ie("HeyTapBrowser"),jo=ye("HeyTapBrowser"),os=ie("VivoBrowser"),Jo=ye("VivoBrowser"),jr=()=>Po("Chrome"),Qd=ie("Chrome"),Jr=!Br&&!qn&&!zn&&!xt&&!Qn&&!$r&&!Zn&&!is&&!rs&&!ns&&!ss&&!os&&Qd,Zd=ie("HeadlessChrome"),Yr=jr(),Yo=ye("Chrome"),Vt=!Qd&&!Gr&&!Fr&&!es&&!ts&&ie("Safari");var Xr=ye("Safari"),rE=/Android.*(wv|.0.0.0)/.test(gt),Zi=(()=>{if(Jd)return Xr;if(It){let i=gt.match(/OS (\d+)_(\d+)/i);if(i&&i[1]){let t=i[1];return i[2]&&(t+=`.${i[2]}`),t}}return""})(),as=Xr==="15.1",er=Zi==="15.1",nE=(()=>{let i=Number(Zi.split(".")[0]);return i===14||i===13})(),Rt=typeof location!="undefined"?location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1":!1,ri=(()=>{let i;return()=>{if(b(i))try{i=!!window.localStorage}catch(t){i=!1}return i}})(),tr=rm();function rm(){let i=new Map([[pe,["Firefox",Mo]],[$r,["Edg",ko]],[Jr,["Chrome",Yo]],[Vt,["Safari",Xr]],[xt,["TBS",Vo]],[Qn,["XWEB",wo]],[Hr&&Ri,["WeChat",Bo]],[Zn,["QQ(Win)",$o]],[Gr,["QQ(Mobile)",Vr]],[Fr,["QQ(Mobile X5)",Vr]],[es,["QQ(Mac)",Ho]],[ts,["QQ(iPad)",Fo]],[is,["MI",Go]],[rs,["HW",Wo]],[ns,["Samsung",Ko]],[ss,["OPPO",jo]],[os,["VIVO",Jo]],[Br,["EDGE",Lo]],[zn,["SogouMobile",xo]],[qn,["Sogou",Uo]]]),t="unknown",e="unknown";return i.has(!0)&&([t,e]=i.get(!0)),{name:t,version:e}}var IE=_(f(),1);var pE=_(f(),1);var aE=_(f(),1);var Ai=1e8;var w={AVOID_REPEATED_CALL:"AVOID_REPEATED_CALL",INVALID_PARAMETER_REQUIRED:"INVALID_PARAMETER_REQUIRED",INVALID_PARAMETER_TYPE:"INVALID_PARAMETER_TYPE",INVALID_PARAMETER_EMPTY:"INVALID_PARAMETER_EMPTY",INVALID_PARAMETER_INSTANCE:"INVALID_PARAMETER_INSTANCE",INVALID_PARAMETER_RANGE:"INVALID_PARAMETER_RANGE",INVALID_PARAMETER_MIN:"INVALID_PARAMETER_MIN",INVALID_PARAMETER_MAX:"INVALID_PARAMETER_MAX",INVALID_PARAMETER_STREAMTYPE:"INVALID_PARAMETER_STREAMTYPE",API_CALL_TIMEOUT:"API_CALL_TIMEOUT",SIGNAL_CHANNEL_RECONNECTION_FAILED:"SIGNAL_CHANNEL_RECONNECTION_FAILED",SIGNAL_CHANNEL_SETUP_FAILED:"SIGNAL_CHANNEL_SETUP_FAILED",ERROR_MESSAGE:"ERROR_MESSAGE",EXCHANGE_SDP_TIMEOUT:"EXCHANGE_SDP_TIMEOUT",DOWNLINK_RECONNECTION_FAILED:"DOWNLINK_RECONNECTION_FAILED",EXCHANGE_SDP_FAILED:"EXCHANGE_SDP_FAILED",UPDATE_OFFER_TIMEOUT:"UPDATE_OFFER_TIMEOUT",UPLINK_RECONNECTION_FAILED:"UPLINK_RECONNECTION_FAILED",INVALID_RECORDID:"INVALID_RECORDID",INVALID_PURE_AUDIO:"INVALID_PURE_AUDIO",INVALID_STREAMID:"INVALID_STREAMID",INVALID_USER_DEFINE_RECORDID:"INVALID_USER_DEFINE_RECORDID",INVALID_USER_DEFINE_PUSH_ARGS:"INVALID_USER_DEFINE_PUSH_ARGS",INVALID_PROXY:"INVALID_PROXY",INVALID_JOIN:"INVALID_JOIN",INVALID_ROOMID_STRING:"INVALID_ROOMID_STRING",INVALID_ROOMID_INTEGER:"INVALID_ROOMID_INTEGER",INVALID_SIGNAL_CHANNEL:"INVALID_SIGNAL_CHANNEL",JOIN_ROOM_TIMEOUT:"JOIN_ROOM_TIMEOUT",JOIN_ROOM_FAILED:"JOIN_ROOM_FAILED",REJOIN_ROOM_FAILED:"REJOIN_ROOM_FAILED",INVALID_DESTROY:"INVALID_DESTROY",INVALID_PUBLISH:"INVALID_PUBLISH",INVALID_UNPUBLISH:"INVALID_UNPUBLISH",INVALID_AUDIENCE:"INVALID_AUDIENCE",INVALID_INITIALIZE:"INVALID_INITIALIZE",INVALID_DUPLICATE_PUBLISHING:"INVALID_DUPLICATE_PUBLISHING",INVALID_SUBSCRIBE_UNDEFINED:"INVALID_SUBSCRIBE_UNDEFINED",INVALID_SUBSCRIBE_LOCAL:"INVALID_SUBSCRIBE_LOCAL",INVALID_REMOTE_STREAM:"INVALID_REMOTE_STREAM",SUBSCRIBE_FAILED:"SUBSCRIBE_FAILED",INVALID_ROLE:"INVALID_ROLE",INVALID_PARAMETER_SWITCH_ROLE:"INVALID_PARAMETER_SWITCH_ROLE",INVALID_OPERATION_SWITCH_ROLE:"INVALID_OPERATION_SWITCH_ROLE",SWITCH_ROLE_TIMEOUT:"SWITCH_ROLE_TIMEOUT",SWITCH_ROLE_FAILED:"SWITCH_ROLE_FAILED",CLIENT_BANNED:"CLIENT_BANNED",INVALID_OPERATION_START_PUBLISH_CDN:"INVALID_OPERATION_START_PUBLISH_CDN",INVALID_OPERATION_STOP_PUBLISH_CDN:"INVALID_OPERATION_STOP_PUBLISH_CDN",INVALID_STREAM_ID:"INVALID_STREAM_ID",START_PUBLISH_CDN_FAILED:"START_PUBLISH_CDN_FAILED",STOP_PUBLISH_CDN_FAILED:"STOP_PUBLISH_CDN_FAILED",START_MIX_TRANSCODE:"START_MIX_TRANSCODE",STOP_MIX_TRANSCODE:"STOP_MIX_TRANSCODE",INVALID_AUDIO_VOLUME:"INVALID_AUDIO_VOLUME",ENABLE_SMALL_STREAM_PUBLISHED:"ENABLE_SMALL_STREAM_PUBLISHED",DISABLE_SMALL_STREAM_PUBLISHED:"DISABLE_SMALL_STREAM_PUBLISHED",NOT_SUPPORTED_SMALL_STREAM:"NOT_SUPPORTED_SMALL_STREAM",INVALID_SMALL_STREAM_PROFILE:"INVALID_SMALL_STREAM_PROFILE",INVALID_PARAMETER_REMOTE_STREAM:"INVALID_PARAMETER_REMOTE_STREAM",INVALID_OPERATION_CHANGE_SMALL:"INVALID_OPERATION_CHANGE_SMALL",REMOTE_NOT_PUBLISH_SMALL_STREAM:"REMOTE_NOT_PUBLISH_SMALL_STREAM",INVALID_SWITCH_DEVICE:"INVALID_SWITCH_DEVICE",INVALID_SWITCH_DEVICE_PUBLISHING:"INVALID_SWITCH_DEVICE_PUBLISHING",INVALID_REPLACE_TRACK:"INVALID_REPLACE_TRACK",INVALID_INITIALIZE_LOCAL_STREAM:"INVALID_INITIALIZE_LOCAL_STREAM",INVALID_ADD_TRACK_REPETITIVE:"INVALID_ADD_TRACK_REPETITIVE",INVALID_ADD_TRACK_REMOVING:"INVALID_ADD_TRACK_REMOVING",INVALID_ADD_TRACK_PUBLISHING:"INVALID_ADD_TRACK_PUBLISHING",INVALID_STREAM_INITIALIZED:"INVALID_STREAM_INITIALIZED",INVALID_ADD_TRACK_NUMBER:"INVALID_ADD_TRACK_NUMBER",INVALID_REMOVE_AUDIO_TRACK:"INVALID_REMOVE_AUDIO_TRACK",INVALID_REMOVE_AUDIO_ADDING:"INVALID_REMOVE_AUDIO_ADDING",INVALID_REMOVE_AUDIO_ON:"INVALID_REMOVE_AUDIO_ON",INVALID_REMOVE_TRACK_PUBLISHING:"INVALID_REMOVE_TRACK_PUBLISHING",INVALID_REMOVE_TRACK_NOT_TRACK:"INVALID_REMOVE_TRACK_NOT_TRACK",INVALID_REMOVE_TRACK_NUMBER:"INVALID_REMOVE_TRACK_NUMBER",INVALID_REPLACE_TRACK_NO_TRACK:"INVALID_REPLACE_TRACK_NO_TRACK",REPEAT_JOIN:"REPEAT_JOIN",CLIENT_DESTROYED:"CLIENT_DESTROYED",START_MIX_TRANSCODE_FAILED:"START_MIX_TRANSCODE_FAILED",STOP_MIX_TRANSCODE_FAILED:"STOP_MIX_TRANSCODE_FAILED",MIX_TRANSCODE_NOT_STARTED:"MIX_TRANSCODE_NOT_STARTED",CANNOT_LESS_THAN_ZERO:"CANNOT_LESS_THAN_ZERO",MIX_PARAMS_VIDEO_FRAMERATE:"MIX_PARAMS_VIDEO_FRAMERATE",MIX_PARAMS_VIDEO_GOP:"MIX_PARAMS_VIDEO_GOP",MIX_PARAMS_AUDIO_BITRATE:"MIX_PARAMS_AUDIO_BITRATE",MIX_PARAMS_USER_Z_ORDER:"MIX_PARAMS_USER_Z_ORDER",MIX_PARAMS_NOT_SELF:"MIX_PARAMS_NOT_SELF",MIX_PARAMS_USER_STREAM:"MIX_PARAMS_USER_STREAM",INVALID_PLAY:"INVALID_PLAY",INVALID_ELEMENT_ID:"INVALID_ELEMENT_ID",INVALID_ELEMENT_ID_TYPE:"INVALID_ELEMENT_ID_TYPE",PLAY_FAILED:"PLAY_FAILED",INVALID_USERID:"INVALID_USERID",INVALID_CREATE_STREAM_SOURCE:"INVALID_CREATE_STREAM_SOURCE",INVALID_CREATE_STREAM_SCREEN:"INVALID_CREATE_STREAM_SCREEN",INVALID_CREATE_STREAM_AUDIO:"INVALID_CREATE_STREAM_AUDIO",INVALID_CREATE_STREAM_SCREEN_AUDIO:"INVALID_CREATE_STREAM_SCREEN_AUDIO",NOT_SUPPORTED_HTTP:"NOT_SUPPORTED_HTTP",NOT_SUPPORTED_WEBRTC:"NOT_SUPPORTED_WEBRTC",NOT_SUPPORTED_PROFILE:"NOT_SUPPORTED_PROFILE",NOT_SUPPORTED_MEDIA:"NOT_SUPPORTED_MEDIA",NOT_SUPPORTED_H264ENCODE:"NOT_SUPPORTED_H264ENCODE",NOT_SUPPORTED_H264DECODE:"NOT_SUPPORTED_H264DECODE",NOT_SUPPORTED_TRACK:"NOT_SUPPORTED_TRACK",NOT_SUPPORTED_SWITCH_DEVICE:"NOT_SUPPORTED_SWITCH_DEVICE",NOT_SUPPORTED_CAPTURE:"NOT_SUPPORTED_CAPTURE",NOT_SUPPORTED_AUX:"NOT_SUPPORTED_AUX",MICROPHONE_NOT_FOUND:"MICROPHONE_NOT_FOUND",CAMERA_NOT_FOUND:"CAMERA_NOT_FOUND",SIGNAL_RESPONSE_FAILED:"SIGNAL_RESPONSE_FAILED",CATCH_HANDLER_ERROR:"CATCH_HANDLER_ERROR",API_NOT_EXIST:"API_NOT_EXIST",CONNECTION_CLOSED:"CONNECTION_CLOSED",SUBSCRIBE_ALL_FALSE:"SUBSCRIBE_ALL_FALSE",SEI_NOT_SUPPORT:"SEI_NOT_SUPPORT",SEI_DISABLED:"SEI_DISABLED",SEI_EMPTY:"SEI_EMPTY",SEI_OVERSIZE:"SEI_OVERSIZE",SEI_BEFORE_PUBLISH:"SEI_BEFORE_PUBLISH",SEI_NOT_VIDEO:"SEI_NOT_VIDEO",CALL_FREQUENCY_LIMIT:"CALL_FREQUENCY_LIMIT",CONNECTION_ABORTED:"CONNECTION_ABORTED",API_CALL_ABORTED:"API_CALL_ABORTED",DUPLICATE_AUX:"DUPLICATE_AUX"},Le={AVOID_REPEATED_CALL(i){return`previous ${i.name}() is ongoing, please avoid repeated calls.`},INVALID_PARAMETER_REQUIRED({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' is a required param when calling ${e}(), received: ${r}.`},INVALID_PARAMETER_TYPE({key:i,rule:t,fnName:e,value:r}){let n=`${i||t.name}`,s="";return Array.isArray(t.type)?s=t.type.join("|"):s=t.type,`'${n}' must be type of ${s} when calling ${e}(), received type: ${Te(r)}.`},INVALID_PARAMETER_EMPTY({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' cannot be '${r}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:i,rule:t,fnName:e,value:r}){let n=`${i||t.name}`,s=`${t.instanceOf.name||t.instanceOf}`;return`'${n}' must be instanceof ${s} when calling ${e}(), received type: ${Te(r)}.`},INVALID_PARAMETER_RANGE({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' must be one of ${t.values.join("|")} when calling ${e}(), received: ${r}.`},INVALID_PARAMETER_MIN({key:i,rule:t,fnName:e,value:r}){return`the min value of ${i||t.name} is ${t.min}, received: ${r}.`},INVALID_PARAMETER_MAX({key:i,rule:t,fnName:e,value:r}){return`the max value of ${i||t.name} is ${t.max}, received: ${r}.`},API_CALL_TIMEOUT(i){return`${i.commandDesc||i.command} timeout observed.`},SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED(i){return`SignalChannel setup failure: (errorCode: ${i.errorCode}, errorMsg: ${i.errorMsg} }).`},ERROR_MESSAGE(i){let t=`${i.type} failed`;return i.message&&(t=`${t}: ${i.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(i){return`exchange sdp failed ${i.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(i){return`'${i}' must be validate string when useStringRoomId is true.`},INVALID_ROOMID_INTEGER(i){return`'${i}' 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:i,code:t}){return`Failed to join room - ${i} code: ${t}`},REJOIN_ROOM_FAILED(i){return`reJoin room: ${i.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(i){return`duplicate ${i} stream publishing, please unpublish your prev ${i} 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:i,userId:t,streamType:e}){return`failed to subscribe ${t} ${e} stream, reason: ${i}.`},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(i){return`switchRole failed, errCode: ${i.code} errMsg: ${i.message}.`},CLIENT_BANNED(i){return`client was banned because of ${i.message}.`},INVALID_OPERATION_START_PUBLISH_CDN:"please call startPublishCDNStream() after join room and publish the local stream.",INVALID_OPERATION_STOP_PUBLISH_CDN:"please call startPublishCDNStream() before stopPublishCDNStream().",START_PUBLISH_CDN_FAILED(i){return`startPublishCDNStream failed, errMsg: ${i.message}.`},STOP_PUBLISH_CDN_FAILED(i){return`stopPublishCDNStream failed, errMsg: ${i.message}.`},INVALID_STREAM_ID(i){return`'${i}' 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_TRACK:"localStream has not this track.",INVALID_REMOVE_TRACK_NUMBER:"remove the only video track is not supported, please use replaceTrack or muteVideo.",INVALID_REPLACE_TRACK_NO_TRACK(i){return`cannot replace ${i.kind} track because stream has not ${i.kind} track`},START_MIX_TRANSCODE_FAILED(i){return`startMixTranscode failed, errMsg: ${i.message}.`},STOP_MIX_TRANSCODE_FAILED(i){return`stopMixTranscode failed, errMsg: ${i.message}.`},MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' cannot be less than 0 when calling ${e}().`},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(i){return`'${i}' 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:i,fnName:t})=>`'${i}' is not found in the document object when calling ${t}().`,INVALID_ELEMENT_ID_TYPE:({key:i,fnName:t,type:e})=>`the element corresponding to '${i}' must be instanceof HTMLElement when calling ${t}(), received: ${e}.`,PLAY_FAILED:i=>`${i.media} play failed\uFF0Cbrowser exception: ${i.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(i){return`${i}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(i){return`${i.signalResponse} failed, response code is ${i.code} , errMsg: ${i.message}.`},CATCH_HANDLER_ERROR({name:i,event:t}){return`an error was caught on ${i}.on('${t}', handler), please check your code on 'handler'.`},API_NOT_EXIST({name:i}){return`experimental api ${i} does not exist.`},REPEAT_JOIN:i=>`[${i}] 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:i}){return`failed to call ${i}() because client was destroyed.`},SEI_NOT_SUPPORT:i=>`not support to sendSEIMessage${i===!1?" without using h264 codec":""}`,SEI_DISABLED:"SEI is disabled, to enable SEI: TRTC.createClient({ enableSEI: true })",SEI_EMPTY:"buffer cannot be empty",SEI_OVERSIZE:i=>`buffer size(${i}) 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:i,name:t,timesInSecond:e,maxSizeInSecond:r})=>`api ${t} call ${i?"size":"times"} is over ${i?`${r} bytes`:e} in a second.`,CONNECTION_ABORTED(i){return`connection aborted due to: ${i}`},API_CALL_ABORTED(i){let t;return i.message.includes("REMOTE_STREAM_NOT_EXIST")?t=`Subscribe ${i.userId} ${i.streamType} stream aborted, reason: remote user ${i.userId} unpublished stream.`:t=`API aborted, reason: ${i.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.",INVALID_PARAMETER_STREAMTYPE:i=>`'streamType' is required when 'userId' is not '*', calling ${i}()`};var hE=_(f());function eu(i){return Reflect.apply(Object.prototype.toString,i,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var nm={AVOID_REPEATED_CALL(i){return`\u524D\u4E00\u4E2A ${i.name}() \u8C03\u7528\u6B63\u5728\u8FDB\u884C\u4E2D, \u8BF7\u907F\u514D\u91CD\u590D\u8C03\u7528\u3002`},INVALID_PARAMETER_REQUIRED({key:i,rule:t,fnName:e,value:r}){return`\u8C03\u7528 ${e}() \u65B9\u6CD5\u7684\u65F6\u5019 '${i||t.name}' \u662F\u5FC5\u987B\u7684\u53C2\u6570, \u6536\u5230\u7684\u503C\u4E3A: ${r}\u3002`},INVALID_PARAMETER_TYPE({key:i,rule:t,fnName:e,value:r}){let n=`${i||t.name}`,s="";return Array.isArray(t.type)?s=t.type.join("|"):s=t.type,`\u8C03\u7528 ${e}() \u65B9\u6CD5\u7684\u65F6\u5019 '${n}' \u5FC5\u987B\u662F ${s} \u7C7B\u578B, \u6536\u5230\u7684\u7C7B\u578B\u662F: ${eu(r)}\u3002`},INVALID_PARAMETER_EMPTY({key:i,rule:t,fnName:e,value:r}){return`\u8C03\u7528 ${e}() \u7684\u65F6\u5019 '${i||t.name}' \u4E0D\u80FD\u662F '${r}'\u3002`},INVALID_PARAMETER_INSTANCE({key:i,rule:t,fnName:e,value:r}){let n=`${i||t.name}`,s=`${t.instanceOf.name||t.instanceOf}`;return`\u8C03\u7528 ${e}() \u7684\u65F6\u5019 '${n}' \u539F\u578B\u5FC5\u987B\u662F ${s} , \u6536\u5230\u7684\u662F: ${eu(r)}\u3002`},INVALID_PARAMETER_RANGE({key:i,rule:t,fnName:e,value:r}){return`\u8C03\u7528 ${e}() \u7684\u65F6\u5019 '${i||t.name}' \u5FC5\u987B\u662F ${t.values.join("|")} \u7684\u5176\u4E2D\u4E00\u79CD, \u6536\u5230\u7684\u662F: ${r}\u3002`},API_CALL_TIMEOUT(i){return`${i.commandDesc||i.command} \u8D85\u65F6\u3002`},SIGNAL_CHANNEL_RECONNECTION_FAILED:"\u4FE1\u4EE4\u901A\u9053\u91CD\u8FDE\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u4F60\u7684\u7F51\u7EDC\u3002",SIGNAL_CHANNEL_SETUP_FAILED(i){return`\u4FE1\u4EE4\u901A\u9053\u5EFA\u7ACB\u5931\u8D25: (\u9519\u8BEF\u7801: ${i.errorCode}, \u9519\u8BEF\u4FE1\u606F: ${i.errorMsg} })\u3002`},ERROR_MESSAGE(i){let t=`${i.type} \u5931\u8D25\u3002`;return i.message&&(t=`${t}: ${i.message}\u3002`),t},SUBSCRIPTION_TIMEOUT:"\u8FDC\u7A0B\u670D\u52A1\u5668\u4E0D\u54CD\u5E94\u8BA2\u9605\u884C\u4E3A\u3002",EXCHANGE_SDP_TIMEOUT:"\u4EA4\u6362 sdp \u8D85\u65F6\uFF0C\u8BF7\u5237\u65B0\u7F51\u7EDC\u91CD\u8BD5\u3002",DOWNLINK_RECONNECTION_FAILED:"\u4E0B\u884C\u91CD\u8FDE\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u60A8\u7684\u7F51\u7EDC\u5E76\u91CD\u65B0\u52A0\u5165\u623F\u95F4\u3002",EXCHANGE_SDP_FAILED(i){return`\u4EA4\u6362 SDP \u5931\u8D25\uFF0C\u539F\u56E0 ${i.errMsg}\u3002`},REPLACE_TRACK_INVALID:"LocalStream \u53D1\u5E03\u4E4B\u540E\u624D\u53EF\u4EE5\u8C03\u7528 replaceTrack\u3002",UPDATE_OFFER_TIMEOUT:"\u66F4\u65B0 offer \u8D85\u65F6\uFF0C\u8BF7\u5237\u65B0\u7F51\u7EDC\u91CD\u8BD5\u3002",UPLINK_RECONNECTION_FAILED:"\u4E0A\u884C\u91CD\u8FDE\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u60A8\u7684\u7F51\u7EDC\u5E76\u91CD\u65B0\u63A8\u6D41\u3002",INVALID_RECORDID:"recordId \u5FC5\u987B\u662F\u6570\u5B57\u3002",INVALID_PURE_AUDIO:"pureAudioPushMode \u5FC5\u987B\u662F\u6570\u5B571\u62162\u3002",INVALID_STREAMID:"streamId \u5FC5\u987B\u662F 64 \u5B57\u8282\u4EE5\u5185\u7684\u5B57\u7B26\u4E32\uFF0C\u5E76\u4E14\u4E0D\u80FD\u4E3A\u7A7A\u3002",INVALID_USER_DEFINE_RECORDID:"userDefineRecordId \u5FC5\u987B\u662F\u5305\u542B (a-zA-Z)\u3001(0-9)\u3001\u4E0B\u5212\u7EBF\u548C\u8FDE\u5B57\u7B26\u7684\u5B57\u7B26\u4E32\u5B57\u9762\u91CF\uFF0C64 \u4E2A\u5B57\u8282\u4EE5\u5185\uFF0C\u4E14\u4E0D\u4E3A\u7A7A\u3002",INVALID_USER_DEFINE_PUSH_ARGS:"userDefinePushArgs \u5FC5\u987B\u662F 256 \u5B57\u8282\u4EE5\u5185\u7684\u5B57\u7B26\u4E32\u6587\u5B57\uFF0C\u5E76\u4E14\u4E0D\u80FD\u4E3A\u7A7A\u3002",INVALID_PROXY:"\u4EE3\u7406\u670D\u52A1\u5668 url \u5FC5\u987B\u4EE5\u201Cwss://\u201D\u5F00\u5934\u3002",INVALID_JOIN:"join() \u65B9\u6CD5\u4E0D\u80FD\u88AB\u91CD\u590D\u8C03\u7528\u3002",INVALID_ROOMID_STRING(i){return`\u5F53 useStringRoomId \u4E3A true \u65F6\uFF0C'${i}' \u5FC5\u987B\u662F\u5408\u6CD5\u5B57\u7B26\u4E32\u3002`},INVALID_ROOMID_INTEGER(i){return`\u5F53 useStringRoomId \u4E3A false \u65F6\uFF0C'${i}' \u5FC5\u987B\u662F\u5408\u6CD5\u6574\u6570\u5728\u533A\u95F4[1, 4294967294]\u3002`},INVALID_SIGNAL_CHANNEL:"SignalChannel \u8FD8\u672A\u521D\u59CB\u5316\u597D\u3002",JOIN_ROOM_TIMEOUT:"\u8FDB\u623F\u8D85\u65F6\u3002",JOIN_ROOM_FAILED(i){return`\u8FDB\u623F\u5931\u8D25\uFF0C\u539F\u56E0\uFF1A${i.error}\u3002`},REJOIN_ROOM_FAILED(i){return`\u91CD\u8FDB\u623F: ${i.roomId} \u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC\u72B6\u51B5\u3002`},INVALID_LEAVE:"\u8BF7\u5728\u8C03\u7528 destroy() \u65B9\u6CD5\u4E4B\u524D\u8C03\u7528 leave()\u3002",INVALID_PUBLISH:"\u8BF7\u5728\u8C03\u7528 publish() \u65B9\u6CD5\u4E4B\u524D\u8C03\u7528 join()\u3002",INVALID_UNPUBLISH:"\u8FD8\u6CA1\u6709\u88AB publish\u3002",INVALID_AUDIENCE:"\u5728\u89C2\u4F17\u6A21\u5F0F\u4E0B\u4E0D\u5141\u8BB8\u8C03\u7528 publish()\uFF0C\u8BF7\u5148\u5207\u6362\u6210\u4E3B\u64AD\u6A21\u5F0F\u3002",INVALID_INITIALIZE:"\u65E0\u6CD5\u53D1\u5E03 stream\uFF0C\u539F\u56E0\uFF1AlocalStream \u672A\u521D\u59CB\u5316\u3001\u6B63\u5728\u5207\u6362\u8BBE\u5907\u3001\u5DF2\u7ECF\u8C03\u7528 localStream.close() \u5173\u95ED\u91C7\u96C6",INVALID_DUPLICATE_PUBLISHING:"\u91CD\u590D\u53D1\u5E03\uFF0C\u8BF7\u5148 unpublish \u4E4B\u540E\uFF0C\u518D\u91CD\u65B0 publish\u3002",INVALID_SUBSCRIBE_UNDEFINED:"stream \u53C2\u6570\u662F undefined \u6216\u8005 null\u3002",INVALID_SUBSCRIBE_LOCAL:"stream \u53C2\u6570\u4E0D\u80FD\u4E3A\u672C\u5730\u6D41\u3002",INVALID_REMOTE_STREAM:"remoteStream \u4E0D\u5B58\u5728\uFF0C\u5DF2\u88AB\u8FDC\u7AEF client \u53D6\u6D88\u53D1\u5E03\u3002",SUBSCRIBE_FAILED(i){let t="\u8BA2\u9605\u6D41\u5931\u8D25\uFF0C\u539F\u56E0: ";return i.message.includes("REMOTE_STREAM_NOT_EXIST")?t+="\u8FDC\u7AEF\u7528\u6237\u5DF2\u53D6\u6D88\u63A8\u6D41\uFF0C\u65E0\u6CD5\u8BA2\u9605\u8BE5\u8FDC\u7AEF\u6D41\u3002":t+=`${i.message}\u3002`,t},INVALID_ROLE:"\u53EA\u6709\u76F4\u64AD\u6A21\u5F0F\u624D\u53EF\u4EE5\u8FDB\u884C\u89D2\u8272\u5207\u6362\u3002",INVALID_PARAMETER_SWITCH_ROLE:"role \u53EA\u80FD\u8BBE\u7F6E\u4E3A anchor \u6216\u8005 audience\u3002",INVALID_OPERATION_SWITCH_ROLE:"\u8BF7\u5728\u4F7F\u7528 switchRole() \u65B9\u6CD5\u524D\u5148\u8FDB\u623F\u3002",SWITCH_ROLE_TIMEOUT:"\u5207\u6362\u89D2\u8272\u8D85\u65F6\u3002",SWITCH_ROLE_FAILED(i){return`\u5207\u6362\u89D2\u8272\u5931\u8D25\u3002\u9519\u8BEF\u7801: ${i.code} \u9519\u8BEF\u4FE1\u606F: ${i.message}\u3002`},CLIENT_BANNED(i){return`\u60A8\u88AB\u52A8\u9000\u623F\u4E86\uFF0C\u539F\u56E0\u4E3A\uFF1A${i.reason}\u3002`},INVALID_OPERATION_START_PUBLISH_CDN:"\u8BF7\u5728\u8FDB\u623F\u524D\u6216\u8005\u8FDB\u623F\u5E76\u6210\u529F\u53D1\u5E03\u672C\u5730\u6D41\u540E\u8C03\u7528 startPublishCDNStream() \u65B9\u6CD5\u3002",INVALID_OPERATION_STOP_PUBLISH_CDN:"\u5728\u8C03\u7528 stopPublishCDNStream() \u65B9\u6CD5\u524D\u9700\u8981\u5148 startPublishCDNStream()\u3002",INVALID_STREAM_ID(i){return`'${i}' \u53EA\u80FD\u7531\u5927\u5C0F\u5199\u5B57\u6BCD\uFF08a-zA-z\uFF09, \u6570\u5B57\uFF080-9\uFF09, \u8FDE\u5B57\u7B26\u548C\u4E0B\u5212\u7EBF\u7EC4\u6210`},START_PUBLISH_CDN_FAILED(i){return`startPublishCDNStream \u8C03\u7528\u5931\u8D25\uFF0C\u9519\u8BEF\u4FE1\u606F: ${i.message}\u3002`},STOP_PUBLISH_CDN_FAILED(i){return`stopPublishCDNStream \u8C03\u7528\u5931\u8D25\uFF0C\u9519\u8BEF\u4FE1\u606F: ${i.message}\u3002`},START_MIX_TRANSCODE:"\u8C03\u7528 startMixTranscode() \u65B9\u6CD5\u524D\u9700\u8981\u5148\u8C03\u7528 join()\u3002",STOP_MIX_TRANSCODE:"\u8C03\u7528 stopMixTranscode \u4E4B\u524D\u9700\u8981\u8C03\u7528 startMixTranscode\u3002",INVALID_AUDIO_VOLUME:"interval \u5FC5\u987B\u662F\u6570\u5B57\u3002",ENABLE_SMALL_STREAM_PUBLISHED:"\u53D1\u5E03 localStream \u4E4B\u540E\u4E0D\u5141\u8BB8\u5F00\u542F\u5C0F\u6D41\u3002",DISABLE_SMALL_STREAM_PUBLISHED:"\u53D1\u5E03 localStream \u4E4B\u540E\u4E0D\u5141\u8BB8\u5173\u95ED\u5C0F\u6D41\u3002",NOT_SUPPORTED_SMALL_STREAM:"\u60A8\u7684\u6D4F\u89C8\u5668\u4E0D\u652F\u6301\u5F00\u542F\u5C0F\u6D41\u3002",INVALID_SMALL_STREAM_PROFILE:"\u5C0F\u6D41\u53C2\u6570\u4E0D\u5408\u6CD5\u3002",INVALID_PARAMETER_REMOTE_STREAM:"remoteStream \u4E0D\u5408\u6CD5\u3002",REMOTE_NOT_PUBLISH_SMALL_STREAM:"\u8FDC\u7AEF\u7528\u6237\u6CA1\u6709\u53D1\u5E03\u5C0F\u6D41\u3002",INVALID_SWITCH_DEVICE:"\u5F53\u524D\u7684\u6D41\u4E0D\u53EF\u4EE5\u8C03\u7528 switchDevice\u3002",INVALID_SWITCH_DEVICE_PUBLISHING:"\u53D1\u5E03\u672C\u5730\u6D41\u65F6\u4E0D\u80FD\u5207\u6362\u8BBE\u5907\u3002",INVALID_REPLACE_TRACK:"client.publish \u63A5\u53E3\u5C1A\u672A\u8C03\u7528\u5B8C\u6210\uFF0C\u8BF7\u7B49\u5176\u8C03\u7528\u5B8C\u6210\u540E\u518D\u8C03\u7528 replaceTrack \u63A5\u53E3\u3002",INVALID_INITIALIZE_LOCAL_STREAM:"\u672C\u5730\u6D41\u8FD8\u6CA1\u6709\u521D\u59CB\u5316\u3002",INVALID_ADD_TRACK_REPETITIVE:"\u524D\u4E00\u4E2A addTrack \u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u907F\u514D\u91CD\u590D\u8C03\u7528\u3002",INVALID_ADD_TRACK_REMOVING:"track \u5728\u79FB\u52A8\u7684\u65F6\u5019\u4E0D\u80FD\u6DFB\u52A0\u65B0\u7684 track\u3002",INVALID_ADD_TRACK_PUBLISHING:"\u5728\u53D1\u5E03\u672C\u5730\u6D41\u7684\u65F6\u5019\u4E0D\u80FD\u6DFB\u52A0\u65B0\u7684 track\u3002",INVALID_STREAM_INITIALIZED:"\u60A8\u7684\u672C\u5730\u6D41\u8FD8\u6CA1\u6709\u521D\u59CB\u5316\u3002",INVALID_ADD_TRACK_NUMBER:"\u4E00\u6761\u6D41\u6700\u591A\u6709\u4E00\u4E2A\u97F3\u9891\u8F68\u9053\u548C\u4E00\u4E2A\u89C6\u9891\u8F68\u9053\u3002",INVALID_REMOVE_AUDIO_TRACK:"remove audio track \u662F\u4E0D\u5141\u8BB8\u7684\u3002",INVALID_REMOVE_AUDIO_ADDING:"\u5F53\u4E00\u4E2A track \u88AB addTrack \u7684\u65F6\u5019\u4E0D\u80FD\u5BF9\u6D41\u8FDB\u884C removeTrack \u64CD\u4F5C\u3002",INVALID_REMOVE_AUDIO_ON:"\u524D\u4E00\u6B21\u8C03\u7528\u7684 removeTrack \u6B63\u5728\u8FDB\u884C\u4E2D\uFF0C\u8BF7\u907F\u514D\u91CD\u590D\u64CD\u4F5C\u3002",INVALID_REMOVE_TRACK_PUBLISHING:"\u53D1\u5E03\u6D41\u7684\u8FC7\u7A0B\u4E2D\u4E0D\u80FD\u8FDB\u884C removeTrack \u64CD\u4F5C\u3002",INVALID_REMOVE_TRACK_NOT_PUBLISHING:"\u88AB remove \u7684 track \u6CA1\u6709\u88AB\u53D1\u5E03\u3002",INVALID_REMOVE_TRACK_NUMBER:"\u4E0D\u652F\u6301\u79FB\u9664\u552F\u4E00\u7684\u89C6\u9891\u8F68\u9053\uFF0C\u8BF7\u4F7F\u7528 replaceTrack \u6216\u8005 muteVideo \u65B9\u6CD5\u3002",INVALID_REPLACE_TRACK_NO_TRACK(i){return`LocalStream \u6CA1\u6709 ${i.kind} track\uFF0C\u65E0\u6CD5\u8FDB\u884C\u66FF\u6362\u3002`},START_MIX_TRANSCODE_FAILED(i){return`startMixTranscode \u8C03\u7528\u5931\u8D25\uFF0C\u9519\u8BEF\u4FE1\u606F: ${i.message}\u3002`},STOP_MIX_TRANSCODE_FAILED(i){return`stopMixTranscode \u8C03\u7528\u5931\u8D25\uFF0C\u9519\u8BEF\u4FE1\u606F: ${i.message}\u3002`},MIX_TRANSCODE_NOT_STARTED:"\u8FD8\u6CA1\u6709\u5F00\u59CB mixTranscode\u3002",CANNOT_LESS_THAN_ZERO({key:i,rule:t,fnName:e}){return`'\u5F53\u8C03\u7528 ${e}() \u51FD\u6570\u65F6\uFF0C\u8981\u6C42\u53C2\u6570 ${i||t.name}' \u5FC5\u987B\u5927\u4E8E\u7B49\u4E8E0`},MIX_PARAMS_VIDEO_FRAMERATE:"'config.videoFramerate' \u5E94\u8BE5\u662F (0, 30] \u533A\u95F4\u5185\u7684\u6574\u6570\u3002",MIX_PARAMS_VIDEO_GOP:"'config.videoGOP' \u5E94\u8BE5\u662F [1, 8] \u533A\u95F4\u5185\u7684\u6574\u6570\u3002",MIX_PARAMS_AUDIO_BITRATE:"'config.audioBitrate' \u5E94\u8BE5\u662F [32, 192] \u533A\u95F4\u5185\u7684\u6574\u6570\u3002",MIX_PARAMS_USER_Z_ORDER(i){return`'${i}' \u662F\u5FC5\u4F20\u7684\uFF0C\u4E14\u8981\u6C42\u4E3A [1 ,15] \u4E4B\u95F4\u7684\u6574\u6570\u3002`},MIX_PARAMS_NOT_SELF:"'config.mixUsers' \u5FC5\u987B\u5305\u542B\u53D1\u8D77\u6DF7\u6D41\u7684\u7528\u6237\u4FE1\u606F\u3002",MIX_PARAMS_USER_STREAM:"\u8F93\u51FA\u6D41\u7684 'config.videoWidth' \u548C 'config.videoHeight' \u5E94\u8BE5\u5BB9\u7EB3\u6240\u6709\u6DF7\u5165\u6D41\u3002",INVALID_PLAY:"play() \u88AB\u91CD\u590D\u8C03\u7528\uFF0C\u8BF7\u5148 stop()\uFF0C\u7136\u540E\u518D\u91CD\u65B0\u8C03\u7528 play\u3002",INVALID_ELEMENT_ID:({key:i,fnName:t})=>`\u5728\u8C03\u7528 ${t}() \u65F6\uFF0Cdocument \u5BF9\u8C61\u4E2D\u627E\u4E0D\u5230 ${i} \u5BF9\u5E94\u7684\u5143\u7D20\uFF0C\u8BF7\u68C0\u67E5\u3002`,INVALID_ELEMENT_ID_TYPE:({key:i,type:t,fnName:e})=>`\u5728\u8C03\u7528 ${e}() \u65B9\u6CD5\u65F6\uFF0C${i} \u53C2\u6570\u5BF9\u5E94\u7684 HTML \u6807\u7B7E\u5143\u7D20\u5FC5\u987B\u662F HTMLElement \u5B9E\u4F8B\uFF0C\u60A8\u4F20\u5165\u7684\u662F\uFF1A${t}\u3002`,PLAY_FAILED:i=>`${i.media} \u64AD\u653E\u88AB\u4E2D\u65AD\uFF0C\u6D4F\u89C8\u5668\u5F02\u5E38\u539F\u56E0\uFF1A${i.error.toString()}`,INVALID_USERID:"userId \u4E0D\u80FD\u4E3A\u7A7A\u683C\u3002",INVALID_CREATE_STREAM_SOURCE:"createStream() \u751F\u6210 LocalStream \u53EF\u4EE5\u4F7F\u7528 audio & video \u6216 audioSource & videoSource \u521B\u5EFA\uFF0C\u4F46\u4E0D\u80FD\u6DF7\u5408\u4F7F\u7528\u3002",INVALID_CREATE_STREAM_SCREEN:"screen \u548C video \u4E0D\u80FD\u540C\u65F6\u4E3A true\u3002",INVALID_CREATE_STREAM_AUDIO:"audio \u548C screenAudio \u4E0D\u80FD\u540C\u65F6\u4E3A true\u3002",INVALID_CREATE_STREAM_SCREEN_AUDIO:"screen \u4E3A true \u65F6\uFF0C\u4E0D\u80FD\u8BBE\u7F6E screenAudio\u3002",NOT_SUPPORTED_HTTP:"\u7531\u4E8E\u6D4F\u89C8\u5668\u5B89\u5168\u7B56\u7565\u9650\u5236\uFF0C\u4E0D\u652F\u6301\u5728 http \u534F\u8BAE\u4E0B\u4F7F\u7528\u91C7\u96C6\u3001\u63A8\u6D41\u7B49\u80FD\u529B\uFF0C\u8BF7\u4F7F\u7528 https \u534F\u8BAE\u3002",NOT_SUPPORTED_WEBRTC:"\u5F53\u524D\u6D4F\u89C8\u5668\u6216\u73AF\u5883\u4E0D\u5B8C\u5168\u652F\u6301 WebRTC \u80FD\u529B\uFF0C\u8BF7\u68C0\u67E5\u6D4F\u89C8\u5668\u7248\u672C\u548C\u9875\u9762\u8BBF\u95EE\u534F\u8BAE\u662F\u5426\u6EE1\u8DB3\u6761\u4EF6\u3002",NOT_SUPPORTED_PROFILE:"\u60A8\u7684\u6D4F\u89C8\u5668\u4E0D\u652F\u6301 setVideoProfile \u65B9\u6CD5\u3002\u8BF7\u68C0\u67E5\u6D4F\u89C8\u5668\u7248\u672C\u662F\u5426\u6EE1\u8DB3\u6761\u4EF6\u3002",NOT_SUPPORTED_MEDIA:"\u5F53\u524D\u6D4F\u89C8\u5668\u6216\u73AF\u5883\u4E0D\u652F\u6301 navigator.mediaDevices\uFF0C\u8BF7\u68C0\u67E5\u6D4F\u89C8\u5668\u7248\u672C\u548C\u9875\u9762\u8BBF\u95EE\u534F\u8BAE\u662F\u5426\u6EE1\u8DB3\u6761\u4EF6\u3002",NOT_SUPPORTED_H264ENCODE:"\u5F53\u524D\u7684\u8BBE\u5907\u6216\u73AF\u5883\u4E0D\u652F\u6301 H264 \u7F16\u7801\uFF0C\u4E0D\u652F\u6301 H264 \u683C\u5F0F\u8FDB\u884C\u63A8\u6D41\u3002",NOT_SUPPORTED_H264DECODE:"\u5F53\u524D\u7684\u8BBE\u5907\u6216\u73AF\u5883\u4E0D\u652F\u6301 H264 \u89E3\u7801\uFF0C\u4E0D\u652F\u6301 H264 \u683C\u5F0F\u8FDB\u884C\u62C9\u6D41\u3002",NOT_SUPPORTED_TRACK(i){return`\u60A8\u7684\u6D4F\u89C8\u5668\u4E0D\u652F\u6301 ${i}Track \u65B9\u6CD5\u3002`},NOT_SUPPORTED_REPLACE_TRACK:"\u60A8\u7684\u6D4F\u89C8\u5668\u4E0D\u652F\u6301 replaceTrack \u65B9\u6CD5\uFF0C\u8BF7\u4F7F\u7528 switchDevice \u6216\u8005 addTrack\u3002",NOT_SUPPORTED_CAPTURE:"\u60A8\u5F53\u524D\u7684\u6D4F\u89C8\u5668\u4E0D\u652F\u6301\u5C4F\u5E55\u5206\u4EAB\uFF0C\u8BF7\u68C0\u67E5\u6D4F\u89C8\u5668\u7248\u672C\u548C\u9875\u9762\u8BBF\u95EE\u534F\u8BAE\u662F\u5426\u6EE1\u8DB3\u6761\u4EF6\u3002",NOT_SUPPORTED_AUX:"\u60A8\u5F53\u524D\u7684\u6D4F\u89C8\u5668\u4E0D\u652F\u6301\u63A8\u8F85\u6D41\uFF0C\u8BF7\u68C0\u67E5\u6D4F\u89C8\u5668\u7248\u672C\u662F\u5426\u6EE1\u8DB3\u6761\u4EF6\uFF08Chrome 69+, Safari 11+, Firefox 59+\uFF09\u3002",MICROPHONE_NOT_FOUND:"\u672A\u68C0\u6D4B\u5230\u9EA6\u514B\u98CE\uFF0C\u8BF7\u68C0\u67E5\u60A8\u7684\u9EA6\u514B\u98CE\u548C TRTC.createStream \u4E0A\u7684\u914D\u7F6E\u3002",CAMERA_NOT_FOUND:"\u672A\u68C0\u6D4B\u5230\u6444\u50CF\u5934\uFF0C\u8BF7\u68C0\u67E5\u60A8\u7684\u6444\u50CF\u5934\u548C TRTC.createStream \u4E0A\u7684\u914D\u7F6E\u3002",CATCH_HANDLER_ERROR:({name:i,event:t})=>` \u5728 ${i}.on('${t}', handler) \u4E8B\u4EF6\u4E2D\u6355\u83B7\u5230\u4E1A\u52A1\u4FA7\u9519\u8BEF\uFF0C\u8BF7\u6839\u636E\u4E0B\u8FF0\u9519\u8BEF\u4FE1\u606F\uFF0C\u68C0\u67E5\u60A8\u5728 handler \u4E2D\u7684\u4E1A\u52A1\u4EE3\u7801\u3002`,REPEAT_JOIN:i=>`\u7528\u6237 [${i}] \u6B63\u5728\u8C03\u7528\u8FDB\u623F\u63A5\u53E3\u6216\u8005\u5DF2\u7ECF\u5728\u623F\u95F4\u5185\uFF0C\u8BF7\u52FF\u91CD\u590D\u521B\u5EFA\u76F8\u540C userId \u7684 client \u8FDB\u5165\u540C\u4E00\u4E2A\u623F\u95F4\u3002`,CLIENT_DESTROYED:({funName:i})=>`client \u5DF2\u7ECF\u88AB\u9500\u6BC1\uFF0C\u8C03\u7528 ${i}() \u65B9\u6CD5\u5931\u8D25\u3002`,API_CALL_ABORTED(i){let t;return i.message.includes("REMOTE_STREAM_NOT_EXIST")?t=`\u4E2D\u65AD\u8BA2\u9605\u7528\u6237 ${i.userId} \u7684 ${i.streamType} stream, \u539F\u56E0: \u5728\u60A8\u8BA2\u9605\u8FC7\u7A0B\u4E2D\uFF0C\u8FDC\u7AEF\u7528\u6237 ${i.userId} \u53D6\u6D88\u4E86\u63A8\u6D41\uFF0C\u60A8\u53EF\u4EE5\u5728\u4E0B\u6B21\u8FDC\u7AEF\u63A8\u6D41\u65F6\u518D\u8FDB\u884C\u8BA2\u9605\u3002`:t=`\u4E2D\u65AD\u63A5\u53E3\u8C03\u7528, \u539F\u56E0: ${i.message}\u3002`,t},SEI_BEFORE_PUBLISH:"\u5F53\u524D client \u6CA1\u6709\u63A8 localStream(\u4E3B\u6D41\uFF0C\u975E\u5C4F\u5E55\u5206\u4EAB\u6D41)\uFF0C\u65E0\u6CD5\u8C03\u7528 client.sendSEIMessage() \u63A5\u53E3\u3002"},sm={INVALID_USER_DEFINE_RECORDID:"TRTC.html#createClient",INVALID_PROXY:"Client.html#setProxyServer",INVALID_JOIN:"Client.html#join",INVALID_ROOMID_STRING:"Client.html#join",INVALID_ROOMID_INTEGER:"Client.html#join",INVALID_PUBLISH:"Client.html#publish",INVALID_UNPUBLISH:"Client.html#unpublish",INVALID_AUDIENCE:"Client.html#switchRole",INVALID_INITIALIZE:"Client.html#publish",INVALID_DUPLICATE_PUBLISHING:"Client.html#publish",INVALID_SUBSCRIBE_UNDEFINED:"Client.html#subscribe",INVALID_SUBSCRIBE_LOCAL:"Client.html#subscribe",INVALID_REMOTE_STREAM:"Client.html#subscribe",INVALID_ROLE:"Client.html#switchRole",INVALID_PARAMETER_SWITCH_ROLE:"Client.html#switchRole",INVALID_OPERATION_SWITCH_ROLE:"Client.html#switchRole",CLIENT_BANNED:"module-ClientEvent.html#.CLIENT_BANNED",INVALID_OPERATION_START_PUBLISH_CDN:"Client.html#startPublishCDNStream",INVALID_OPERATION_STOP_PUBLISH_CDN:"Client.html#stopPublishCDNStream",START_MIX_TRANSCODE:"Client.html#startMixTranscode",STOP_MIX_TRANSCODE:"Client.html#stopMixTranscode",INVALID_AUDIO_VOLUME:"Client.html#enableAudioVolumeEvaluation",ENABLE_SMALL_STREAM_PUBLISHED:"Client.html#enableSmallStream",DISABLE_SMALL_STREAM_PUBLISHED:"Client.html#disableSmallStream",NOT_SUPPORTED_SMALL_STREAM:"tutorial-27-advanced-small-stream.html#h2-4",INVALID_SMALL_STREAM_PROFILE:"Client.html#setSmallStreamProfile",REMOTE_NOT_PUBLISH_SMALL_STREAM:"Client.html#setRemoteVideoStreamType",INVALID_SWITCH_DEVICE:"LocalStream.html#switchDevice",INVALID_SWITCH_DEVICE_PUBLISHING:"LocalStream.html#switchDevice",INVALID_REPLACE_TRACK:"LocalStream.html#replaceTrack",INVALID_INITIALIZE_LOCAL_STREAM:"LocalStream.html#replaceTrack",INVALID_ADD_TRACK_REPETITIVE:"LocalStream.html#addTrack",INVALID_ADD_TRACK_REMOVING:"LocalStream.html#addTrack",INVALID_ADD_TRACK_PUBLISHING:"LocalStream.html#addTrack",INVALID_STREAM_INITIALIZED:"LocalStream.html#addTrack",INVALID_ADD_TRACK_NUMBER:"LocalStream.html#addTrack",INVALID_REMOVE_AUDIO_TRACK:"LocalStream.html#removeTrack",INVALID_REMOVE_AUDIO_ADDING:"LocalStream.html#removeTrack",INVALID_REMOVE_AUDIO_ON:"LocalStream.html#removeTrack",INVALID_REMOVE_TRACK_PUBLISHING:"LocalStream.html#removeTrack",INVALID_REMOVE_TRACK_NOT_PUBLISHING:"LocalStream.html#removeTrack",INVALID_REMOVE_TRACK_NUMBER:"LocalStream.html#removeTrack",INVALID_REMOVE_TRACK_NOT_PUBLISHED:"LocalStream.html#removeTrack",START_MIX_TRANSCODE_TIMEOUT:"Client.html#startMixTranscode",START_MIX_TRANSCODE_FAILED:"Client.html#startMixTranscode",STOP_MIX_TRANSCODE_FAILED:"Client.html#stopMixTranscode",MIX_TRANSCODE_NOT_STARTED:"Client.html#startMixTranscode",MIX_PARAMS_VIDEO_FRAMERATE:"Client.html#startMixTranscode",MIX_PARAMS_VIDEO_GOP:"Client.html#startMixTranscode",MIX_PARAMS_AUDIO_BITRATE:"Client.html#startMixTranscode",MIX_PARAMS_USER_Z_ORDER:"Client.html#startMixTranscode",MIX_PARAMS_NOT_SELF:"Client.html#startMixTranscode",MIX_PARAMS_USER_STREAM:"Client.html#startMixTranscode",INVALID_PLAY:"Stream.html#play",PLAY_FAILED:"Stream.html#play",INVALID_USERID:"TRTC.html#createClient",INVALID_CREATE_STREAM_SOURCE:"TRTC.html#createStream",INVALID_CREATE_STREAM_SCREEN:"TRTC.html#createStream",INVALID_CREATE_STREAM_AUDIO:"TRTC.html#createStream",INVALID_CREATE_STREAM_SCREEN_AUDIO:"TRTC.html#createStream",NOT_SUPPORTED_HTTP:"tutorial-05-info-browser.html#h2-2",NOT_SUPPORTED_WEBRTC:"tutorial-05-info-browser.html",NOT_SUPPORTED_TRTC:"tutorial-05-info-browser.html",NOT_SUPPORTED_PROFILE:"tutorial-23-advanced-support-detection.html",NOT_SUPPORTED_MEDIA:"tutorial-05-info-browser.html",NOT_SUPPORTED_H264ENCODE:"tutorial-23-advanced-support-detection.html",NOT_SUPPORTED_H264DECODE:"tutorial-23-advanced-support-detection.html",NOT_SUPPORTED_TRACK:"LocalStream.html#addTrack",NOT_SUPPORTED_REPLACE_TRACK:"LocalStream.html#replaceTrack",NOT_SUPPORTED_CAPTURE:"tutorial-05-info-browser.html",MICROPHONE_NOT_FOUND:"TRTC.html#createStream",CAMERA_NOT_FOUND:"TRTC.html#createStream",SUBSCRIBE_FAILED:"Client.html#subscribe",API_CALL_ABORTED(i){let t;return i.message.includes("REMOTE_STREAM_NOT_EXIST")?t="Client.html#subscribe":t="module-ErrorCode.html#.API_CALL_ABORTED",t}};typeof window!="undefined"&&(window.TRTC_ERROR_INFO=nm,window.TRTC_ERROR_LINK=sm);var tu=(i,t)=>t?`${Ji}/${i}/${t}`:`${Ji}/${i}/index.html`;var om=()=>{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 i=localStorage.getItem(Ld);if(i){i=JSON.parse(i);let t=document.createElement("script");t.type="text/javascript",t.text=i.message,document.body.appendChild(t);let e=window.TRTC_ERROR_INFO,r=window.TRTC_ERROR_LINK;return document.body.removeChild(t),{TRTC_ERROR_INFO:e,TRTC_ERROR_LINK:r}}return{}};function $(i){let{key:t,data:e,link:r,addDocLink:n=!0}=i,s="",o="",a="";ue(Le[t])?s=Le[t](e):oe(Le[t])&&(s=Le[t]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:d}=om();r?a=`${r.className}.html#${r.fnName}`:d&&d[t]&&(ue(d[t])?a=d[t](e):oe(d[t])&&(a=d[t]));let u=s;return Ct()&&(c&&c[t]&&(ue(c[t])?o=c[t](e):oe(c[t])&&(o=c[t])),o&&(n?u=`${o}
75
- \u8BF7\u67E5\u770B\u6587\u6863: ${tu("zh-cn",a)}
74
+ `}});var jc=fe(Qt=>{var RO=_(f()),qi=Ul(),Tf=wl();Qt.write=Tf;Qt.parse=qi.parse;Qt.parseParams=qi.parseParams;Qt.parseFmtpConfig=qi.parseFmtpConfig;Qt.parsePayloads=qi.parsePayloads;Qt.parseRemoteCandidates=qi.parseRemoteCandidates;Qt.parseImageAttributes=qi.parseImageAttributes;Qt.parseSimulcastStreamList=qi.parseSimulcastStreamList});var sd=fe((Xl,Ao)=>{var rL=_(f());(function(i){"use strict";function t(A,U){var y=(A&65535)+(U&65535),J=(A>>16)+(U>>16)+(y>>16);return J<<16|y&65535}function e(A,U){return A<<U|A>>>32-U}function r(A,U,y,J,ie,Re){return t(e(t(t(U,A),t(J,Re)),ie),y)}function n(A,U,y,J,ie,Re,G){return r(U&y|~U&J,A,U,ie,Re,G)}function s(A,U,y,J,ie,Re,G){return r(U&J|y&~J,A,U,ie,Re,G)}function o(A,U,y,J,ie,Re,G){return r(U^y^J,A,U,ie,Re,G)}function a(A,U,y,J,ie,Re,G){return r(y^(U|~J),A,U,ie,Re,G)}function c(A,U){A[U>>5]|=128<<U%32,A[(U+64>>>9<<4)+14]=U;var y,J,ie,Re,G,k=1732584193,L=-271733879,R=-1732584194,g=271733878;for(y=0;y<A.length;y+=16)J=k,ie=L,Re=R,G=g,k=n(k,L,R,g,A[y],7,-680876936),g=n(g,k,L,R,A[y+1],12,-389564586),R=n(R,g,k,L,A[y+2],17,606105819),L=n(L,R,g,k,A[y+3],22,-1044525330),k=n(k,L,R,g,A[y+4],7,-176418897),g=n(g,k,L,R,A[y+5],12,1200080426),R=n(R,g,k,L,A[y+6],17,-1473231341),L=n(L,R,g,k,A[y+7],22,-45705983),k=n(k,L,R,g,A[y+8],7,1770035416),g=n(g,k,L,R,A[y+9],12,-1958414417),R=n(R,g,k,L,A[y+10],17,-42063),L=n(L,R,g,k,A[y+11],22,-1990404162),k=n(k,L,R,g,A[y+12],7,1804603682),g=n(g,k,L,R,A[y+13],12,-40341101),R=n(R,g,k,L,A[y+14],17,-1502002290),L=n(L,R,g,k,A[y+15],22,1236535329),k=s(k,L,R,g,A[y+1],5,-165796510),g=s(g,k,L,R,A[y+6],9,-1069501632),R=s(R,g,k,L,A[y+11],14,643717713),L=s(L,R,g,k,A[y],20,-373897302),k=s(k,L,R,g,A[y+5],5,-701558691),g=s(g,k,L,R,A[y+10],9,38016083),R=s(R,g,k,L,A[y+15],14,-660478335),L=s(L,R,g,k,A[y+4],20,-405537848),k=s(k,L,R,g,A[y+9],5,568446438),g=s(g,k,L,R,A[y+14],9,-1019803690),R=s(R,g,k,L,A[y+3],14,-187363961),L=s(L,R,g,k,A[y+8],20,1163531501),k=s(k,L,R,g,A[y+13],5,-1444681467),g=s(g,k,L,R,A[y+2],9,-51403784),R=s(R,g,k,L,A[y+7],14,1735328473),L=s(L,R,g,k,A[y+12],20,-1926607734),k=o(k,L,R,g,A[y+5],4,-378558),g=o(g,k,L,R,A[y+8],11,-2022574463),R=o(R,g,k,L,A[y+11],16,1839030562),L=o(L,R,g,k,A[y+14],23,-35309556),k=o(k,L,R,g,A[y+1],4,-1530992060),g=o(g,k,L,R,A[y+4],11,1272893353),R=o(R,g,k,L,A[y+7],16,-155497632),L=o(L,R,g,k,A[y+10],23,-1094730640),k=o(k,L,R,g,A[y+13],4,681279174),g=o(g,k,L,R,A[y],11,-358537222),R=o(R,g,k,L,A[y+3],16,-722521979),L=o(L,R,g,k,A[y+6],23,76029189),k=o(k,L,R,g,A[y+9],4,-640364487),g=o(g,k,L,R,A[y+12],11,-421815835),R=o(R,g,k,L,A[y+15],16,530742520),L=o(L,R,g,k,A[y+2],23,-995338651),k=a(k,L,R,g,A[y],6,-198630844),g=a(g,k,L,R,A[y+7],10,1126891415),R=a(R,g,k,L,A[y+14],15,-1416354905),L=a(L,R,g,k,A[y+5],21,-57434055),k=a(k,L,R,g,A[y+12],6,1700485571),g=a(g,k,L,R,A[y+3],10,-1894986606),R=a(R,g,k,L,A[y+10],15,-1051523),L=a(L,R,g,k,A[y+1],21,-2054922799),k=a(k,L,R,g,A[y+8],6,1873313359),g=a(g,k,L,R,A[y+15],10,-30611744),R=a(R,g,k,L,A[y+6],15,-1560198380),L=a(L,R,g,k,A[y+13],21,1309151649),k=a(k,L,R,g,A[y+4],6,-145523070),g=a(g,k,L,R,A[y+11],10,-1120210379),R=a(R,g,k,L,A[y+2],15,718787259),L=a(L,R,g,k,A[y+9],21,-343485551),k=t(k,J),L=t(L,ie),R=t(R,Re),g=t(g,G);return[k,L,R,g]}function d(A){var U,y="",J=A.length*32;for(U=0;U<J;U+=8)y+=String.fromCharCode(A[U>>5]>>>U%32&255);return y}function u(A){var U,y=[];for(y[(A.length>>2)-1]=void 0,U=0;U<y.length;U+=1)y[U]=0;var J=A.length*8;for(U=0;U<J;U+=8)y[U>>5]|=(A.charCodeAt(U/8)&255)<<U%32;return y}function l(A){return d(c(u(A),A.length*8))}function h(A,U){var y,J=u(A),ie=[],Re=[],G;for(ie[15]=Re[15]=void 0,J.length>16&&(J=c(J,A.length*8)),y=0;y<16;y+=1)ie[y]=J[y]^909522486,Re[y]=J[y]^1549556828;return G=c(ie.concat(u(U)),512+U.length*8),d(c(Re.concat(G),512+128))}function I(A){var U="0123456789abcdef",y="",J,ie;for(ie=0;ie<A.length;ie+=1)J=A.charCodeAt(ie),y+=U.charAt(J>>>4&15)+U.charAt(J&15);return y}function T(A){return unescape(encodeURIComponent(A))}function N(A){return l(T(A))}function $(A){return I(N(A))}function x(A,U){return h(T(A),T(U))}function F(A,U){return I(x(A,U))}function ge(A,U,y){return U?y?x(U,A):F(U,A):y?N(A):$(A)}typeof define=="function"&&define.amd?define(function(){return ge}):typeof Ao=="object"&&Ao.exports?Ao.exports=ge:i.md5=ge})(Xl)});var aU=_(f());var Zb=_(f()),vl=_(rt());var Vy=_(f(),1);var bE=_(f(),1);var yE=_(f(),1),eu=(R=>(R[R.INVALID_PARAMETER=4096]="INVALID_PARAMETER",R[R.INVALID_OPERATION=4097]="INVALID_OPERATION",R[R.NOT_SUPPORTED=4098]="NOT_SUPPORTED",R[R.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",R[R.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",R[R.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",R[R.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",R[R.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",R[R.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",R[R.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",R[R.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",R[R.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",R[R.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",R[R.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",R[R.CLIENT_BANNED=16448]="CLIENT_BANNED",R[R.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",R[R.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",R[R.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",R[R.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",R[R.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",R[R.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",R[R.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",R[R.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",R[R.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",R[R.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",R[R.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",R[R.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",R[R.API_CALL_ABORTED=16461]="API_CALL_ABORTED",R[R.UNKNOWN=65535]="UNKNOWN",R))(eu||{}),v=eu;var pm=function(i){for(let t in v)if(v[t]===i)return t;return"UNKNOWN"},qo=class extends Error{constructor({name:e="RtcError",message:r,code:n=v.UNKNOWN,extraCode:s=0,constraint:o}){let a=`<${pm(n)} 0x${n.toString(16)}>`,c=`${r}${o?` constraint: ${o}`:""}${r!=null&&r.includes(a)?"":` ${a}`}`;super(c);p(this,"code");p(this,"extraCode");p(this,"message");p(this,"originMessage");p(this,"name");p(this,"constraint");this.code=n,this.extraCode=s,this.name=e,this.message=c,this.constraint=o,this.originMessage=r}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},M=qo;var RT=_(f(),1);var ME=_(f(),1);var tu=new Date().getTime(),Qo=0,iu=function(i){tu=i,Qo=tu-new Date().getTime();let t=new Date;t.setTime(i),O.info(`baseTime from server: ${t} offset: ${Qo}`)},en=function(){return new Date().getTime()+Qo},ls=function(){let i=new Date;return i.setTime(en()),i.toLocaleString()};var ke={};Jr(ke,{bytes2ms:()=>Ym,copyProperties:()=>Jm,deepMerge:()=>bt,fibonacci:()=>vr,formatedTime:()=>i_,getConstructorName:()=>$s,getContainerFromElement:()=>Hs,getEnv:()=>Km,getInternalVersion:()=>qm,getLoggerUrl:()=>wi,getMuteStateFromFlag:()=>li,getNetworkQuality:()=>Zm,getNetworkType:()=>Bs,getOSType:()=>pu,getReconnectionTimeout:()=>ot,getSysInfo:()=>jm,getTerminalType:()=>lu,getTurnServer:()=>e_,getValueType:()=>Ee,glog:()=>_u,ipv4ToUint32:()=>bn,isArray:()=>Oe,isArrayOrObject:()=>Cn,isAudioWorkletSupported:()=>Aa,isBoolean:()=>Ne,isConstructor:()=>vn,isEmpty:()=>Nn,isFunction:()=>ce,isLangChinese:()=>Nt,isMediaStreamTrack:()=>zm,isNumber:()=>de,isObject:()=>Bi,isOverseaSdkAppId:()=>ws,isPlainObject:()=>Ht,isPromise:()=>yn,isRemoteTrack:()=>ui,isString:()=>oe,isUndefined:()=>b,ms2bytes:()=>Xm,ms2samples:()=>mu,performanceNow:()=>z,promiseAny:()=>Ca,samples2ms:()=>hu,stringify:()=>$i});var WE=_(f(),1);var Di={};Jr(Di,{ANDROID_VERSION:()=>ta,CHROME_MAJOR_VERSION:()=>fr,CHROME_VERSION:()=>bs,EDGE_VERSION:()=>hs,EDG_MAJOR_VERSION:()=>ra,EDG_VERSION:()=>ms,FIREFOX_MAJOR_VERSION:()=>ia,FIREFOX_VERSION:()=>ps,HUAWEI_VERSION:()=>Cs,IE_VERSION:()=>Em,IOS_VERSION:()=>vi,IPADQQB_VERSION:()=>Rs,IS_ANDROID:()=>st,IS_ANDROID_WEBVIEW:()=>Rm,IS_ANY_SAFARI:()=>Im,IS_CHROME:()=>_r,IS_CHROME_ONLY:()=>sa,IS_EDG:()=>cr,IS_EDGE:()=>ar,IS_ELECTRON:()=>Sm,IS_FIREFOX:()=>ue,IS_HEADLESS_CHROME:()=>oa,IS_HUAWEI:()=>gm,IS_HUAWEIBROWSER:()=>dn,IS_IE:()=>su,IS_IE8:()=>fm,IS_IOS:()=>nt,IS_IOS_13_OR_14:()=>Am,IS_IOS_15_1:()=>Ni,IS_IPAD:()=>or,IS_IPADQQB:()=>an,IS_IPAD_PRO:()=>ea,IS_IPHONE:()=>si,IS_IPOD:()=>nu,IS_LINUX:()=>hr,IS_LOCAL:()=>mt,IS_MAC:()=>Ct,IS_MACQQB:()=>on,IS_MIBROWSER:()=>cn,IS_MQQB:()=>lr,IS_NATIVE_ANDROID:()=>_m,IS_OLD_ANDROID:()=>mm,IS_OPPOBROWSER:()=>ln,IS_SAFARI:()=>ht,IS_SAFARI_15_1:()=>hn,IS_SAMSUNGBROWSER:()=>un,IS_SOGOU:()=>rn,IS_SOGOUM:()=>tn,IS_TBS:()=>At,IS_UCBROWSER:()=>na,IS_VIVOBROWSER:()=>pn,IS_WECHAT:()=>dr,IS_WIN:()=>pr,IS_WQQB:()=>sn,IS_WX:()=>Tm,IS_X5MQQB:()=>ur,IS_XWEB:()=>nn,MACQQB_VERSION:()=>Is,MI_VERSION:()=>As,MQQB_VERSION:()=>sr,OPPO_VERSION:()=>vs,SAFARI_VERSION:()=>Er,SAMSUNG_VERSION:()=>ys,SOGOUM_VERSION:()=>_s,SOGOU_VERSION:()=>fs,TBS_VERSION:()=>Es,USER_AGENT:()=>pt,VIVO_VERSION:()=>Ns,WECHAT_VERSION:()=>Ss,WQQB_VERSION:()=>gs,XWEB_VERSION:()=>Ts,browserInfo:()=>bi,getBrowserInfo:()=>ou,getChromeMajorVersion:()=>mr,isLocalStorageEnabled:()=>Vt});var kE=_(f(),1);var pt=typeof navigator=="undefined"?"":navigator.userAgent,te=i=>new RegExp(i,"i").test(pt),Ce=i=>{if(te(i)){let t=new RegExp(`${i}\\/([\\d.]+)`),e=pt.match(t);if(e&&e[1])return e[1]}return""},Zo=i=>{if(te(i)){let t=new RegExp(`${i}\\/(\\d+)`),e=pt.match(t);if(e&&e[1])return parseFloat(e[1])}return NaN},ru=/AppleWebKit\/([\d.]+)/i.exec(pt),hm=ru?parseFloat(ru[1]):NaN,or=te("iPad"),ea=typeof navigator!="undefined"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&te("Macintosh"),si=te("iPhone")&&!or,nu=te("iPod"),nt=si||or||nu||ea,st=te("Android"),ta=function(){if(st){let i=pt.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(i){let t=i[1]&&parseFloat(i[1]),e=i[2]&&parseFloat(i[2]);if(t&&e)return parseFloat(`${i[1]}.${i[2]}`);if(t)return t}}return NaN}(),mm=st&&te("webkit")&&ta<2.3,_m=st&&ta<5&&hm<537,ue=te("Firefox"),ps=Ce("Firefox"),ia=Zo("Firefox"),ar=te("Edge"),hs=Ce("Edge"),cr=te("Edg"),ms=Ce("Edg"),ra=Zo("Edg"),tn=te("SogouMobileBrowser"),_s=Ce("SogouMobileBrowser"),rn=te("MetaSr\\s"),fs=Ce("MetaSr\\s"),At=te("TBS"),Es=Ce("TBS"),nn=te("XWEB"),Ts=Ce("XWEB"),fm=te("MSIE\\s8\\.0"),su=te("MSIE\\/\\d+"),Em=function(){if(su){let i=/MSIE\s(\d+)\.\d/.exec(pt),t=i&&parseFloat(i[1]);return!t&&/Trident\/7.0/i.test(pt)&&/rv:11.0/.test(pt)&&(t=11),t}return NaN}(),dr=te("(micromessenger|webbrowser)"),Ss=Ce("MicroMessenger"),ur=!At&&te("MQQBrowser")&&te("COVC"),lr=!At&&te("MQQBrowser")&&!te("COVC"),sr=lr||ur?Ce("MQQBrowser"):"",sn=!At&&te(" QQBrowser"),gs=Ce(" QQBrowser"),on=!At&&te("QQBrowserLite"),Is=Ce("QQBrowserLite"),an=!At&&te("MQBHD"),Rs=Ce("MQBHD"),pr=te("Windows"),Ct=!nt&&te("MAC OS X"),hr=!st&&te("Linux"),Tm=te("MicroMessenger"),na=te("UCBrowser"),Sm=te("Electron"),cn=te("MiuiBrowser"),As=Ce("MiuiBrowser"),dn=te("HuaweiBrowser"),gm=te("Huawei"),Cs=Ce("HuaweiBrowser"),un=te("SamsungBrowser"),ys=Ce("SamsungBrowser"),ln=te("HeyTapBrowser"),vs=Ce("HeyTapBrowser"),pn=te("VivoBrowser"),Ns=Ce("VivoBrowser"),mr=()=>Zo("Chrome"),sa=te("Chrome"),_r=!ar&&!rn&&!tn&&!At&&!nn&&!cr&&!sn&&!cn&&!dn&&!un&&!ln&&!pn&&sa,oa=te("HeadlessChrome"),fr=mr(),bs=Ce("Chrome"),ht=!sa&&!lr&&!ur&&!on&&!an&&te("Safari"),Im=ht||nt,Er=Ce("Safari"),Rm=/Android.*(wv|.0.0.0)/.test(pt),vi=(()=>{if(ea)return Er;if(nt){let i=pt.match(/OS (\d+)_(\d+)/i);if(i&&i[1]){let t=i[1];return i[2]&&(t+=`.${i[2]}`),t}}return""})(),hn=Er==="15.1",Ni=vi==="15.1",Am=(()=>{let i=Number(vi.split(".")[0]);return i===14||i===13})(),mt=typeof location!="undefined"?location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1":!1,Vt=(()=>{let i;return()=>{if(b(i))try{i=!!window.localStorage}catch(t){i=!1}return i}})(),bi=ou();function ou(){let i=new Map([[ue,["Firefox",ps]],[cr,["Edg",ms]],[_r,["Chrome",bs]],[ht,["Safari",Er]],[At,["TBS",Es]],[nn,["XWEB",Ts]],[dr&&si,["WeChat",Ss]],[sn,["QQ(Win)",gs]],[lr,["QQ(Mobile)",sr]],[ur,["QQ(Mobile X5)",sr]],[on,["QQ(Mac)",Is]],[an,["QQ(iPad)",Rs]],[cn,["MI",As]],[dn,["HW",Cs]],[un,["Samsung",ys]],[ln,["OPPO",vs]],[pn,["VIVO",Ns]],[ar,["EDGE",hs]],[tn,["SogouMobile",_s]],[rn,["Sogou",fs]]]),t="unknown",e="unknown";return i.has(!0)&&([t,e]=i.get(!0)),{name:t,version:e}}var Ra={};Jr(Ra,{AUDIO_MUTE_BIT:()=>ks,AUDIO_STAT_BIT:()=>gr,AUX_STAT_BIT:()=>Tn,AUX_STREAM_MSID:()=>ma,BACKEND_ENV:()=>Ls,BASE_DOC_URL:()=>Pi,BASE_HOST:()=>Ds,CAPABILITIES_KEYS:()=>Vs,CLASS_NAME:()=>$m,CLOUD_CONSOLE_URL:()=>En,DATA_FREEZE_TIMING:()=>Us,DOC_URL:()=>Mi,DTLS_STATE_UNKNOWN:()=>ft,ENV_NAME:()=>wt,EXCHANGE_SDP_TIMEOUT:()=>Ta,INTERVAL:()=>Ia,IS_WORKER:()=>Tr,IS_WORKLET:()=>mn,KIBANA_EVENT:()=>yt,LOCAL_STREAM_PUBLISH_STATE:()=>du,LOGGER_CMD_TYPE:()=>Li,LOGGER_DOMAIN:()=>ua,LOGGER_DOMAIN_OVERSEA:()=>la,LOG_LEVEL:()=>_t,LOG_LEVEL_NAME:()=>Fm,MAIN_STREAM_MSID:()=>Sn,MICROPHONE_COMMUNICATIONS:()=>Hm,MICROPHONE_DEFAULT:()=>Ui,MIX_TRANCODE:()=>Nm,MIX_TRANSCODE:()=>di,NAME:()=>m,NETWORK_TYPE:()=>oi,NOT_SUPPORTED_H264:()=>xi,PAUSED_RETRY_COUNT:()=>Sa,PEERCONNECTION_CONNECTING_TIMEOUT:()=>Rn,PEER_CONNECTION_STATE:()=>pe,PEER_LEAVE_REASON:()=>ga,RAF:()=>$t,RECOVER_CAPTURE_INTERVAL:()=>Cr,REMOTE_STREAM_TYPE_AUX:()=>gn,REMOTE_STREAM_TYPE_MAIN:()=>_a,RENDER_FREEZE_TIMING:()=>Um,RIC:()=>vt,SCHEDULE_DOMAIN:()=>Rr,SCHEDULE_TIMEOUT:()=>Bm,SDP_SEMANTICS_PLAN_B:()=>Ir,SDP_SEMANTICS_UNIFIED_PLAN:()=>ci,SECOND_HOST:()=>ca,SIGNAL_PING_PONG_INTERVAL:()=>vm,SIGNAL_PING_TIMEOUT:()=>ym,SIGNAL_RECONNECTION_COUNT:()=>In,SMALL_STAT_BIT:()=>ha,SPEAKER_DEFAULT:()=>An,STORAGE_EXPIRES_TIME:()=>Os,STREAM_TYPE_BIG:()=>Vm,STREAM_TYPE_SMALL:()=>wm,SUBSCRIBE_SMALL_RETRY_COUNT:()=>Ar,SYNC_USER_LIST_INTERVAL:()=>xm,Scene:()=>ai,Switch:()=>au,THIRD_HOST:()=>da,TIMEOUT:()=>yr,TRANSPORT_DIRECTION:()=>se,TRTC_ERROR_ASSISTANCE:()=>pa,TRTC_QUALITY_BAD:()=>Mm,TRTC_QUALITY_DISCONNECTED:()=>km,TRTC_QUALITY_EXCELLENT:()=>Dm,TRTC_QUALITY_GOOD:()=>Om,TRTC_QUALITY_POOR:()=>Pm,TRTC_QUALITY_UNKNOWN:()=>bm,TRTC_QUALITY_VERY_BAD:()=>Lm,UPDATE_OFFER_TIMEOUT:()=>Ea,VIDEO_MUTE_BIT:()=>xs,VIDEO_STAT_BIT:()=>Sr,audioProfileMap:()=>Ps,getRetryCount:()=>Bt,getScriptDir:()=>Cm,innerVersion:()=>Oi,loggerProxy:()=>_n,screenProfileMap:()=>Ms,setLoggerProxy:()=>fn,setRetryCount:()=>fa,setVersion:()=>aa,version:()=>$e,videoProfileMap:()=>ki});var xE=_(f(),1),Oi="4.15.00.1600",$e="5.0.0";function aa(i){$e=i;let[t,e,r]=i.split(".").map(n=>parseInt(n,10));Oi=`${t}.${Math.min(15,e)}.${Math.min(15,r)}.${e.toString().padStart(2,"0")}${r.toString().padStart(2,"0")}`}var Tr=typeof importScripts!="undefined",mn=typeof registerProcessor!="undefined",Cm=()=>{let i=Tr?self.location.href:document.currentScript.src;return i.substring(0,i.lastIndexOf("/")+1)},_n="",fn=i=>_n=i,Ds="web.sdk.qcloud.com",ca="web.sdk.tencent.cn",da="web.sdk.cloud.tencent.cn",En="https://console.cloud.tencent.com/trtc",Pi=`https://${Ds}/trtc/webrtc/v5/doc`,Mi=`${Pi}/zh-cn/`,ua="https://yun.tim.qq.com",la="https://videoapi-sgp.im.qcloud.com",pa="trtc_error_assistance",Li={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport"},wt={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},_t=(o=>(o[o.TRACE=0]="TRACE",o[o.DEBUG=1]="DEBUG",o[o.INFO=2]="INFO",o[o.WARN=3]="WARN",o[o.ERROR=4]="ERROR",o[o.NONE=5]="NONE",o))(_t||{}),ym=18e3,vm=2e3,Nm={MODE:{MANUAL:"manual",PRESET_LAYOUT:"preset-layout"},PLACE_HOLDER:{REMOTE:"$PLACE_HOLDER_REMOTE$"},STREAM_TYPE:{IT_AUDIO_VIDEO:0,IT_PICTURE:2,IT_CANVAS:3,IT_PURE_AUDIO:4,IT_PURE_VIDEO:5}},oi={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5},Os=7*24*3600*1e3,au=(n=>(n.USEAINS="useAINS",n.ENABLEDEBUG="enableDebug",n.USEV2="useV2",n.USEWT="useWt",n))(au||{}),Ps={standard:{sampleRate:48e3,channelCount:1,bitrate:40},"standard-stereo":{sampleRate:48e3,channelCount:2,bitrate:64},high:{sampleRate:48e3,channelCount:1,bitrate:192},"high-stereo":{sampleRate:48e3,channelCount:2,bitrate:192}},ki={"120p":{width:160,height:120,frameRate:15,bitrate:200},"180p":{width:320,height:180,frameRate:15,bitrate:350},"240p":{width:320,height:240,frameRate:15,bitrate:400},"360p":{width:640,height:360,frameRate:15,bitrate:800},"480p":{width:640,height:480,frameRate:15,bitrate:900},"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}},Ms={"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}},m={CANVAS:"canvas",AUDIO:"audio",VIDEO:"video",SCREEN:"screen",SMALL:"small",BIG:"big",AUXILIARY:"auxiliary",SMALL_VIDEO:"smallVideo",FACING_MODE_USER:"user",FACING_MODE_ENVIRONMENT:"environment",MUTE:"mute",UNMUTE:"unmute",ENDED:"ended",PLAYING:"playing",PAUSE:"pause",ERROR:"error",LOADEDDATA:"loadeddata",AUDIO_INPUT:"audioinput",VIDEO_INPUT:"videoinput",DETAIL:"detail",TEXT:"text",MAIN:"main",BACKUP:"backup",BANNED:"banned",KICK:"kick",USER_TIME_OUT:"user_time_out",ROOM_DISBAND:"room_disband",SEI_MESSAGE:"sei-message",ADD:"add",REMOVE:"remove",REPLACE:"replace",TRACK:"track",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",TRANSCEIVER_DIRECTION_SENDONLY:"sendonly",TRANSCEIVER_DIRECTION_RECVONLY:"recvonly"},se={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},Ls={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},ai=(e=>(e.LIVE="live",e.RTC="rtc",e))(ai||{}),Sr=1,ha=2,Tn=4,gr=8,ks=64,xs=16,Sn="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",ma="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",_a=m.MAIN,gn=m.AUXILIARY,bm=0,Dm=1,Om=2,Pm=3,Mm=4,Lm=5,km=6,ft="unknown",pe={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},cu=1/0;function fa(i){cu=i}function Bt(){return cu}var In=30,yt={JOIN:"join",DELTA_JOIN:"delta-join",REJOIN:"rejoin",LEAVE:"leave",DELTA_LEAVE:"delta-leave",PUBLISH:"publish",DELTA_PUBLISH:"delta-publish",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",UPLINK_CONNECTION:"uplink-connection",UPLINK_RECONNECTION:"uplink-reconnection",DOWNLINK_CONNECTION:"downlink-connection",DOWNLINK_RECONNECTION:"downlink-reconnection",ON_TRACK:"ontrack",ICE_CONNECTION_STATE:"iceConnectionState",LOCAL_STREAM_INITIALIZE:"stream-initialize",SIGNAL_CONNECTION:"websocketConnectionState",SIGNAL_RECONNECTION:"websocketReconnectionState",UPDATE_STREAM:"update-stream",RECOVER_LOCAL_AUDIO_TRACK:"recover-local-audio-track",RECOVER_LOCAL_VIDEO_TRACK:"recover-local-video-track",RECOVER_SUBSCRIPTION:"recover-subscription",START_MIX_TRANSCODE:"start-mix-transcode",STOP_MIX_TRANSCODE:"stop-mix-transcode",PLAYER_ERROR:"player-error",SCHEDULE:"schedule",LOAD_WORKLET:"load-worklet",VIDEO_FROZEN_COUNT:"videoFrozenCount"},xm=1e4,Ea=1e4,Ta=1e4,ci="unified-plan",Ir="plan-b",di={MODE:{MANUAL:"manual",PRESET_LAYOUT:"preset-layout"},PLACE_HOLDER:{REMOTE:"$PLACE_HOLDER_REMOTE$"},STREAM_TYPE:{IT_AUDIO_VIDEO:0,IT_PICTURE:2,IT_CANVAS:3,IT_PURE_AUDIO:4,IT_PURE_VIDEO:5}},xi=1028,du=(r=>(r[r.UNPUBLISH=-1]="UNPUBLISH",r[r.PUBLISHING=0]="PUBLISHING",r[r.PUBLISHED=1]="PUBLISHED",r))(du||{}),Us=500,Um=1e3,Vm=m.BIG,wm=m.SMALL,Rn=10*1e3,Rr={MAIN:"schedule.rtc.qq.com",BACKUP:"schedule.rtc.qcloud.com",MAIN_OVERSEA:"schedule.rtc.tencentcloud.com",BACKUP_OVERSEA:"schedule-ecdn.rtc.tencentcloud.com"},Bm=2e3,$m={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},Sa=5,Ui="default",An=Ui,Hm="communications",Fm=Object.keys(_t),ga=["normal leave","timeout leave","kick","role change"],Ar=10,Cr=2e3,vt="ric",$t="raf",Ia="interval",yr="timeout",Vs=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId"];var VE=_(f(),1);var Vi=1e8;var Wm="trtc_env",Km=function(){return new URLSearchParams(location.search).get(Wm)||""},ws=i=>Number(i)<14e8,wi=function(i,t){let e;_n?e=_n:e=ws(i)?la:ua;let r=Math.floor(Math.random()*ss(2,31));return`${e}/v5/AVQualityReportSvc/C2S?random=${r}&sdkappid=${i}&cmdtype=${t}`};function lu(){return st?4:si?2:or?3:Ct?12:pr?5:hr?13:1}function pu(){return st?"Android":si?"iPhone":or?"iPad":Ct?"Mac":pr?"Windows":hr?"Linux":"unknown"}function Bs(){let{userAgent:i,connection:t}=navigator,e=(i.match(/NetType\/\S+/)||[])[0]||"";e=e.toLowerCase().replace("nettype/",""),e==="3gnet"&&(e="3g");let r=t&&t.type&&t.type.toLowerCase(),n=t&&t.effectiveType&&t.effectiveType.toLowerCase();n==="slow-2"&&(n="2g");let s=e||"unknown";if(r)switch(r){case"cellular":case"wimax":s=n||"unknown";break;case"wifi":s="wifi";break;case"ethernet":s="wired";break;case"none":case"other":case"unknown":default:s="unknown";break}return s}var jm=function(i){return{AbilityOption:{AVLimit:i,GeneralLimit:{CPULimit:{uint32_CPU_num:navigator.hardwareConcurrency||0,str_CPU_name:String(navigator.platform),uint32_CPU_maxfreq:0,model:"",uint32_total_memory:0},uint32_terminal_type:lu(),uint32_device_type:0,str_os_verion:pu(),uint32_link_type:1,str_client_version:Oi,uint32_net_type:oi[Bs()],ua:navigator.userAgent,version:""}}}};function Jm(i,t){for(let e of Reflect.ownKeys(t))if(e!=="constructor"&&e!=="prototype"&&e!=="name"){let r=Object.getOwnPropertyDescriptor(t,e)||"";Object.defineProperty(i,e,r)}return i}function Ym(i,t=48e3){return hu(i/4,t)}function hu(i,t=48e3){return i*1e3/t}function Xm(i,t=48e3){return mu(i,t)*4}function mu(i,t=48e3){return i*t/1e3}var _u=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},Nt=()=>{let i=navigator.language;return i=i.substring(0,2),i==="zh"},Ht=function(i){if(!i||typeof i!="object"||Object.prototype.toString.call(i)!="[object Object]")return!1;let t=Object.getPrototypeOf(i);if(t===null)return!0;let e=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return typeof e=="function"&&e instanceof e&&Function.prototype.toString.call(e)===Function.prototype.toString.call(Object)};function vr(i,t=1,e=1){return i<=1?e:vr(i-1,e,t+e)}function ot(i){return i>8?30*1e3:vr(i)*1e3}function Ee(i){return Reflect.apply(Object.prototype.toString,i,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var ce=i=>typeof i=="function",b=i=>typeof i=="undefined",oe=i=>typeof i=="string",de=i=>typeof i=="number",Ne=i=>typeof i=="boolean",Bi=i=>Ee(i)==="object",Oe=i=>Ee(i)==="array",zm=i=>Ee(i)==="MediaStreamTrack".toLowerCase(),ui=i=>i.isRemote,yn=i=>Ee(i)==="promise",vn=i=>ce(i)&&i.prototype.constructor===i,$s=i=>vn(i)?i.prototype.constructor.name:"",Aa=typeof AudioWorkletNode!="undefined";function Ca(i){return new Promise((t,e)=>{let r=[];i.forEach(n=>{n.then(t).catch(s=>{r.push(s),r.length===i.length&&e(r)})})})}function z(){return!performance||!performance.now?Date.now():Math.floor(performance.now())}var uu=i=>+i<10?`0${i}`:i,qm=i=>{let t=i.match(/^\d+\.\d+\.\d+/)[0];if(!t)return i;let e=t.split("."),r=uu(e[1])+uu(e[2]);return e[1]-15>0&&(e[1]="15"),e[2]-15>0&&(e[2]="15"),`${e.join(".")}.${r}`},Qm=Object.prototype.hasOwnProperty,{toString:GE}=Object.prototype;function Nn(i){if(i==null)return!0;if(typeof i=="boolean")return!1;if(typeof i=="number")return i===0;if(typeof i=="string"||typeof i=="function"||Array.isArray(i))return i.length===0;if(i instanceof Error)return i.message==="";if(Ht(i))switch(Object.prototype.toString.call(i)){case"[object File]":case"[object Map]":case"[object Set]":return i.size===0;case"[object Object]":{for(let t in i)if(Qm.call(i,t))return!1;return!0}}return!1}function li(i,t){return{userId:t,hasAudio:!!(i&gr),hasVideo:!!(i&Sr),hasAuxiliary:!!(i&Tn),hasSmall:!!(i&ha),audioMuted:!!(i&ks),videoMuted:!!(i&xs),audioAvailable:!!(i&gr)&&!(i&ks),videoAvailable:!!(i&Sr)&&!(i&xs)}}function Zm(i,t){return i>50||t>500?5:i>30||t>350?4:i>20||t>200?3:i>10||t>100?2:i>=0||t>=0?1:0}function e_(i){let t={urls:`turn:${i.url}`};return!b(i.username)&&!b(i.credential)&&(t.username=i.username,t.credential=i.credential,t.credentialType="password",b(i.credentialType)||(t.credentialType=i.credentialType)),t}function bn(i,t=!0){if(!oe(i))return 0;let e=i.split(".");return t?(Number(e[0])<<24|Number(e[1])<<16|Number(e[2])<<8|Number(e[3]))>>>0:(Number(e[3])<<24|Number(e[2])<<16|Number(e[1])<<8|Number(e[0]))>>>0}var Cn=function(i){return Oe(i)||Bi(i)},bt=function(i,t,e,r){if(!(Cn(i)&&Cn(t)))return 0;let n=0,s=Object.keys(t),o;for(let a=0,c=s.length;a<c;a++)if(o=s[a],!(b(t[o])||e&&e.includes(o)))if(Cn(i[o])&&Cn(t[o]))n+=bt(i[o],t[o],e,r);else{if(r&&r.includes(t[o]))continue;i[o]!==t[o]&&(i[o]=t[o],n+=1)}return n},Hs=i=>oe(i)?document.getElementById(i):i,t_=new Intl.DateTimeFormat("zh-CN",{dateStyle:"short",timeStyle:"medium"}),i_=()=>t_.format(new Date);function $i(i,t){try{if(Oe(i))return`[${i.map(n=>$i(n,t)).join(",")}]`;if(!Ht(i)||!Oe(t))return JSON.stringify(i);let e={},r=new Set(t);return Object.keys(i).forEach(n=>{r.has(n)&&(e[n]=i[n])}),JSON.stringify(e)}catch(e){return"{}"}}var JE=_(f(),1);function pi({url:i,body:t,method:e,timeout:r}){let n=new XMLHttpRequest;return new Promise((s,o)=>{n.onreadystatechange=()=>{if(n.readyState===4)if(n.status>=200&&n.status<300)try{let a=JSON.parse(n.response);s({data:a})}catch(a){s({data:n.response})}else o({status:n.status,statusText:n.statusText||"request failed!"})},n.timeout=r||5e3,n.open(e||"POST",i,!0),n.send(t)})}var qE=_(f(),1);var r_=0,n_=1,fu=2;function s_({retryFunction:i,settings:t,onError:e,onRetrying:r,onRetryFailed:n,context:s}){return function(...o){let{retries:a=5,timeout:c=1e3}=t,d=0,u=-1,l=r_,h=(I,T)=>E(this,null,function*(){let N=s||this;try{let $=yield i.apply(N,o);d=0,I($)}catch($){let x=()=>{clearTimeout(u),d=0,l=fu,T($)},F=()=>{l!==fu&&d<(ce(a)?a():a)?(d++,l=n_,ce(r)&&r.call(this,d,x),u=window.setTimeout(()=>{u=-1,h(I,T)},ce(c)?c(d):c)):(x(),ce(n)&&n.call(this,$))};ce(e)?e.call(N,$,F,T,o):F()}});return new Promise(h)}}var Dt=s_;var rT=_(f(),1);var Nr=class{constructor(t){p(this,"userId");p(this,"remoteUserId");p(this,"id");p(this,"sdkAppId");p(this,"type");p(this,"isLocal");this.id=t.id,this.userId=t.userId,this.sdkAppId=t.sdkAppId,this.remoteUserId=t.remoteUserId,this.isLocal=Ne(t.isLocal)?t.isLocal:!0,this.type=this.isLocal?"":t.type}createChild(t){return Object.setPrototypeOf(t,this)}setUserId(t){this.userId=t}setSdkAppId(t){this.sdkAppId=t}log(t,e){let r=this.isLocal?this.userId:this.remoteUserId;e.unshift(`[${this.isLocal?"\u2191":"\u2193"}${this.type&&this.type!=="main"?"*":""}${this.id}${r?`|${r}`:""}]`),O.log(t,e,b(this.userId)||Nn(this.userId),this.userId,this.sdkAppId)}info(...t){this.log(2,t)}debug(...t){this.log(1,t)}warn(...t){this.log(3,t)}error(...t){this.log(4,t)}};var oT=_(f(),1),Eu=_(rt(),1),o_=new Eu.default,C=o_;var lT=_(f(),1);var cT=_(f(),1),ya=(W=>(W.ROOM_DESTROY="1",W.JOIN_START="21",W.JOIN_SCHEDULE_SUCCESS="22",W.JOIN_SIGNAL_CONNECTION_START="23",W.JOIN_SIGNAL_CONNECTION_END="24",W.JOIN_SEND_CMD="25",W.JOIN_RECEIVED_CMD_RES="26",W.JOIN_SUCCESS="27",W.JOIN_FAILED="28",W.LEAVE_START="51",W.LEAVE_SEND_CMD="52",W.LEAVE_SUCCESS="53",W.PUBLISH_START="61",W.SEND_FIRST_VIDEO_FRAME="62",W.SUBSCRIBE_START="81",W.SUBSCRIBE_SUCCESS="82",W.UNSUBSCRIBE_SUCCESS="83",W.LOCAL_TRACK_CAPTURE_START="101",W.LOCAL_TRACK_CAPTURE_SUCCESS="102",W.LOCAL_TRACK_CAPTURE_FAILED="103",W.LOCAL_TRACK_PUBLISHED="104",W.LOCAL_TRACK_UNPUBLISHED="105",W.LOCAL_TRACK_REPLACED="106",W.SWITCH_DEVICE_SUCCESS="107",W.TRACK_MUTED="108",W.TRACK_UNMUTED="109",W.REMOTE_TRACK_SUBSCRIBED="110",W.REMOTE_TRACK_UNSUBSCRIBED="111",W.PLAY_TRACK_START="151",W.PLAYER_STATE_CHANGED="152",W.VIDEO_LOADED_DATA="153",W.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",W.WORKLET_LOADED_SUCCESS="155",W.WORKLET_LOADED_FAILED="156",W.SIGNAL_CONNECTION_STATE_CHANGED="201",W.PEER_CONNECTION_STATE_CHANGED="202",W.HEARTBEAT_REPORT="251",W.RECEIVED_PUBLISHED_USER_LIST="252",W.REMOTE_PUBLISH_STATE_CHANGED="253",W.AUDIO_LEVEL_INTERVAL="260",W.NETWORK_QUALITY="261",W.API_SUCCESS_RATE="262",W))(ya||{});var S=ya;var a_="%cTRTC%c%s",c_="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",d_="display: inline",u_=!(nt||st||oa),va=class{constructor(){p(this,"_isEnableUploadLog",!0);p(this,"_localJoinedUser",new Map);p(this,"_queue",[]);p(this,"_timeoutId",-1);p(this,"_logLevel",1);p(this,"_logLevelToUpload",2);!Tr&&!mn&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){C.on(S.JOIN_SCHEDULE_SUCCESS,({schedule:t})=>{var e;((e=t==null?void 0:t.config)==null?void 0:e.logLevelToUpload)&&_t[t.config.logLevelToUpload]&&(this._logLevelToUpload=t.config.logLevelToUpload)}),C.on(S.JOIN_SUCCESS,({room:t})=>{this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload()}),C.once(S.JOIN_FAILED,()=>{this.startUpload()}),C.on(S.LEAVE_SUCCESS,({room:t})=>{this.deleteJoinedUser(t.userId)})}startUpload(){this._timeoutId===-1&&this.uploadInterval()}addJoinedUser(t){this._localJoinedUser.set(t.userId,t),this.startUpload()}deleteJoinedUser(t){this._localJoinedUser.delete(t)}uploadInterval(){this.upload().catch(()=>{}),this._timeoutId=window.setTimeout(()=>this.uploadInterval(),2e3)}getLogsToUpload(){let t={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&this._localJoinedUser.size===0)return t;let e=0;for(;e<this._queue.length&&e!==50;e++){let r=this._queue[e];if(r.forAllJoinedClients)this._localJoinedUser.forEach(({userId:n,sdkAppId:s})=>{t.map.has(n)?t.map.get(n).logs.push(r):t.map.set(n,{userId:n,sdkAppId:s,logs:[r]})});else if(oe(r.userId)&&de(r.sdkAppId)){let{userId:n,sdkAppId:s}=r;t.map.has(n)?t.map.get(n).logs.push(r):t.map.set(n,{userId:n,sdkAppId:s,logs:[r]})}}return t.map.size>0&&(t.splicedQueue=this._queue.splice(0,e)),t}upload(){return E(this,null,function*(){if(this._queue.length===0||!this._isEnableUploadLog)return;let{map:t,splicedQueue:e}=this.getLogsToUpload();if(t.size===0)return;try{let n=[...t.values()];for(let s=0;s<n.length;s++){let{userId:o,sdkAppId:a,logs:c}=n[s];yield this.uploadLogWithRetry(JSON.stringify({timestamp:ls(),sdkAppId:String(a),userId:o,version:$e,log:c.map(d=>d.log).join(`
75
+ `)}),a),c.forEach(d=>d.uploaded=!0)}}catch(n){}let r=e.filter(n=>!n.uploaded);r.length>0&&(this._queue=r.concat(this._queue))})}uploadLogWithRetry(t,e){return Dt({retryFunction:()=>pi({url:wi(e,Li.LOG),body:t,timeout:5e3}),settings:{retries:3,timeout:1e3},onError:(r,n)=>{n()}})()}getPrefix(t){let e=new Date;e.setTime(en());let r=String(e.getMilliseconds());return"padStart"in String.prototype&&(r=r.toString().padStart(3,"0")),`[${e.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")}:${r}] <${_t[t]}>`}getLogLevel(){return this._logLevel}setLogLevel(t){b(_t[t])||(this._logLevel!==t&&this.info("setLogLevel",t),this._logLevel=t)}enableUploadLog(){this._isEnableUploadLog=!0}disableUploadLog(){this.warn("disableUploadLog"),this._isEnableUploadLog=!1}logChunkToString(t){if(oe(t))return t;try{return JSON.stringify(t)}catch(e){return""}}log(t,e,r=!0,n,s){var a;if(e.unshift(this.getPrefix(t)),this._isEnableUploadLog&&t>=this._logLevelToUpload&&this._queue.push({log:e.reduce((c,d)=>`${c} ${this.logChunkToString(d)}`.trim(),""),level:t,userId:n,sdkAppId:s,forAllJoinedClients:r}),t<this._logLevel)return;let o=((a=_t[t])==null?void 0:a.toLowerCase())||"info";u_?console[o](a_,c_,d_,...e):console[o](...e)}debug(...t){this.log(1,t)}info(...t){this.log(2,t)}warn(...t){this.log(3,t)}error(...t){this.log(4,t)}createLogger(t){return new Nr(t)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),r=e?Number(e):-1;_t[r]&&(this._logLevelToUpload=r)}},O=new va;var yT=_(f(),1),l_=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{let t=Math.random()*16|0;return(i=="x"?t:t&3|8).toString(16)})},Na=l_;var OT=_(f(),1);var ba=class{constructor(){p(this,"_prefix","TRTC");p(this,"_queue",new Map);this.checkStorage()}getRealKey(t){return`${this._prefix}_${t}`}checkStorage(){if(!Vt())return;setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter(r=>{if(r.startsWith(this._prefix)){let n=JSON.parse(localStorage.getItem(r));if(n&&n.expiresIn<Date.now())return!0}return!1}).forEach(r=>localStorage.removeItem(r))}doFlush(){if(!!Vt())try{for(let[t,e]of this._queue)localStorage.setItem(t,JSON.stringify(e))}catch(t){O.warn(t)}}getItem(t){if(!Vt())return null;try{let e=JSON.parse(localStorage.getItem(this.getRealKey(t)));return e&&e.expiresIn>=Date.now()?e.value:null}catch(e){O.warn(e)}}setItem(t,e){if(!!Vt())try{let r={expiresIn:Date.now()+Os,value:e};this._queue.set(this.getRealKey(t),r)}catch(r){O.warn(r)}}deleteItem(t){if(!Vt())return!1;try{return t=this.getRealKey(t),this._queue.delete(t),localStorage.removeItem(t),!0}catch(e){return O.warn(e),!1}}clear(){if(!!Vt())try{localStorage.clear()}catch(t){O.warn(t)}}},br=new ba;var rR=_(f(),1);var Gt={};Jr(Gt,{HTTPS_API:()=>T_,IS_GET_CAPABILITIES_SUPPORTED:()=>ka,IS_GET_SETTINGS_SUPPORTED:()=>Ft,IS_SEI_SUPPORTED:()=>_i,IS_SPC_SUPPORTED:()=>Ks,basis:()=>R_,checkSystemRequirementsInternal:()=>Ma,decodeSupportStatus:()=>Gs,encodeSupportStatus:()=>Au,getBrowserInfo:()=>f_,getDisplayResolution:()=>yu,getOSName:()=>Cu,isAddTransceiverSupported:()=>mi,isBrowserSupported:()=>Da,isGetReceiversSupported:()=>Hi,isGetSendersSupported:()=>Dr,isGetTransceiversSupported:()=>at,isGetUserMediaSupported:()=>vu,isMediaDevicesSupported:()=>Fs,isMediaSessionSupported:()=>Ou,isMediaStreamTrackProcessorSupported:()=>Pa,isReplaceTrackSupported:()=>I_,isScreenCaptureApiAvailable:()=>La,isSelectedCandidatePair:()=>hi,isSetParametersSupported:()=>Dn,isSmallStreamAPISupported:()=>bu,isSmallStreamSupported:()=>Ws,isStopTransceiverSupported:()=>g_,isTRTCSupported:()=>E_,isUnifiedPlanDefault:()=>S_,isUsedInHttpProtocol:()=>Oa,isWebAudioSupported:()=>Nu,isWebCodecSupported:()=>Du,isWebCodecsSupported:()=>Ru,isWebRTCSupported:()=>xa,isWebTransportSupported:()=>Pu});var ZT=_(f(),1);var xT=_(f(),1);var V={AVOID_REPEATED_CALL:"AVOID_REPEATED_CALL",INVALID_PARAMETER_REQUIRED:"INVALID_PARAMETER_REQUIRED",INVALID_PARAMETER_TYPE:"INVALID_PARAMETER_TYPE",INVALID_PARAMETER_EMPTY:"INVALID_PARAMETER_EMPTY",INVALID_PARAMETER_INSTANCE:"INVALID_PARAMETER_INSTANCE",INVALID_PARAMETER_RANGE:"INVALID_PARAMETER_RANGE",INVALID_PARAMETER_MIN:"INVALID_PARAMETER_MIN",INVALID_PARAMETER_MAX:"INVALID_PARAMETER_MAX",INVALID_PARAMETER_STREAMTYPE:"INVALID_PARAMETER_STREAMTYPE",API_CALL_TIMEOUT:"API_CALL_TIMEOUT",SIGNAL_CHANNEL_RECONNECTION_FAILED:"SIGNAL_CHANNEL_RECONNECTION_FAILED",SIGNAL_CHANNEL_SETUP_FAILED:"SIGNAL_CHANNEL_SETUP_FAILED",ERROR_MESSAGE:"ERROR_MESSAGE",EXCHANGE_SDP_TIMEOUT:"EXCHANGE_SDP_TIMEOUT",DOWNLINK_RECONNECTION_FAILED:"DOWNLINK_RECONNECTION_FAILED",EXCHANGE_SDP_FAILED:"EXCHANGE_SDP_FAILED",UPDATE_OFFER_TIMEOUT:"UPDATE_OFFER_TIMEOUT",UPLINK_RECONNECTION_FAILED:"UPLINK_RECONNECTION_FAILED",INVALID_RECORDID:"INVALID_RECORDID",INVALID_PURE_AUDIO:"INVALID_PURE_AUDIO",INVALID_STREAMID:"INVALID_STREAMID",INVALID_USER_DEFINE_RECORDID:"INVALID_USER_DEFINE_RECORDID",INVALID_USER_DEFINE_PUSH_ARGS:"INVALID_USER_DEFINE_PUSH_ARGS",INVALID_PROXY:"INVALID_PROXY",INVALID_JOIN:"INVALID_JOIN",INVALID_ROOMID_STRING:"INVALID_ROOMID_STRING",INVALID_ROOMID_INTEGER:"INVALID_ROOMID_INTEGER",INVALID_SIGNAL_CHANNEL:"INVALID_SIGNAL_CHANNEL",JOIN_ROOM_TIMEOUT:"JOIN_ROOM_TIMEOUT",JOIN_ROOM_FAILED:"JOIN_ROOM_FAILED",REJOIN_ROOM_FAILED:"REJOIN_ROOM_FAILED",INVALID_DESTROY:"INVALID_DESTROY",INVALID_PUBLISH:"INVALID_PUBLISH",INVALID_UNPUBLISH:"INVALID_UNPUBLISH",INVALID_AUDIENCE:"INVALID_AUDIENCE",INVALID_INITIALIZE:"INVALID_INITIALIZE",INVALID_DUPLICATE_PUBLISHING:"INVALID_DUPLICATE_PUBLISHING",INVALID_SUBSCRIBE_UNDEFINED:"INVALID_SUBSCRIBE_UNDEFINED",INVALID_SUBSCRIBE_LOCAL:"INVALID_SUBSCRIBE_LOCAL",INVALID_REMOTE_STREAM:"INVALID_REMOTE_STREAM",SUBSCRIBE_FAILED:"SUBSCRIBE_FAILED",INVALID_ROLE:"INVALID_ROLE",INVALID_PARAMETER_SWITCH_ROLE:"INVALID_PARAMETER_SWITCH_ROLE",INVALID_OPERATION_SWITCH_ROLE:"INVALID_OPERATION_SWITCH_ROLE",SWITCH_ROLE_TIMEOUT:"SWITCH_ROLE_TIMEOUT",SWITCH_ROLE_FAILED:"SWITCH_ROLE_FAILED",CLIENT_BANNED:"CLIENT_BANNED",INVALID_OPERATION_START_PUBLISH_CDN:"INVALID_OPERATION_START_PUBLISH_CDN",INVALID_OPERATION_STOP_PUBLISH_CDN:"INVALID_OPERATION_STOP_PUBLISH_CDN",INVALID_STREAM_ID:"INVALID_STREAM_ID",START_PUBLISH_CDN_FAILED:"START_PUBLISH_CDN_FAILED",STOP_PUBLISH_CDN_FAILED:"STOP_PUBLISH_CDN_FAILED",START_MIX_TRANSCODE:"START_MIX_TRANSCODE",STOP_MIX_TRANSCODE:"STOP_MIX_TRANSCODE",INVALID_AUDIO_VOLUME:"INVALID_AUDIO_VOLUME",ENABLE_SMALL_STREAM_PUBLISHED:"ENABLE_SMALL_STREAM_PUBLISHED",DISABLE_SMALL_STREAM_PUBLISHED:"DISABLE_SMALL_STREAM_PUBLISHED",NOT_SUPPORTED_SMALL_STREAM:"NOT_SUPPORTED_SMALL_STREAM",INVALID_SMALL_STREAM_PROFILE:"INVALID_SMALL_STREAM_PROFILE",INVALID_PARAMETER_REMOTE_STREAM:"INVALID_PARAMETER_REMOTE_STREAM",INVALID_OPERATION_CHANGE_SMALL:"INVALID_OPERATION_CHANGE_SMALL",REMOTE_NOT_PUBLISH_SMALL_STREAM:"REMOTE_NOT_PUBLISH_SMALL_STREAM",INVALID_SWITCH_DEVICE:"INVALID_SWITCH_DEVICE",INVALID_SWITCH_DEVICE_PUBLISHING:"INVALID_SWITCH_DEVICE_PUBLISHING",INVALID_REPLACE_TRACK:"INVALID_REPLACE_TRACK",INVALID_INITIALIZE_LOCAL_STREAM:"INVALID_INITIALIZE_LOCAL_STREAM",INVALID_ADD_TRACK_REPETITIVE:"INVALID_ADD_TRACK_REPETITIVE",INVALID_ADD_TRACK_REMOVING:"INVALID_ADD_TRACK_REMOVING",INVALID_ADD_TRACK_PUBLISHING:"INVALID_ADD_TRACK_PUBLISHING",INVALID_STREAM_INITIALIZED:"INVALID_STREAM_INITIALIZED",INVALID_ADD_TRACK_NUMBER:"INVALID_ADD_TRACK_NUMBER",INVALID_REMOVE_AUDIO_TRACK:"INVALID_REMOVE_AUDIO_TRACK",INVALID_REMOVE_AUDIO_ADDING:"INVALID_REMOVE_AUDIO_ADDING",INVALID_REMOVE_AUDIO_ON:"INVALID_REMOVE_AUDIO_ON",INVALID_REMOVE_TRACK_PUBLISHING:"INVALID_REMOVE_TRACK_PUBLISHING",INVALID_REMOVE_TRACK_NOT_TRACK:"INVALID_REMOVE_TRACK_NOT_TRACK",INVALID_REMOVE_TRACK_NUMBER:"INVALID_REMOVE_TRACK_NUMBER",INVALID_REPLACE_TRACK_NO_TRACK:"INVALID_REPLACE_TRACK_NO_TRACK",REPEAT_JOIN:"REPEAT_JOIN",CLIENT_DESTROYED:"CLIENT_DESTROYED",START_MIX_TRANSCODE_FAILED:"START_MIX_TRANSCODE_FAILED",STOP_MIX_TRANSCODE_FAILED:"STOP_MIX_TRANSCODE_FAILED",MIX_TRANSCODE_NOT_STARTED:"MIX_TRANSCODE_NOT_STARTED",CANNOT_LESS_THAN_ZERO:"CANNOT_LESS_THAN_ZERO",MIX_PARAMS_VIDEO_FRAMERATE:"MIX_PARAMS_VIDEO_FRAMERATE",MIX_PARAMS_VIDEO_GOP:"MIX_PARAMS_VIDEO_GOP",MIX_PARAMS_AUDIO_BITRATE:"MIX_PARAMS_AUDIO_BITRATE",MIX_PARAMS_USER_Z_ORDER:"MIX_PARAMS_USER_Z_ORDER",MIX_PARAMS_NOT_SELF:"MIX_PARAMS_NOT_SELF",MIX_PARAMS_USER_STREAM:"MIX_PARAMS_USER_STREAM",INVALID_PLAY:"INVALID_PLAY",INVALID_ELEMENT_ID:"INVALID_ELEMENT_ID",INVALID_ELEMENT_ID_TYPE:"INVALID_ELEMENT_ID_TYPE",PLAY_FAILED:"PLAY_FAILED",INVALID_USERID:"INVALID_USERID",INVALID_CREATE_STREAM_SOURCE:"INVALID_CREATE_STREAM_SOURCE",INVALID_CREATE_STREAM_SCREEN:"INVALID_CREATE_STREAM_SCREEN",INVALID_CREATE_STREAM_AUDIO:"INVALID_CREATE_STREAM_AUDIO",INVALID_CREATE_STREAM_SCREEN_AUDIO:"INVALID_CREATE_STREAM_SCREEN_AUDIO",NOT_SUPPORTED_HTTP:"NOT_SUPPORTED_HTTP",NOT_SUPPORTED_WEBRTC:"NOT_SUPPORTED_WEBRTC",NOT_SUPPORTED_PROFILE:"NOT_SUPPORTED_PROFILE",NOT_SUPPORTED_MEDIA:"NOT_SUPPORTED_MEDIA",NOT_SUPPORTED_H264ENCODE:"NOT_SUPPORTED_H264ENCODE",NOT_SUPPORTED_H264DECODE:"NOT_SUPPORTED_H264DECODE",NOT_SUPPORTED_TRACK:"NOT_SUPPORTED_TRACK",NOT_SUPPORTED_SWITCH_DEVICE:"NOT_SUPPORTED_SWITCH_DEVICE",NOT_SUPPORTED_CAPTURE:"NOT_SUPPORTED_CAPTURE",NOT_SUPPORTED_AUX:"NOT_SUPPORTED_AUX",MICROPHONE_NOT_FOUND:"MICROPHONE_NOT_FOUND",CAMERA_NOT_FOUND:"CAMERA_NOT_FOUND",SIGNAL_RESPONSE_FAILED:"SIGNAL_RESPONSE_FAILED",CATCH_HANDLER_ERROR:"CATCH_HANDLER_ERROR",API_NOT_EXIST:"API_NOT_EXIST",CONNECTION_CLOSED:"CONNECTION_CLOSED",SUBSCRIBE_ALL_FALSE:"SUBSCRIBE_ALL_FALSE",SEI_NOT_SUPPORT:"SEI_NOT_SUPPORT",SEI_DISABLED:"SEI_DISABLED",SEI_EMPTY:"SEI_EMPTY",SEI_OVERSIZE:"SEI_OVERSIZE",SEI_BEFORE_PUBLISH:"SEI_BEFORE_PUBLISH",SEI_NOT_VIDEO:"SEI_NOT_VIDEO",CALL_FREQUENCY_LIMIT:"CALL_FREQUENCY_LIMIT",CONNECTION_ABORTED:"CONNECTION_ABORTED",API_CALL_ABORTED:"API_CALL_ABORTED",DUPLICATE_AUX:"DUPLICATE_AUX"},xe={AVOID_REPEATED_CALL(i){return`previous ${i.name}() is ongoing, please avoid repeated calls.`},INVALID_PARAMETER_REQUIRED({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' is a required param when calling ${e}(), received: ${r}.`},INVALID_PARAMETER_TYPE({key:i,rule:t,fnName:e,value:r}){let n=`${i||t.name}`,s="";return Array.isArray(t.type)?s=t.type.join("|"):s=t.type,`'${n}' must be type of ${s} when calling ${e}(), received type: ${Ee(r)}.`},INVALID_PARAMETER_EMPTY({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' cannot be '${r}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:i,rule:t,fnName:e,value:r}){let n=`${i||t.name}`,s=`${t.instanceOf.name||t.instanceOf}`;return`'${n}' must be instanceof ${s} when calling ${e}(), received type: ${Ee(r)}.`},INVALID_PARAMETER_RANGE({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' must be one of ${t.values.join("|")} when calling ${e}(), received: ${r}.`},INVALID_PARAMETER_MIN({key:i,rule:t,fnName:e,value:r}){return`the min value of ${i||t.name} is ${t.min}, received: ${r}.`},INVALID_PARAMETER_MAX({key:i,rule:t,fnName:e,value:r}){return`the max value of ${i||t.name} is ${t.max}, received: ${r}.`},API_CALL_TIMEOUT(i){return`${i.commandDesc||i.command} timeout observed.`},SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED(i){return`SignalChannel setup failure: (errorCode: ${i.errorCode}, errorMsg: ${i.errorMsg} }).`},ERROR_MESSAGE(i){let t=`${i.type} failed`;return i.message&&(t=`${t}: ${i.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(i){return`exchange sdp failed ${i.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(i){return`'${i}' must be validate string when useStringRoomId is true.`},INVALID_ROOMID_INTEGER(i){return`'${i}' 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:i,code:t}){return`Failed to join room - ${i} code: ${t}`},REJOIN_ROOM_FAILED(i){return`reJoin room: ${i.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(i){return`duplicate ${i} stream publishing, please unpublish your prev ${i} 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:i,userId:t,streamType:e}){return`failed to subscribe ${t} ${e} stream, reason: ${i}.`},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(i){return`switchRole failed, errCode: ${i.code} errMsg: ${i.message}.`},CLIENT_BANNED(i){return`client was banned because of ${i.message}.`},INVALID_OPERATION_START_PUBLISH_CDN:"please call startPublishCDNStream() after join room and publish the local stream.",INVALID_OPERATION_STOP_PUBLISH_CDN:"please call startPublishCDNStream() before stopPublishCDNStream().",START_PUBLISH_CDN_FAILED(i){return`startPublishCDNStream failed, errMsg: ${i.message}.`},STOP_PUBLISH_CDN_FAILED(i){return`stopPublishCDNStream failed, errMsg: ${i.message}.`},INVALID_STREAM_ID(i){return`'${i}' 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_TRACK:"localStream has not this track.",INVALID_REMOVE_TRACK_NUMBER:"remove the only video track is not supported, please use replaceTrack or muteVideo.",INVALID_REPLACE_TRACK_NO_TRACK(i){return`cannot replace ${i.kind} track because stream has not ${i.kind} track`},START_MIX_TRANSCODE_FAILED(i){return`startMixTranscode failed, errMsg: ${i.message}.`},STOP_MIX_TRANSCODE_FAILED(i){return`stopMixTranscode failed, errMsg: ${i.message}.`},MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' cannot be less than 0 when calling ${e}().`},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(i){return`'${i}' 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:i,fnName:t})=>`'${i}' is not found in the document object when calling ${t}().`,INVALID_ELEMENT_ID_TYPE:({key:i,fnName:t,type:e})=>`the element corresponding to '${i}' must be instanceof HTMLElement when calling ${t}(), received: ${e}.`,PLAY_FAILED:i=>`${i.media} play failed\uFF0Cbrowser exception: ${i.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(i){return`${i}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(i){return`${i.signalResponse} failed, response code is ${i.code} , errMsg: ${i.message}.`},CATCH_HANDLER_ERROR({name:i,event:t}){return`an error was caught on ${i}.on('${t}', handler), please check your code on 'handler'.`},API_NOT_EXIST({name:i}){return`experimental api ${i} does not exist.`},REPEAT_JOIN:i=>`[${i}] 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:i}){return`failed to call ${i}() because client was destroyed.`},SEI_NOT_SUPPORT:i=>`not support to sendSEIMessage${i===!1?" without using h264 codec":""}`,SEI_DISABLED:"SEI is disabled, to enable SEI: TRTC.createClient({ enableSEI: true })",SEI_EMPTY:"buffer cannot be empty",SEI_OVERSIZE:i=>`buffer size(${i}) 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:i,name:t,timesInSecond:e,maxSizeInSecond:r})=>`api ${t} call ${i?"size":"times"} is over ${i?`${r} bytes`:e} in a second.`,CONNECTION_ABORTED(i){return`connection aborted due to: ${i}`},API_CALL_ABORTED(i){let t;return i.message.includes("REMOTE_STREAM_NOT_EXIST")?t=`Subscribe ${i.userId} ${i.streamType} stream aborted, reason: remote user ${i.userId} unpublished stream.`:t=`API aborted, reason: ${i.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.",INVALID_PARAMETER_STREAMTYPE:i=>`'streamType' is required when 'userId' is not '*', calling ${i}()`};var WT=_(f(),1);var UT=_(f());function Tu(i){return Reflect.apply(Object.prototype.toString,i,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var p_={AVOID_REPEATED_CALL(i){return`\u524D\u4E00\u4E2A ${i.name}() \u8C03\u7528\u6B63\u5728\u8FDB\u884C\u4E2D, \u8BF7\u907F\u514D\u91CD\u590D\u8C03\u7528\u3002`},INVALID_PARAMETER_REQUIRED({key:i,rule:t,fnName:e,value:r}){return`\u8C03\u7528 ${e}() \u65B9\u6CD5\u7684\u65F6\u5019 '${i||t.name}' \u662F\u5FC5\u987B\u7684\u53C2\u6570, \u6536\u5230\u7684\u503C\u4E3A: ${r}\u3002`},INVALID_PARAMETER_TYPE({key:i,rule:t,fnName:e,value:r}){let n=`${i||t.name}`,s="";return Array.isArray(t.type)?s=t.type.join("|"):s=t.type,`\u8C03\u7528 ${e}() \u65B9\u6CD5\u7684\u65F6\u5019 '${n}' \u5FC5\u987B\u662F ${s} \u7C7B\u578B, \u6536\u5230\u7684\u7C7B\u578B\u662F: ${Tu(r)}\u3002`},INVALID_PARAMETER_EMPTY({key:i,rule:t,fnName:e,value:r}){return`\u8C03\u7528 ${e}() \u7684\u65F6\u5019 '${i||t.name}' \u4E0D\u80FD\u662F '${r}'\u3002`},INVALID_PARAMETER_INSTANCE({key:i,rule:t,fnName:e,value:r}){let n=`${i||t.name}`,s=`${t.instanceOf.name||t.instanceOf}`;return`\u8C03\u7528 ${e}() \u7684\u65F6\u5019 '${n}' \u539F\u578B\u5FC5\u987B\u662F ${s} , \u6536\u5230\u7684\u662F: ${Tu(r)}\u3002`},INVALID_PARAMETER_RANGE({key:i,rule:t,fnName:e,value:r}){return`\u8C03\u7528 ${e}() \u7684\u65F6\u5019 '${i||t.name}' \u5FC5\u987B\u662F ${t.values.join("|")} \u7684\u5176\u4E2D\u4E00\u79CD, \u6536\u5230\u7684\u662F: ${r}\u3002`},API_CALL_TIMEOUT(i){return`${i.commandDesc||i.command} \u8D85\u65F6\u3002`},SIGNAL_CHANNEL_RECONNECTION_FAILED:"\u4FE1\u4EE4\u901A\u9053\u91CD\u8FDE\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u4F60\u7684\u7F51\u7EDC\u3002",SIGNAL_CHANNEL_SETUP_FAILED(i){return`\u4FE1\u4EE4\u901A\u9053\u5EFA\u7ACB\u5931\u8D25: (\u9519\u8BEF\u7801: ${i.errorCode}, \u9519\u8BEF\u4FE1\u606F: ${i.errorMsg} })\u3002`},ERROR_MESSAGE(i){let t=`${i.type} \u5931\u8D25\u3002`;return i.message&&(t=`${t}: ${i.message}\u3002`),t},SUBSCRIPTION_TIMEOUT:"\u8FDC\u7A0B\u670D\u52A1\u5668\u4E0D\u54CD\u5E94\u8BA2\u9605\u884C\u4E3A\u3002",EXCHANGE_SDP_TIMEOUT:"\u4EA4\u6362 sdp \u8D85\u65F6\uFF0C\u8BF7\u5237\u65B0\u7F51\u7EDC\u91CD\u8BD5\u3002",DOWNLINK_RECONNECTION_FAILED:"\u4E0B\u884C\u91CD\u8FDE\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u60A8\u7684\u7F51\u7EDC\u5E76\u91CD\u65B0\u52A0\u5165\u623F\u95F4\u3002",EXCHANGE_SDP_FAILED(i){return`\u4EA4\u6362 SDP \u5931\u8D25\uFF0C\u539F\u56E0 ${i.errMsg}\u3002`},REPLACE_TRACK_INVALID:"LocalStream \u53D1\u5E03\u4E4B\u540E\u624D\u53EF\u4EE5\u8C03\u7528 replaceTrack\u3002",UPDATE_OFFER_TIMEOUT:"\u66F4\u65B0 offer \u8D85\u65F6\uFF0C\u8BF7\u5237\u65B0\u7F51\u7EDC\u91CD\u8BD5\u3002",UPLINK_RECONNECTION_FAILED:"\u4E0A\u884C\u91CD\u8FDE\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u60A8\u7684\u7F51\u7EDC\u5E76\u91CD\u65B0\u63A8\u6D41\u3002",INVALID_RECORDID:"recordId \u5FC5\u987B\u662F\u6570\u5B57\u3002",INVALID_PURE_AUDIO:"pureAudioPushMode \u5FC5\u987B\u662F\u6570\u5B571\u62162\u3002",INVALID_STREAMID:"streamId \u5FC5\u987B\u662F 64 \u5B57\u8282\u4EE5\u5185\u7684\u5B57\u7B26\u4E32\uFF0C\u5E76\u4E14\u4E0D\u80FD\u4E3A\u7A7A\u3002",INVALID_USER_DEFINE_RECORDID:"userDefineRecordId \u5FC5\u987B\u662F\u5305\u542B (a-zA-Z)\u3001(0-9)\u3001\u4E0B\u5212\u7EBF\u548C\u8FDE\u5B57\u7B26\u7684\u5B57\u7B26\u4E32\u5B57\u9762\u91CF\uFF0C64 \u4E2A\u5B57\u8282\u4EE5\u5185\uFF0C\u4E14\u4E0D\u4E3A\u7A7A\u3002",INVALID_USER_DEFINE_PUSH_ARGS:"userDefinePushArgs \u5FC5\u987B\u662F 256 \u5B57\u8282\u4EE5\u5185\u7684\u5B57\u7B26\u4E32\u6587\u5B57\uFF0C\u5E76\u4E14\u4E0D\u80FD\u4E3A\u7A7A\u3002",INVALID_PROXY:"\u4EE3\u7406\u670D\u52A1\u5668 url \u5FC5\u987B\u4EE5\u201Cwss://\u201D\u5F00\u5934\u3002",INVALID_JOIN:"join() \u65B9\u6CD5\u4E0D\u80FD\u88AB\u91CD\u590D\u8C03\u7528\u3002",INVALID_ROOMID_STRING(i){return`\u5F53 useStringRoomId \u4E3A true \u65F6\uFF0C'${i}' \u5FC5\u987B\u662F\u5408\u6CD5\u5B57\u7B26\u4E32\u3002`},INVALID_ROOMID_INTEGER(i){return`\u5F53 useStringRoomId \u4E3A false \u65F6\uFF0C'${i}' \u5FC5\u987B\u662F\u5408\u6CD5\u6574\u6570\u5728\u533A\u95F4[1, 4294967294]\u3002`},INVALID_SIGNAL_CHANNEL:"SignalChannel \u8FD8\u672A\u521D\u59CB\u5316\u597D\u3002",JOIN_ROOM_TIMEOUT:"\u8FDB\u623F\u8D85\u65F6\u3002",JOIN_ROOM_FAILED(i){return`\u8FDB\u623F\u5931\u8D25\uFF0C\u539F\u56E0\uFF1A${i.error}\u3002`},REJOIN_ROOM_FAILED(i){return`\u91CD\u8FDB\u623F: ${i.roomId} \u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC\u72B6\u51B5\u3002`},INVALID_LEAVE:"\u8BF7\u5728\u8C03\u7528 destroy() \u65B9\u6CD5\u4E4B\u524D\u8C03\u7528 leave()\u3002",INVALID_PUBLISH:"\u8BF7\u5728\u8C03\u7528 publish() \u65B9\u6CD5\u4E4B\u524D\u8C03\u7528 join()\u3002",INVALID_UNPUBLISH:"\u8FD8\u6CA1\u6709\u88AB publish\u3002",INVALID_AUDIENCE:"\u5728\u89C2\u4F17\u6A21\u5F0F\u4E0B\u4E0D\u5141\u8BB8\u8C03\u7528 publish()\uFF0C\u8BF7\u5148\u5207\u6362\u6210\u4E3B\u64AD\u6A21\u5F0F\u3002",INVALID_INITIALIZE:"\u65E0\u6CD5\u53D1\u5E03 stream\uFF0C\u539F\u56E0\uFF1AlocalStream \u672A\u521D\u59CB\u5316\u3001\u6B63\u5728\u5207\u6362\u8BBE\u5907\u3001\u5DF2\u7ECF\u8C03\u7528 localStream.close() \u5173\u95ED\u91C7\u96C6",INVALID_DUPLICATE_PUBLISHING:"\u91CD\u590D\u53D1\u5E03\uFF0C\u8BF7\u5148 unpublish \u4E4B\u540E\uFF0C\u518D\u91CD\u65B0 publish\u3002",INVALID_SUBSCRIBE_UNDEFINED:"stream \u53C2\u6570\u662F undefined \u6216\u8005 null\u3002",INVALID_SUBSCRIBE_LOCAL:"stream \u53C2\u6570\u4E0D\u80FD\u4E3A\u672C\u5730\u6D41\u3002",INVALID_REMOTE_STREAM:"remoteStream \u4E0D\u5B58\u5728\uFF0C\u5DF2\u88AB\u8FDC\u7AEF client \u53D6\u6D88\u53D1\u5E03\u3002",SUBSCRIBE_FAILED(i){let t="\u8BA2\u9605\u6D41\u5931\u8D25\uFF0C\u539F\u56E0: ";return i.message.includes("REMOTE_STREAM_NOT_EXIST")?t+="\u8FDC\u7AEF\u7528\u6237\u5DF2\u53D6\u6D88\u63A8\u6D41\uFF0C\u65E0\u6CD5\u8BA2\u9605\u8BE5\u8FDC\u7AEF\u6D41\u3002":t+=`${i.message}\u3002`,t},INVALID_ROLE:"\u53EA\u6709\u76F4\u64AD\u6A21\u5F0F\u624D\u53EF\u4EE5\u8FDB\u884C\u89D2\u8272\u5207\u6362\u3002",INVALID_PARAMETER_SWITCH_ROLE:"role \u53EA\u80FD\u8BBE\u7F6E\u4E3A anchor \u6216\u8005 audience\u3002",INVALID_OPERATION_SWITCH_ROLE:"\u8BF7\u5728\u4F7F\u7528 switchRole() \u65B9\u6CD5\u524D\u5148\u8FDB\u623F\u3002",SWITCH_ROLE_TIMEOUT:"\u5207\u6362\u89D2\u8272\u8D85\u65F6\u3002",SWITCH_ROLE_FAILED(i){return`\u5207\u6362\u89D2\u8272\u5931\u8D25\u3002\u9519\u8BEF\u7801: ${i.code} \u9519\u8BEF\u4FE1\u606F: ${i.message}\u3002`},CLIENT_BANNED(i){return`\u60A8\u88AB\u52A8\u9000\u623F\u4E86\uFF0C\u539F\u56E0\u4E3A\uFF1A${i.reason}\u3002`},INVALID_OPERATION_START_PUBLISH_CDN:"\u8BF7\u5728\u8FDB\u623F\u524D\u6216\u8005\u8FDB\u623F\u5E76\u6210\u529F\u53D1\u5E03\u672C\u5730\u6D41\u540E\u8C03\u7528 startPublishCDNStream() \u65B9\u6CD5\u3002",INVALID_OPERATION_STOP_PUBLISH_CDN:"\u5728\u8C03\u7528 stopPublishCDNStream() \u65B9\u6CD5\u524D\u9700\u8981\u5148 startPublishCDNStream()\u3002",INVALID_STREAM_ID(i){return`'${i}' \u53EA\u80FD\u7531\u5927\u5C0F\u5199\u5B57\u6BCD\uFF08a-zA-z\uFF09, \u6570\u5B57\uFF080-9\uFF09, \u8FDE\u5B57\u7B26\u548C\u4E0B\u5212\u7EBF\u7EC4\u6210`},START_PUBLISH_CDN_FAILED(i){return`startPublishCDNStream \u8C03\u7528\u5931\u8D25\uFF0C\u9519\u8BEF\u4FE1\u606F: ${i.message}\u3002`},STOP_PUBLISH_CDN_FAILED(i){return`stopPublishCDNStream \u8C03\u7528\u5931\u8D25\uFF0C\u9519\u8BEF\u4FE1\u606F: ${i.message}\u3002`},START_MIX_TRANSCODE:"\u8C03\u7528 startMixTranscode() \u65B9\u6CD5\u524D\u9700\u8981\u5148\u8C03\u7528 join()\u3002",STOP_MIX_TRANSCODE:"\u8C03\u7528 stopMixTranscode \u4E4B\u524D\u9700\u8981\u8C03\u7528 startMixTranscode\u3002",INVALID_AUDIO_VOLUME:"interval \u5FC5\u987B\u662F\u6570\u5B57\u3002",ENABLE_SMALL_STREAM_PUBLISHED:"\u53D1\u5E03 localStream \u4E4B\u540E\u4E0D\u5141\u8BB8\u5F00\u542F\u5C0F\u6D41\u3002",DISABLE_SMALL_STREAM_PUBLISHED:"\u53D1\u5E03 localStream \u4E4B\u540E\u4E0D\u5141\u8BB8\u5173\u95ED\u5C0F\u6D41\u3002",NOT_SUPPORTED_SMALL_STREAM:"\u60A8\u7684\u6D4F\u89C8\u5668\u4E0D\u652F\u6301\u5F00\u542F\u5C0F\u6D41\u3002",INVALID_SMALL_STREAM_PROFILE:"\u5C0F\u6D41\u53C2\u6570\u4E0D\u5408\u6CD5\u3002",INVALID_PARAMETER_REMOTE_STREAM:"remoteStream \u4E0D\u5408\u6CD5\u3002",REMOTE_NOT_PUBLISH_SMALL_STREAM:"\u8FDC\u7AEF\u7528\u6237\u6CA1\u6709\u53D1\u5E03\u5C0F\u6D41\u3002",INVALID_SWITCH_DEVICE:"\u5F53\u524D\u7684\u6D41\u4E0D\u53EF\u4EE5\u8C03\u7528 switchDevice\u3002",INVALID_SWITCH_DEVICE_PUBLISHING:"\u53D1\u5E03\u672C\u5730\u6D41\u65F6\u4E0D\u80FD\u5207\u6362\u8BBE\u5907\u3002",INVALID_REPLACE_TRACK:"client.publish \u63A5\u53E3\u5C1A\u672A\u8C03\u7528\u5B8C\u6210\uFF0C\u8BF7\u7B49\u5176\u8C03\u7528\u5B8C\u6210\u540E\u518D\u8C03\u7528 replaceTrack \u63A5\u53E3\u3002",INVALID_INITIALIZE_LOCAL_STREAM:"\u672C\u5730\u6D41\u8FD8\u6CA1\u6709\u521D\u59CB\u5316\u3002",INVALID_ADD_TRACK_REPETITIVE:"\u524D\u4E00\u4E2A addTrack \u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u907F\u514D\u91CD\u590D\u8C03\u7528\u3002",INVALID_ADD_TRACK_REMOVING:"track \u5728\u79FB\u52A8\u7684\u65F6\u5019\u4E0D\u80FD\u6DFB\u52A0\u65B0\u7684 track\u3002",INVALID_ADD_TRACK_PUBLISHING:"\u5728\u53D1\u5E03\u672C\u5730\u6D41\u7684\u65F6\u5019\u4E0D\u80FD\u6DFB\u52A0\u65B0\u7684 track\u3002",INVALID_STREAM_INITIALIZED:"\u60A8\u7684\u672C\u5730\u6D41\u8FD8\u6CA1\u6709\u521D\u59CB\u5316\u3002",INVALID_ADD_TRACK_NUMBER:"\u4E00\u6761\u6D41\u6700\u591A\u6709\u4E00\u4E2A\u97F3\u9891\u8F68\u9053\u548C\u4E00\u4E2A\u89C6\u9891\u8F68\u9053\u3002",INVALID_REMOVE_AUDIO_TRACK:"remove audio track \u662F\u4E0D\u5141\u8BB8\u7684\u3002",INVALID_REMOVE_AUDIO_ADDING:"\u5F53\u4E00\u4E2A track \u88AB addTrack \u7684\u65F6\u5019\u4E0D\u80FD\u5BF9\u6D41\u8FDB\u884C removeTrack \u64CD\u4F5C\u3002",INVALID_REMOVE_AUDIO_ON:"\u524D\u4E00\u6B21\u8C03\u7528\u7684 removeTrack \u6B63\u5728\u8FDB\u884C\u4E2D\uFF0C\u8BF7\u907F\u514D\u91CD\u590D\u64CD\u4F5C\u3002",INVALID_REMOVE_TRACK_PUBLISHING:"\u53D1\u5E03\u6D41\u7684\u8FC7\u7A0B\u4E2D\u4E0D\u80FD\u8FDB\u884C removeTrack \u64CD\u4F5C\u3002",INVALID_REMOVE_TRACK_NOT_PUBLISHING:"\u88AB remove \u7684 track \u6CA1\u6709\u88AB\u53D1\u5E03\u3002",INVALID_REMOVE_TRACK_NUMBER:"\u4E0D\u652F\u6301\u79FB\u9664\u552F\u4E00\u7684\u89C6\u9891\u8F68\u9053\uFF0C\u8BF7\u4F7F\u7528 replaceTrack \u6216\u8005 muteVideo \u65B9\u6CD5\u3002",INVALID_REPLACE_TRACK_NO_TRACK(i){return`LocalStream \u6CA1\u6709 ${i.kind} track\uFF0C\u65E0\u6CD5\u8FDB\u884C\u66FF\u6362\u3002`},START_MIX_TRANSCODE_FAILED(i){return`startMixTranscode \u8C03\u7528\u5931\u8D25\uFF0C\u9519\u8BEF\u4FE1\u606F: ${i.message}\u3002`},STOP_MIX_TRANSCODE_FAILED(i){return`stopMixTranscode \u8C03\u7528\u5931\u8D25\uFF0C\u9519\u8BEF\u4FE1\u606F: ${i.message}\u3002`},MIX_TRANSCODE_NOT_STARTED:"\u8FD8\u6CA1\u6709\u5F00\u59CB mixTranscode\u3002",CANNOT_LESS_THAN_ZERO({key:i,rule:t,fnName:e}){return`'\u5F53\u8C03\u7528 ${e}() \u51FD\u6570\u65F6\uFF0C\u8981\u6C42\u53C2\u6570 ${i||t.name}' \u5FC5\u987B\u5927\u4E8E\u7B49\u4E8E0`},MIX_PARAMS_VIDEO_FRAMERATE:"'config.videoFramerate' \u5E94\u8BE5\u662F (0, 30] \u533A\u95F4\u5185\u7684\u6574\u6570\u3002",MIX_PARAMS_VIDEO_GOP:"'config.videoGOP' \u5E94\u8BE5\u662F [1, 8] \u533A\u95F4\u5185\u7684\u6574\u6570\u3002",MIX_PARAMS_AUDIO_BITRATE:"'config.audioBitrate' \u5E94\u8BE5\u662F [32, 192] \u533A\u95F4\u5185\u7684\u6574\u6570\u3002",MIX_PARAMS_USER_Z_ORDER(i){return`'${i}' \u662F\u5FC5\u4F20\u7684\uFF0C\u4E14\u8981\u6C42\u4E3A [1 ,15] \u4E4B\u95F4\u7684\u6574\u6570\u3002`},MIX_PARAMS_NOT_SELF:"'config.mixUsers' \u5FC5\u987B\u5305\u542B\u53D1\u8D77\u6DF7\u6D41\u7684\u7528\u6237\u4FE1\u606F\u3002",MIX_PARAMS_USER_STREAM:"\u8F93\u51FA\u6D41\u7684 'config.videoWidth' \u548C 'config.videoHeight' \u5E94\u8BE5\u5BB9\u7EB3\u6240\u6709\u6DF7\u5165\u6D41\u3002",INVALID_PLAY:"play() \u88AB\u91CD\u590D\u8C03\u7528\uFF0C\u8BF7\u5148 stop()\uFF0C\u7136\u540E\u518D\u91CD\u65B0\u8C03\u7528 play\u3002",INVALID_ELEMENT_ID:({key:i,fnName:t})=>`\u5728\u8C03\u7528 ${t}() \u65F6\uFF0Cdocument \u5BF9\u8C61\u4E2D\u627E\u4E0D\u5230 ${i} \u5BF9\u5E94\u7684\u5143\u7D20\uFF0C\u8BF7\u68C0\u67E5\u3002`,INVALID_ELEMENT_ID_TYPE:({key:i,type:t,fnName:e})=>`\u5728\u8C03\u7528 ${e}() \u65B9\u6CD5\u65F6\uFF0C${i} \u53C2\u6570\u5BF9\u5E94\u7684 HTML \u6807\u7B7E\u5143\u7D20\u5FC5\u987B\u662F HTMLElement \u5B9E\u4F8B\uFF0C\u60A8\u4F20\u5165\u7684\u662F\uFF1A${t}\u3002`,PLAY_FAILED:i=>`${i.media} \u64AD\u653E\u88AB\u4E2D\u65AD\uFF0C\u6D4F\u89C8\u5668\u5F02\u5E38\u539F\u56E0\uFF1A${i.error.toString()}`,INVALID_USERID:"userId \u4E0D\u80FD\u4E3A\u7A7A\u683C\u3002",INVALID_CREATE_STREAM_SOURCE:"createStream() \u751F\u6210 LocalStream \u53EF\u4EE5\u4F7F\u7528 audio & video \u6216 audioSource & videoSource \u521B\u5EFA\uFF0C\u4F46\u4E0D\u80FD\u6DF7\u5408\u4F7F\u7528\u3002",INVALID_CREATE_STREAM_SCREEN:"screen \u548C video \u4E0D\u80FD\u540C\u65F6\u4E3A true\u3002",INVALID_CREATE_STREAM_AUDIO:"audio \u548C screenAudio \u4E0D\u80FD\u540C\u65F6\u4E3A true\u3002",INVALID_CREATE_STREAM_SCREEN_AUDIO:"screen \u4E3A true \u65F6\uFF0C\u4E0D\u80FD\u8BBE\u7F6E screenAudio\u3002",NOT_SUPPORTED_HTTP:"\u7531\u4E8E\u6D4F\u89C8\u5668\u5B89\u5168\u7B56\u7565\u9650\u5236\uFF0C\u4E0D\u652F\u6301\u5728 http \u534F\u8BAE\u4E0B\u4F7F\u7528\u91C7\u96C6\u3001\u63A8\u6D41\u7B49\u80FD\u529B\uFF0C\u8BF7\u4F7F\u7528 https \u534F\u8BAE\u3002",NOT_SUPPORTED_WEBRTC:"\u5F53\u524D\u6D4F\u89C8\u5668\u6216\u73AF\u5883\u4E0D\u5B8C\u5168\u652F\u6301 WebRTC \u80FD\u529B\uFF0C\u8BF7\u68C0\u67E5\u6D4F\u89C8\u5668\u7248\u672C\u548C\u9875\u9762\u8BBF\u95EE\u534F\u8BAE\u662F\u5426\u6EE1\u8DB3\u6761\u4EF6\u3002",NOT_SUPPORTED_PROFILE:"\u60A8\u7684\u6D4F\u89C8\u5668\u4E0D\u652F\u6301 setVideoProfile \u65B9\u6CD5\u3002\u8BF7\u68C0\u67E5\u6D4F\u89C8\u5668\u7248\u672C\u662F\u5426\u6EE1\u8DB3\u6761\u4EF6\u3002",NOT_SUPPORTED_MEDIA:"\u5F53\u524D\u6D4F\u89C8\u5668\u6216\u73AF\u5883\u4E0D\u652F\u6301 navigator.mediaDevices\uFF0C\u8BF7\u68C0\u67E5\u6D4F\u89C8\u5668\u7248\u672C\u548C\u9875\u9762\u8BBF\u95EE\u534F\u8BAE\u662F\u5426\u6EE1\u8DB3\u6761\u4EF6\u3002",NOT_SUPPORTED_H264ENCODE:"\u5F53\u524D\u7684\u8BBE\u5907\u6216\u73AF\u5883\u4E0D\u652F\u6301 H264 \u7F16\u7801\uFF0C\u4E0D\u652F\u6301 H264 \u683C\u5F0F\u8FDB\u884C\u63A8\u6D41\u3002",NOT_SUPPORTED_H264DECODE:"\u5F53\u524D\u7684\u8BBE\u5907\u6216\u73AF\u5883\u4E0D\u652F\u6301 H264 \u89E3\u7801\uFF0C\u4E0D\u652F\u6301 H264 \u683C\u5F0F\u8FDB\u884C\u62C9\u6D41\u3002",NOT_SUPPORTED_TRACK(i){return`\u60A8\u7684\u6D4F\u89C8\u5668\u4E0D\u652F\u6301 ${i}Track \u65B9\u6CD5\u3002`},NOT_SUPPORTED_REPLACE_TRACK:"\u60A8\u7684\u6D4F\u89C8\u5668\u4E0D\u652F\u6301 replaceTrack \u65B9\u6CD5\uFF0C\u8BF7\u4F7F\u7528 switchDevice \u6216\u8005 addTrack\u3002",NOT_SUPPORTED_CAPTURE:"\u60A8\u5F53\u524D\u7684\u6D4F\u89C8\u5668\u4E0D\u652F\u6301\u5C4F\u5E55\u5206\u4EAB\uFF0C\u8BF7\u68C0\u67E5\u6D4F\u89C8\u5668\u7248\u672C\u548C\u9875\u9762\u8BBF\u95EE\u534F\u8BAE\u662F\u5426\u6EE1\u8DB3\u6761\u4EF6\u3002",NOT_SUPPORTED_AUX:"\u60A8\u5F53\u524D\u7684\u6D4F\u89C8\u5668\u4E0D\u652F\u6301\u63A8\u8F85\u6D41\uFF0C\u8BF7\u68C0\u67E5\u6D4F\u89C8\u5668\u7248\u672C\u662F\u5426\u6EE1\u8DB3\u6761\u4EF6\uFF08Chrome 69+, Safari 11+, Firefox 59+\uFF09\u3002",MICROPHONE_NOT_FOUND:"\u672A\u68C0\u6D4B\u5230\u9EA6\u514B\u98CE\uFF0C\u8BF7\u68C0\u67E5\u60A8\u7684\u9EA6\u514B\u98CE\u548C TRTC.createStream \u4E0A\u7684\u914D\u7F6E\u3002",CAMERA_NOT_FOUND:"\u672A\u68C0\u6D4B\u5230\u6444\u50CF\u5934\uFF0C\u8BF7\u68C0\u67E5\u60A8\u7684\u6444\u50CF\u5934\u548C TRTC.createStream \u4E0A\u7684\u914D\u7F6E\u3002",CATCH_HANDLER_ERROR:({name:i,event:t})=>` \u5728 ${i}.on('${t}', handler) \u4E8B\u4EF6\u4E2D\u6355\u83B7\u5230\u4E1A\u52A1\u4FA7\u9519\u8BEF\uFF0C\u8BF7\u6839\u636E\u4E0B\u8FF0\u9519\u8BEF\u4FE1\u606F\uFF0C\u68C0\u67E5\u60A8\u5728 handler \u4E2D\u7684\u4E1A\u52A1\u4EE3\u7801\u3002`,REPEAT_JOIN:i=>`\u7528\u6237 [${i}] \u6B63\u5728\u8C03\u7528\u8FDB\u623F\u63A5\u53E3\u6216\u8005\u5DF2\u7ECF\u5728\u623F\u95F4\u5185\uFF0C\u8BF7\u52FF\u91CD\u590D\u521B\u5EFA\u76F8\u540C userId \u7684 client \u8FDB\u5165\u540C\u4E00\u4E2A\u623F\u95F4\u3002`,CLIENT_DESTROYED:({funName:i})=>`client \u5DF2\u7ECF\u88AB\u9500\u6BC1\uFF0C\u8C03\u7528 ${i}() \u65B9\u6CD5\u5931\u8D25\u3002`,API_CALL_ABORTED(i){let t;return i.message.includes("REMOTE_STREAM_NOT_EXIST")?t=`\u4E2D\u65AD\u8BA2\u9605\u7528\u6237 ${i.userId} \u7684 ${i.streamType} stream, \u539F\u56E0: \u5728\u60A8\u8BA2\u9605\u8FC7\u7A0B\u4E2D\uFF0C\u8FDC\u7AEF\u7528\u6237 ${i.userId} \u53D6\u6D88\u4E86\u63A8\u6D41\uFF0C\u60A8\u53EF\u4EE5\u5728\u4E0B\u6B21\u8FDC\u7AEF\u63A8\u6D41\u65F6\u518D\u8FDB\u884C\u8BA2\u9605\u3002`:t=`\u4E2D\u65AD\u63A5\u53E3\u8C03\u7528, \u539F\u56E0: ${i.message}\u3002`,t},SEI_BEFORE_PUBLISH:"\u5F53\u524D client \u6CA1\u6709\u63A8 localStream(\u4E3B\u6D41\uFF0C\u975E\u5C4F\u5E55\u5206\u4EAB\u6D41)\uFF0C\u65E0\u6CD5\u8C03\u7528 client.sendSEIMessage() \u63A5\u53E3\u3002"},h_={INVALID_USER_DEFINE_RECORDID:"TRTC.html#createClient",INVALID_PROXY:"Client.html#setProxyServer",INVALID_JOIN:"Client.html#join",INVALID_ROOMID_STRING:"Client.html#join",INVALID_ROOMID_INTEGER:"Client.html#join",INVALID_PUBLISH:"Client.html#publish",INVALID_UNPUBLISH:"Client.html#unpublish",INVALID_AUDIENCE:"Client.html#switchRole",INVALID_INITIALIZE:"Client.html#publish",INVALID_DUPLICATE_PUBLISHING:"Client.html#publish",INVALID_SUBSCRIBE_UNDEFINED:"Client.html#subscribe",INVALID_SUBSCRIBE_LOCAL:"Client.html#subscribe",INVALID_REMOTE_STREAM:"Client.html#subscribe",INVALID_ROLE:"Client.html#switchRole",INVALID_PARAMETER_SWITCH_ROLE:"Client.html#switchRole",INVALID_OPERATION_SWITCH_ROLE:"Client.html#switchRole",CLIENT_BANNED:"module-ClientEvent.html#.CLIENT_BANNED",INVALID_OPERATION_START_PUBLISH_CDN:"Client.html#startPublishCDNStream",INVALID_OPERATION_STOP_PUBLISH_CDN:"Client.html#stopPublishCDNStream",START_MIX_TRANSCODE:"Client.html#startMixTranscode",STOP_MIX_TRANSCODE:"Client.html#stopMixTranscode",INVALID_AUDIO_VOLUME:"Client.html#enableAudioVolumeEvaluation",ENABLE_SMALL_STREAM_PUBLISHED:"Client.html#enableSmallStream",DISABLE_SMALL_STREAM_PUBLISHED:"Client.html#disableSmallStream",NOT_SUPPORTED_SMALL_STREAM:"tutorial-27-advanced-small-stream.html#h2-4",INVALID_SMALL_STREAM_PROFILE:"Client.html#setSmallStreamProfile",REMOTE_NOT_PUBLISH_SMALL_STREAM:"Client.html#setRemoteVideoStreamType",INVALID_SWITCH_DEVICE:"LocalStream.html#switchDevice",INVALID_SWITCH_DEVICE_PUBLISHING:"LocalStream.html#switchDevice",INVALID_REPLACE_TRACK:"LocalStream.html#replaceTrack",INVALID_INITIALIZE_LOCAL_STREAM:"LocalStream.html#replaceTrack",INVALID_ADD_TRACK_REPETITIVE:"LocalStream.html#addTrack",INVALID_ADD_TRACK_REMOVING:"LocalStream.html#addTrack",INVALID_ADD_TRACK_PUBLISHING:"LocalStream.html#addTrack",INVALID_STREAM_INITIALIZED:"LocalStream.html#addTrack",INVALID_ADD_TRACK_NUMBER:"LocalStream.html#addTrack",INVALID_REMOVE_AUDIO_TRACK:"LocalStream.html#removeTrack",INVALID_REMOVE_AUDIO_ADDING:"LocalStream.html#removeTrack",INVALID_REMOVE_AUDIO_ON:"LocalStream.html#removeTrack",INVALID_REMOVE_TRACK_PUBLISHING:"LocalStream.html#removeTrack",INVALID_REMOVE_TRACK_NOT_PUBLISHING:"LocalStream.html#removeTrack",INVALID_REMOVE_TRACK_NUMBER:"LocalStream.html#removeTrack",INVALID_REMOVE_TRACK_NOT_PUBLISHED:"LocalStream.html#removeTrack",START_MIX_TRANSCODE_TIMEOUT:"Client.html#startMixTranscode",START_MIX_TRANSCODE_FAILED:"Client.html#startMixTranscode",STOP_MIX_TRANSCODE_FAILED:"Client.html#stopMixTranscode",MIX_TRANSCODE_NOT_STARTED:"Client.html#startMixTranscode",MIX_PARAMS_VIDEO_FRAMERATE:"Client.html#startMixTranscode",MIX_PARAMS_VIDEO_GOP:"Client.html#startMixTranscode",MIX_PARAMS_AUDIO_BITRATE:"Client.html#startMixTranscode",MIX_PARAMS_USER_Z_ORDER:"Client.html#startMixTranscode",MIX_PARAMS_NOT_SELF:"Client.html#startMixTranscode",MIX_PARAMS_USER_STREAM:"Client.html#startMixTranscode",INVALID_PLAY:"Stream.html#play",PLAY_FAILED:"Stream.html#play",INVALID_USERID:"TRTC.html#createClient",INVALID_CREATE_STREAM_SOURCE:"TRTC.html#createStream",INVALID_CREATE_STREAM_SCREEN:"TRTC.html#createStream",INVALID_CREATE_STREAM_AUDIO:"TRTC.html#createStream",INVALID_CREATE_STREAM_SCREEN_AUDIO:"TRTC.html#createStream",NOT_SUPPORTED_HTTP:"tutorial-05-info-browser.html#h2-2",NOT_SUPPORTED_WEBRTC:"tutorial-05-info-browser.html",NOT_SUPPORTED_TRTC:"tutorial-05-info-browser.html",NOT_SUPPORTED_PROFILE:"tutorial-23-advanced-support-detection.html",NOT_SUPPORTED_MEDIA:"tutorial-05-info-browser.html",NOT_SUPPORTED_H264ENCODE:"tutorial-23-advanced-support-detection.html",NOT_SUPPORTED_H264DECODE:"tutorial-23-advanced-support-detection.html",NOT_SUPPORTED_TRACK:"LocalStream.html#addTrack",NOT_SUPPORTED_REPLACE_TRACK:"LocalStream.html#replaceTrack",NOT_SUPPORTED_CAPTURE:"tutorial-05-info-browser.html",MICROPHONE_NOT_FOUND:"TRTC.html#createStream",CAMERA_NOT_FOUND:"TRTC.html#createStream",SUBSCRIBE_FAILED:"Client.html#subscribe",API_CALL_ABORTED(i){let t;return i.message.includes("REMOTE_STREAM_NOT_EXIST")?t="Client.html#subscribe":t="module-ErrorCode.html#.API_CALL_ABORTED",t}};typeof window!="undefined"&&(window.TRTC_ERROR_INFO=p_,window.TRTC_ERROR_LINK=h_);var Su=(i,t)=>t?`${Pi}/${i}/${t}`:`${Pi}/${i}/index.html`;var m_=()=>{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 i=localStorage.getItem(pa);if(i){i=JSON.parse(i);let t=document.createElement("script");t.type="text/javascript",t.text=i.message,document.body.appendChild(t);let e=window.TRTC_ERROR_INFO,r=window.TRTC_ERROR_LINK;return document.body.removeChild(t),{TRTC_ERROR_INFO:e,TRTC_ERROR_LINK:r}}return{}};function B(i){let{key:t,data:e,link:r,addDocLink:n=!0}=i,s="",o="",a="";ce(xe[t])?s=xe[t](e):oe(xe[t])&&(s=xe[t]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:d}=m_();r?a=`${r.className}.html#${r.fnName}`:d&&d[t]&&(ce(d[t])?a=d[t](e):oe(d[t])&&(a=d[t]));let u=s;return Nt()&&(c&&c[t]&&(ce(c[t])?o=c[t](e):oe(c[t])&&(o=c[t])),o&&(n?u=`${o}
76
+ \u8BF7\u67E5\u770B\u6587\u6863: ${Su("zh-cn",a)}
76
77
 
77
78
  `:u=`${o}
78
79
 
79
80
  `,u+=s)),n&&(u+=`
80
- Refer to: ${tu("en",a)}
81
- `),u}var cm="trtc_env",dm=function(){return new URLSearchParams(location.search).get(cm)||""},ds=i=>Number(i)<14e8,Ci=function(i,t){let e;$n?e=$n:e=ds(i)?Md:Pd;let r=Math.floor(Math.random()*Ln(2,31));return`${e}/v5/AVQualityReportSvc/C2S?random=${r}&sdkappid=${i}&cmdtype=${t}`};function ru(){return ut?4:Ri?2:wr?3:Ut?12:Wr?5:Kr?13:1}function nu(){return ut?"Android":Ri?"iPhone":wr?"iPad":Ut?"Mac":Wr?"Windows":Kr?"Linux":"unknown"}function us(){let{userAgent:i,connection:t}=navigator,e=(i.match(/NetType\/\S+/)||[])[0]||"";e=e.toLowerCase().replace("nettype/",""),e==="3gnet"&&(e="3g");let r=t&&t.type&&t.type.toLowerCase(),n=t&&t.effectiveType&&t.effectiveType.toLowerCase();n==="slow-2"&&(n="2g");let s=e||"unknown";if(r)switch(r){case"cellular":case"wimax":s=n||"unknown";break;case"wifi":s="wifi";break;case"ethernet":s="wired";break;case"none":case"other":case"unknown":default:s="unknown";break}return s}var um=function(i){return{AbilityOption:{AVLimit:i,GeneralLimit:{CPULimit:{uint32_CPU_num:navigator.hardwareConcurrency||0,str_CPU_name:String(navigator.platform),uint32_CPU_maxfreq:0,model:"",uint32_total_memory:0},uint32_terminal_type:ru(),uint32_device_type:0,str_os_verion:nu(),uint32_link_type:1,str_client_version:ji,uint32_net_type:Si[us()],ua:navigator.userAgent,version:""}}}};function Xo({fn:i,context:t}){return function(...e){try{let r=i.apply(t||this,e);return ls(r)?r.catch(n=>M.error(`${i.name}() error observed ${n}`)):r}catch(r){M.error(`${i.name}() error observed ${r}`)}}}function lm(i,t){for(let e of Reflect.ownKeys(t))if(e!=="constructor"&&e!=="prototype"&&e!=="name"){let r=Object.getOwnPropertyDescriptor(t,e)||"";Object.defineProperty(i,e,r)}return i}function pm(i,t=48e3){return su(i/4,t)}function su(i,t=48e3){return i*1e3/t}function hm(i,t=48e3){return ou(i,t)*4}function ou(i,t=48e3){return i*t/1e3}var au=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},Ct=()=>{let i=navigator.language;return i=i.substring(0,2),i==="zh"},ni=function(i){if(!i||typeof i!="object"||Object.prototype.toString.call(i)!="[object Object]")return!1;let t=Object.getPrototypeOf(i);if(t===null)return!0;let e=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return typeof e=="function"&&e instanceof e&&Function.prototype.toString.call(e)===Function.prototype.toString.call(Object)};function ir(i,t=1,e=1){return i<=1?e:ir(i-1,e,t+e)}function rt(i){return i>8?30*1e3:ir(i)*1e3}function Te(i){return Reflect.apply(Object.prototype.toString,i,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var ue=i=>typeof i=="function",b=i=>typeof i=="undefined",oe=i=>typeof i=="string",de=i=>typeof i=="number",be=i=>typeof i=="boolean",yi=i=>Te(i)==="object",Ve=i=>Te(i)==="array",mm=i=>Te(i)==="MediaStreamTrack".toLowerCase(),si=i=>i.isRemote,ls=i=>Te(i)==="promise",qr=i=>ue(i)&&i.prototype.constructor===i,ps=i=>qr(i)?i.prototype.constructor.name:"",zo=typeof AudioWorkletNode!="undefined";function qo(i){return new Promise((t,e)=>{let r=[];i.forEach(n=>{n.then(t).catch(s=>{r.push(s),r.length===i.length&&e(r)})})})}function q(){return!performance||!performance.now?Date.now():Math.floor(performance.now())}var Qo=(i,t)=>{let{emit:e}=i;return i.emit=(...r)=>{try{return e.apply(i,r)}catch(n){let s=$({key:w.CATCH_HANDLER_ERROR,data:{name:t,event:r[0]},addDocLink:!1});return M.warn(`${s}
82
-
83
- ${n.stack}`),!1}},i},iu=i=>+i<10?`0${i}`:i,_m=i=>{let t=i.match(/^\d+\.\d+\.\d+/)[0];if(!t)return i;let e=t.split("."),r=iu(e[1])+iu(e[2]);return e[1]-15>0&&(e[1]="15"),e[2]-15>0&&(e[2]="15"),`${e.join(".")}.${r}`},fm=Object.prototype.hasOwnProperty,{toString:NE}=Object.prototype;function Qr(i){if(i==null)return!0;if(typeof i=="boolean")return!1;if(typeof i=="number")return i===0;if(typeof i=="string"||typeof i=="function"||Array.isArray(i))return i.length===0;if(i instanceof Error)return i.message==="";if(ni(i))switch(Object.prototype.toString.call(i)){case"[object File]":case"[object Map]":case"[object Set]":return i.size===0;case"[object Object]":{for(let t in i)if(fm.call(i,t))return!1;return!0}}return!1}function oi(i,t){return{userId:t,hasAudio:!!(i&Or),hasVideo:!!(i&Dr),hasAuxiliary:!!(i&Gn),hasSmall:!!(i&kd),audioMuted:!!(i&No),videoMuted:!!(i&bo),audioAvailable:!!(i&Or)&&!(i&No),videoAvailable:!!(i&Dr)&&!(i&bo)}}function Em(i,t){return i>50||t>500?5:i>30||t>350?4:i>20||t>200?3:i>10||t>100?2:i>=0||t>=0?1:0}function Tm(i){let t={urls:`turn:${i.url}`};return!b(i.username)&&!b(i.credential)&&(t.username=i.username,t.credential=i.credential,t.credentialType="password",b(i.credentialType)||(t.credentialType=i.credentialType)),t}function Zr(i,t=!0){if(!oe(i))return 0;let e=i.split(".");return t?(Number(e[0])<<24|Number(e[1])<<16|Number(e[2])<<8|Number(e[3]))>>>0:(Number(e[3])<<24|Number(e[2])<<16|Number(e[1])<<8|Number(e[0]))>>>0}var zr=function(i){return Ve(i)||yi(i)},yt=function(i,t,e,r){if(!(zr(i)&&zr(t)))return 0;let n=0,s=Object.keys(t),o;for(let a=0,c=s.length;a<c;a++)if(o=s[a],!(b(t[o])||e&&e.includes(o)))if(zr(i[o])&&zr(t[o]))n+=yt(i[o],t[o],e,r);else{if(r&&r.includes(t[o]))continue;i[o]!==t[o]&&(i[o]=t[o],n+=1)}return n},hs=i=>oe(i)?document.getElementById(i):i,Sm=new Intl.DateTimeFormat("zh-CN",{dateStyle:"short",timeStyle:"medium"}),gm=()=>Sm.format(new Date);var PE=_(f(),1);function ai({url:i,body:t,method:e,timeout:r}){let n=new XMLHttpRequest;return new Promise((s,o)=>{n.onreadystatechange=()=>{if(n.readyState===4)if(n.status>=200&&n.status<300)try{let a=JSON.parse(n.response);s({data:a})}catch(a){s({data:n.response})}else o({status:n.status,statusText:n.statusText||"request failed!"})},n.timeout=r||5e3,n.open(e||"POST",i,!0),n.send(t)})}var xE=_(f(),1);var Im=0,Rm=1,cu=2;function Am({retryFunction:i,settings:t,onError:e,onRetrying:r,onRetryFailed:n,context:s}){return function(...o){let{retries:a=5,timeout:c=1e3}=t,d=0,u=-1,l=Im,h=(I,T)=>E(this,null,function*(){let N=s||this;try{let H=yield i.apply(N,o);d=0,I(H)}catch(H){let U=()=>{clearTimeout(u),d=0,l=cu,T(H)},G=()=>{l!==cu&&d<(ue(a)?a():a)?(d++,l=Rm,ue(r)&&r.call(this,d,U),u=window.setTimeout(()=>{u=-1,h(I,T)},ue(c)?c(d):c)):(U(),ue(n)&&n.call(this,H))};ue(e)?e.call(N,H,G,T,o):G()}});return new Promise(h)}}var vt=Am;var HE=_(f(),1);var rr=class{constructor(t){p(this,"userId");p(this,"remoteUserId");p(this,"id");p(this,"sdkAppId");p(this,"type");p(this,"isLocal");this.id=t.id,this.userId=t.userId,this.sdkAppId=t.sdkAppId,this.remoteUserId=t.remoteUserId,this.isLocal=be(t.isLocal)?t.isLocal:!0,this.type=this.isLocal?"":t.type}createChild(t){return Object.setPrototypeOf(t,this)}setUserId(t){this.userId=t}setSdkAppId(t){this.sdkAppId=t}log(t,e){let r=this.isLocal?this.userId:this.remoteUserId;e.unshift(`[${this.isLocal?"\u2191":"\u2193"}${this.type&&this.type!=="main"?"*":""}${this.id}${r?`|${r}`:""}]`),M.log(t,e,b(this.userId)||Qr(this.userId),this.userId,this.sdkAppId)}info(...t){this.log(2,t)}debug(...t){this.log(1,t)}warn(...t){this.log(3,t)}error(...t){this.log(4,t)}};var jE=_(f(),1),uu=_(nt(),1),vm=new uu.default,C=vm;var YE=_(f(),1),lu=(K=>(K.ROOM_DESTROY="1",K.JOIN_START="21",K.JOIN_SCHEDULE_SUCCESS="22",K.JOIN_SIGNAL_CONNECTION_START="23",K.JOIN_SIGNAL_CONNECTION_END="24",K.JOIN_SEND_CMD="25",K.JOIN_RECEIVED_CMD_RES="26",K.JOIN_SUCCESS="27",K.JOIN_FAILED="28",K.LEAVE_START="51",K.LEAVE_SEND_CMD="52",K.LEAVE_SUCCESS="53",K.PUBLISH_START="61",K.SEND_FIRST_VIDEO_FRAME="62",K.SUBSCRIBE_START="81",K.SUBSCRIBE_SUCCESS="82",K.UNSUBSCRIBE_SUCCESS="83",K.LOCAL_TRACK_CAPTURE_START="101",K.LOCAL_TRACK_CAPTURE_SUCCESS="102",K.LOCAL_TRACK_CAPTURE_FAILED="103",K.LOCAL_TRACK_PUBLISHED="104",K.LOCAL_TRACK_UNPUBLISHED="105",K.LOCAL_TRACK_REPLACED="106",K.SWITCH_DEVICE_SUCCESS="107",K.TRACK_MUTED="108",K.TRACK_UNMUTED="109",K.REMOTE_TRACK_SUBSCRIBED="110",K.REMOTE_TRACK_UNSUBSCRIBED="111",K.PLAY_TRACK_START="151",K.PLAYER_STATE_CHANGED="152",K.VIDEO_LOADED_DATA="153",K.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",K.WORKLET_LOADED_SUCCESS="155",K.WORKLET_LOADED_FAILED="156",K.SIGNAL_CONNECTION_STATE_CHANGED="201",K.PEER_CONNECTION_STATE_CHANGED="202",K.HEARTBEAT_REPORT="251",K.RECEIVED_PUBLISHED_USER_LIST="252",K.REMOTE_PUBLISH_STATE_CHANGED="253",K.AUDIO_LEVEL_INTERVAL="260",K.NETWORK_QUALITY="261",K.API_SUCCESS_RATE="262",K))(lu||{}),S=lu;var Nm="%cTRTC%c%s",bm="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",Dm="display: inline",Om=!(It||ut||Zd),ea=class{constructor(){p(this,"_isEnableUploadLog",!0);p(this,"_localJoinedUser",new Map);p(this,"_queue",[]);p(this,"_timeoutId",-1);p(this,"_logLevel",1);p(this,"_logLevelToUpload",2);!wn&&!Bn&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){C.on(S.JOIN_SCHEDULE_SUCCESS,({schedule:t})=>{var e;((e=t==null?void 0:t.config)==null?void 0:e.logLevelToUpload)&&Tt[t.config.logLevelToUpload]&&(this._logLevelToUpload=t.config.logLevelToUpload)}),C.on(S.JOIN_SUCCESS,({room:t})=>{this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload()}),C.once(S.JOIN_FAILED,()=>{this.startUpload()}),C.on(S.LEAVE_SUCCESS,({room:t})=>{this.deleteJoinedUser(t.userId)})}startUpload(){this._timeoutId===-1&&this.uploadInterval()}addJoinedUser(t){this._localJoinedUser.set(t.userId,t),this.startUpload()}deleteJoinedUser(t){this._localJoinedUser.delete(t)}uploadInterval(){this.upload().catch(()=>{}),this._timeoutId=window.setTimeout(()=>this.uploadInterval(),2e3)}getLogsToUpload(){let t={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&this._localJoinedUser.size===0)return t;let e=0;for(;e<this._queue.length&&e!==50;e++){let r=this._queue[e];if(r.forAllJoinedClients)this._localJoinedUser.forEach(({userId:n,sdkAppId:s})=>{t.map.has(n)?t.map.get(n).logs.push(r):t.map.set(n,{userId:n,sdkAppId:s,logs:[r]})});else if(oe(r.userId)&&de(r.sdkAppId)){let{userId:n,sdkAppId:s}=r;t.map.has(n)?t.map.get(n).logs.push(r):t.map.set(n,{userId:n,sdkAppId:s,logs:[r]})}}return t.map.size>0&&(t.splicedQueue=this._queue.splice(0,e)),t}upload(){return E(this,null,function*(){if(this._queue.length===0||!this._isEnableUploadLog)return;let{map:t,splicedQueue:e}=this.getLogsToUpload();if(t.size===0)return;try{let n=[...t.values()];for(let s=0;s<n.length;s++){let{userId:o,sdkAppId:a,logs:c}=n[s];yield this.uploadLogWithRetry(JSON.stringify({timestamp:Xn(),sdkAppId:String(a),userId:o,version:We,log:c.map(d=>d.log).join(`
84
- `)}),a),c.forEach(d=>d.uploaded=!0)}}catch(n){}let r=e.filter(n=>!n.uploaded);r.length>0&&(this._queue=r.concat(this._queue))})}uploadLogWithRetry(t,e){return vt({retryFunction:()=>ai({url:Ci(e,Xi.LOG),body:t,timeout:5e3}),settings:{retries:3,timeout:1e3},onError:(r,n)=>{n()}})()}getPrefix(t){let e=new Date;e.setTime(Ur());let r=String(e.getMilliseconds());return"padStart"in String.prototype&&(r=r.toString().padStart(3,"0")),`[${e.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")}:${r}] <${Tt[t]}>`}getLogLevel(){return this._logLevel}setLogLevel(t){b(Tt[t])||(this._logLevel!==t&&this.info("setLogLevel",t),this._logLevel=t)}enableUploadLog(){this._isEnableUploadLog=!0}disableUploadLog(){this.warn("disableUploadLog"),this._isEnableUploadLog=!1}logChunkToString(t){if(oe(t))return t;try{return JSON.stringify(t)}catch(e){return""}}log(t,e,r=!0,n,s){var a;if(e.unshift(this.getPrefix(t)),this._isEnableUploadLog&&t>=this._logLevelToUpload&&this._queue.push({log:e.reduce((c,d)=>`${c} ${this.logChunkToString(d)}`.trim(),""),level:t,userId:n,sdkAppId:s,forAllJoinedClients:r}),t<this._logLevel)return;let o=((a=Tt[t])==null?void 0:a.toLowerCase())||"info";Om?console[o](Nm,bm,Dm,...e):console[o](...e)}debug(...t){this.log(1,t)}info(...t){this.log(2,t)}warn(...t){this.log(3,t)}error(...t){this.log(4,t)}createLogger(t){return new rr(t)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),r=e?Number(e):-1;Tt[r]&&(this._logLevelToUpload=r)}},M=new ea;var pu=!0,hu=function(){var i;pu&&(pu=!1,M.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${Yi}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("******************************************************************************")),M.info("TRTC Web SDK Version:",We),M.info("UA:",navigator.userAgent),M.info(`URL: ${location.href}${((i=self.frameElement)==null?void 0:i.tagName)==="IFRAME"?" in iframe":""}`))};var fl=_(nt());var pT=_(f()),X={ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",KICKED_OUT:"kicked-out",REMOTE_USER_ENTER:"remote-user-enter",REMOTE_USER_EXIT:"remote-user-exit",REMOTE_AUDIO_AVAILABLE:"remote-audio-available",REMOTE_AUDIO_UNAVAILABLE:"remote-audio-unavailable",REMOTE_VIDEO_AVAILABLE:"remote-video-available",REMOTE_VIDEO_UNAVAILABLE:"remote-video-unavailable",AUDIO_VOLUME:"audio-volume",NETWORK_QUALITY:"network-quality",CONNECTION_STATE_CHANGED:"connection-state-changed",AUDIO_PLAY_STATE_CHANGED:"audio-play-state-changed",VIDEO_PLAY_STATE_CHANGED:"video-play-state-changed",SCREEN_SHARE_STOPPED:"screen-share-stopped",DEVICE_CHANGED:"device-changed",PUBLISH_STATE_CHANGED:"publish-state-changed",SEI_MESSAGE:"sei-message"};var Bt={};oo(Bt,{HTTPS_API:()=>xm,IS_GET_CAPABILITIES_SUPPORTED:()=>aa,IS_GET_SETTINGS_SUPPORTED:()=>wt,IS_SEI_SUPPORTED:()=>ui,IS_SPC_SUPPORTED:()=>Ts,basis:()=>Bm,checkSystemRequirementsInternal:()=>sa,decodeSupportStatus:()=>fs,encodeSupportStatus:()=>Tu,getBrowserInfo:()=>Lm,getDisplayResolution:()=>gu,getOSName:()=>Su,isAddTransceiverSupported:()=>di,isBrowserSupported:()=>ia,isGetReceiversSupported:()=>vi,isGetSendersSupported:()=>nr,isGetTransceiversSupported:()=>st,isGetUserMediaSupported:()=>Iu,isMediaDevicesSupported:()=>_s,isMediaSessionSupported:()=>yu,isMediaStreamTrackProcessorSupported:()=>na,isReplaceTrackSupported:()=>wm,isScreenCaptureApiAvailable:()=>oa,isSelectedCandidatePair:()=>ci,isSetParametersSupported:()=>tn,isSmallStreamAPISupported:()=>Au,isSmallStreamSupported:()=>Es,isStopTransceiverSupported:()=>Vm,isTRTCSupported:()=>km,isUnifiedPlanDefault:()=>Um,isUsedInHttpProtocol:()=>ra,isWebAudioSupported:()=>Ru,isWebCodecSupported:()=>Cu,isWebCodecsSupported:()=>Eu,isWebRTCSupported:()=>ca,isWebTransportSupported:()=>vu});var NT=_(f(),1);var ET=_(f(),1);var mT=_(f(),1),mu=(R=>(R[R.INVALID_PARAMETER=4096]="INVALID_PARAMETER",R[R.INVALID_OPERATION=4097]="INVALID_OPERATION",R[R.NOT_SUPPORTED=4098]="NOT_SUPPORTED",R[R.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",R[R.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",R[R.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",R[R.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",R[R.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",R[R.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",R[R.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",R[R.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",R[R.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",R[R.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",R[R.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",R[R.CLIENT_BANNED=16448]="CLIENT_BANNED",R[R.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",R[R.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",R[R.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",R[R.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",R[R.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",R[R.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",R[R.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",R[R.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",R[R.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",R[R.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",R[R.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",R[R.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",R[R.API_CALL_ABORTED=16461]="API_CALL_ABORTED",R[R.UNKNOWN=65535]="UNKNOWN",R))(mu||{}),v=mu;var Pm=function(i){for(let t in v)if(v[t]===i)return t;return"UNKNOWN"},ta=class extends Error{constructor({name:e="RtcError",message:r,code:n=v.UNKNOWN,extraCode:s=0,constraint:o}){let a=`<${Pm(n)} 0x${n.toString(16)}>`,c=`${r}${o?` constraint: ${o}`:""}${r!=null&&r.includes(a)?"":` ${a}`}`;super(c);p(this,"code");p(this,"extraCode");p(this,"message");p(this,"originMessage");p(this,"name");p(this,"constraint");this.code=n,this.extraCode=s,this.name=e,this.message=c,this.constraint=o,this.originMessage=r}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},L=ta;var le={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},Mm=new Map([[pe,["Firefox",Mo]],[$r,["Edg",ko]],[Jr,["Chrome",Yo]],[Vt,["Safari",Xr]],[xt,["TBS",Vo]],[Qn,["XWEB",wo]],[Hr&&Ri,["WeChat",Bo]],[Zn,["QQ(Win)",$o]],[Gr,["QQ(Mobile)",Vr]],[Fr,["QQ(Mobile X5)",Vr]],[es,["QQ(Mac)",Ho]],[ts,["QQ(iPad)",Fo]],[is,["MI",Go]],[rs,["HW",Wo]],[ns,["Samsung",Ko]],[ss,["OPPO",jo]],[os,["VIVO",Jo]],[Br,["EDGE",Lo]],[zn,["SogouMobile",xo]],[qn,["Sogou",Uo]]]);function Lm(){let i=Mm.get(!0),t=i?i[0]:"unknown",e=i?i[1]:"unknown";return{browserName:t,browserVersion:e}}var ia=function(){return!(qd||Br||$r&&zd<80||pe&&Xd<56)},Eu=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder","MediaStreamTrackGenerator"].every(t=>t in window)},_s=function(){if(!navigator.mediaDevices)return M.error(Le.NOT_SUPPORTED_MEDIA),!1;let i=["getUserMedia","enumerateDevices"];return i.filter(t=>t in navigator.mediaDevices).length===i.length},_u=!1;function ra(){return location.protocol==="http:"&&!Rt&&!_u?(_u=!0,M.warn($({key:w.NOT_SUPPORTED_HTTP})),!0):!1}var na=function(){return(window==null?void 0:window.OffscreenCanvas)&&(window==null?void 0:window.MediaStreamTrackProcessor)&&(window==null?void 0:window.MediaStreamTrackGenerator)},Tu=function(){return E(this,null,function*(){if(le.detail.isH264EncodeSupported||le.detail.isVp8EncodeSupported)return{isH264EncodeSupported:le.detail.isH264EncodeSupported,isVp8EncodeSupported:le.detail.isVp8EncodeSupported};let i,t=!1,e=!1;try{let r=new RTCPeerConnection,n=document.createElement(m.CANVAS);n.getContext("2d");let s=n.captureStream(0);return r.addTrack(s.getVideoTracks()[0],s),i=yield r.createOffer(),i.sdp.toLowerCase().indexOf("h264")!==-1&&(t=!0),i.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0),r.close(),le.detail.isH264EncodeSupported=t,le.detail.isVp8EncodeSupported=e,{isH264EncodeSupported:le.detail.isH264EncodeSupported,isVp8EncodeSupported:le.detail.isVp8EncodeSupported}}catch(r){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1}}})},fs=function(){return E(this,null,function*(){if(le.detail.isH264DecodeSupported&&le.detail.isVp8DecodeSupported)return{isH264DecodeSupported:le.detail.isH264DecodeSupported,isVp8DecodeSupported:le.detail.isVp8DecodeSupported};let i,t=!1,e=!1;try{let r=new RTCPeerConnection;return i=yield r.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0}),i.sdp.toLowerCase().indexOf("h264")!==-1&&(t=!0),i.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0),r.close(),{isH264DecodeSupported:t,isVp8DecodeSupported:e}}catch(r){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1}}})},sa=function(){return E(this,null,function*(){if(le.result)return le;let i=ia(),t=ca(),e=Eu(),r=_s(),{isH264EncodeSupported:n,isVp8EncodeSupported:s}=yield Tu(),{isH264DecodeSupported:o,isVp8DecodeSupported:a}=yield fs();return le.result=i&&t&&r&&(n||s)&&(o||a),le.detail.isBrowserSupported=i,le.detail.isWebRTCSupported=t,le.detail.isWebCodecsSupported=e,le.detail.isMediaDevicesSupported=r,le.detail.isScreenShareSupported=oa(),le.detail.isSmallStreamSupported=Es(),le.detail.isH264EncodeSupported=n,le.detail.isVp8EncodeSupported=s,le.detail.isH264DecodeSupported=o,le.detail.isVp8DecodeSupported=a,le.result||M.error(`${navigator.userAgent} isBrowserSupported: ${i}isWebCodecsSupported: ${e} isMediaSupported: ${r} isH264EncodeSupported: ${n} isVp8EncodeSupported: ${s} isH264DecodeSupported: ${o} isVp8DecodeSupported: ${a} `),le})},km=function(){return le.result},oa=function(){return!!(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)},xm=(i,t,e)=>{location.protocol==="http:"&&!Rt&&(i[t]=()=>{throw new L({code:v.INVALID_OPERATION,message:Le.NOT_SUPPORTED_HTTP})})},ci=function(i){return i.type==="candidate-pair"&&i.nominated&&(i.state==="in-progress"||i.state==="succeeded")?!(be(i.selected)&&!i.selected):!1},fu=new Map([[ut,"Android"],[It,"iOS"],[Wr,"Windows"],[Ut,"MacOS"],[Kr,"Linux"]]),Su=function(){return fu.get(!0)?fu.get(!0):"unknown"};function gu(){let i="";if(screen.width){let t=screen.width?screen.width*window.devicePixelRatio:"",e=screen.height?screen.height*window.devicePixelRatio:"";i+=`${t} * ${e}`}return i}function Iu(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function Ru(){let i={isSupported:!1},t=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"];for(let e=0;e<t.length;e++)if(t[e]in window){i.isSupported=!0;break}return i.isSupported}function Au(){return"captureStream"in HTMLCanvasElement.prototype}function Es(){return Hr||It||Yr&&Yr<63?!1:!!(ia()&&Au())}var Um=function(){if(b(window.RTCRtpTransceiver)||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let i=null,t=!1;try{i=new RTCPeerConnection({sdpSemantics:gi}),i.addTransceiver(m.AUDIO),t=!0}catch(e){}return i==null||i.close(),t};function vi(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function nr(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function st(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function di(){return"RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype}var Ts=di();function Vm(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}function wm(){return"RTCRtpSender"in window&&"replaceTrack"in window.RTCRtpSender.prototype}function tn(){return"RTCRtpSender"in window&&"setParameters"in window.RTCRtpSender.prototype&&nr()}var wt=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,aa=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,ui="RTCRtpSender"in window&&"createEncodedStreams"in window.RTCRtpSender.prototype&&jr()>=86,ca=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(t=>t in window).length>0};function Cu(){let i={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return b(window.AudioDecoder)||(i.AudioDecoder=!0),b(window.AudioEncoder)||(i.AudioEncoder=!0),b(window.VideoDecoder)||(i.VideoDecoder=!0),b(window.VideoEncoder)||(i.VideoEncoder=!0),b(window.ImageDecoder)||(i.ImageDecoder=!0),i}function yu(){return"mediaSession"in navigator&&!b(navigator.mediaSession.setActionHandler)}function vu(){return!b(window.WebTransport)}function Bm(){let i={browser:`${tr.name}/${tr.version}`,os:Su(),displayResolution:gu(),isScreenShareSupported:oa(),isWebRTCSupported:ca(),isGetUserMediaSupported:Iu(),isWebAudioSupported:Ru(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:Cu(),isMediaSessionSupported:yu(),isWebTransportSupported:vu()};return navigator.userAgent.includes("miniProgram")&&(i.browser=`mini/${i.browser}`),i}var fy=_(f(),1);var OT=_(f(),1),$m=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{let t=Math.random()*16|0;return(i=="x"?t:t&3|8).toString(16)})},da=$m;var xT=_(f(),1);var ua=class{constructor(){p(this,"_prefix","TRTC");p(this,"_queue",new Map);this.checkStorage()}getRealKey(t){return`${this._prefix}_${t}`}checkStorage(){if(!ri())return;setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter(r=>{if(r.startsWith(this._prefix)){let n=JSON.parse(localStorage.getItem(r));if(n&&n.expiresIn<Date.now())return!0}return!1}).forEach(r=>localStorage.removeItem(r))}doFlush(){if(!!ri())try{for(let[t,e]of this._queue)localStorage.setItem(t,JSON.stringify(e))}catch(t){M.warn(t)}}getItem(t){if(!ri())return null;try{let e=JSON.parse(localStorage.getItem(this.getRealKey(t)));return e&&e.expiresIn>=Date.now()?e.value:null}catch(e){M.warn(e)}}setItem(t,e){if(!!ri())try{let r={expiresIn:Date.now()+Ao,value:e};this._queue.set(this.getRealKey(t),r)}catch(r){M.warn(r)}}deleteItem(t){if(!ri())return!1;try{return t=this.getRealKey(t),this._queue.delete(t),localStorage.removeItem(t),!0}catch(e){return M.warn(e),!1}}clear(){if(!!ri())try{localStorage.clear()}catch(t){M.warn(t)}}},sr=new ua;var UI=_(f(),1);var wT=_(f(),1),bu=_(nt(),1);var Nu=Symbol("instance"),rn=Symbol("abortCtrl"),Ni=Symbol("cacheResult"),la=class{constructor(t,e,r){p(this,"oldState");p(this,"newState");p(this,"action");p(this,"error");this.oldState=t,this.newState=e,this.action=r}toString(){return`${this.action}ing`}},nn=class extends Error{constructor(e,r,n){super(r);p(this,"state");p(this,"message");p(this,"cause");this.state=e,this.message=r,this.cause=n}},sn=new Map,Hm=Object.getPrototypeOf((()=>E(void 0,null,function*(){}))()).constructor;function je(i,t,e={}){return(r,n,s)=>{let o=e.action||n;if(!e.context){let c=sn.get(r)||[];sn.has(r)||sn.set(r,c),c.push({from:i,to:t,action:o})}let a=s.value;s.value=function(...c){return E(this,null,function*(){var I;let d=this;if(e.context&&(d=he.get(typeof e.context=="function"?e.context.call(this,...c):e.context)),d.state===t)return d[Ni];let u=null;if(Array.isArray(i)?i.length==0?d[rn]&&(d[rn].aborted=!0):(typeof d.state!="string"||!i.includes(d.state))&&(u=new nn(d._state,`${d.name} ${o} to ${t} failed: current state ${d._state} not in from config`)):i!==d.state&&(u=new nn(d._state,`${d.name} ${o} to ${t} failed: current state ${d._state} not from ${i}`)),u)if(e.fail)e.fail.call(this,u);else{if(e.ignoreError)return u;throw u}let l=d.state;Ss.call(d,new la(l,t,o));let h={aborted:!1};d[rn]=h;try{let T=a.apply(this,c);return T instanceof Hm?d[Ni]=yield T:d[Ni]=T,h.aborted||(d[rn]=void 0,Ss.call(d,t),(I=e.success)==null||I.call(this,d[Ni])),d[Ni]}catch(T){let N=T instanceof Error?T.message:String(T);if(Ss.call(d,l,N),e.fail)e.fail.call(this,new nn(d._state,`action '${o}' failed :${N}`,T instanceof Error?T:new Error(N)));else{if(e.ignoreError)return T;throw T}}})}}}var Fm=(()=>typeof window!="undefined"&&window.__AFSM__?(e,r)=>{window.dispatchEvent(new CustomEvent(e,{detail:r}))}:typeof importScripts!="undefined"?(e,r)=>{postMessage({type:e,payload:r})}:()=>{})();function Ss(i,t){let e=this._state;this._state=i;let r=i.toString();i&&this.emit(r,e),this.emit(he.STATECHANGED,i,e,t),this.updateDevTools({value:i,old:e,err:t})}var Gm,Wm,Ye=class extends bu.default{constructor(e,r,n){super();p(this,"name");p(this,"groupName");p(this,"_state",Ye.INIT);p(this,Gm);p(this,Wm);this.name=e,this.groupName=r,e||(e=Date.now().toString(36)),n?Object.setPrototypeOf(this,n):n=Object.getPrototypeOf(this),r||(this.groupName=this.constructor.name);let s=n[Nu];s?this.name=s.name+"-"+s.count++:n[Nu]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),r=sn.get(e)||[],n=new Set,s=[],o=[],a=new Set,c=Object.getPrototypeOf(e);sn.has(c)&&(c.stateDiagram.forEach(u=>n.add(u)),c.allStates.forEach(u=>a.add(u))),r.forEach(({from:u,to:l,action:h})=>{typeof u=="string"?s.push({from:u,to:l,action:h}):u.length?u.forEach(I=>{s.push({from:I,to:l,action:h})}):o.push({to:l,action:h})}),s.forEach(({from:u,to:l,action:h})=>{a.add(u),a.add(l),a.add(h+"ing"),n.add(`${u} --> ${h}ing : ${h}`),n.add(`${h}ing --> ${l} : ${h} \u{1F7E2}`),n.add(`${h}ing --> ${u} : ${h} \u{1F534}`)}),o.forEach(({to:u,action:l})=>{n.add(`${l}ing --> ${u} : ${l} \u{1F7E2}`),a.forEach(h=>{h!==u&&n.add(`${h} --> ${l}ing : ${l}`)})});let d=[...n];return Object.defineProperties(e,{stateDiagram:{value:d},allStates:{value:a}}),d}static get(e){let r;return typeof e=="string"?(r=Ye.instances.get(e),r||Ye.instances.set(e,r=new Ye(e,void 0,Object.create(Ye.prototype)))):(r=Ye.instances2.get(e),r||Ye.instances2.set(e,r=new Ye(e.constructor.name,void 0,Object.create(Ye.prototype)))),r}static getState(e){var r;return(r=Ye.get(e))==null?void 0:r.state}updateDevTools(e={}){Fm(Ye.UPDATEAFSM,B({name:this.name,group:this.groupName},e))}get state(){return this._state}set state(e){Ss.call(this,e)}},he=Ye;Gm=Ni,Wm=rn,p(he,"STATECHANGED","stateChanged"),p(he,"UPDATEAFSM","updateAFSM"),p(he,"INIT","[*]"),p(he,"ON","on"),p(he,"OFF","off"),p(he,"instances",new Map),p(he,"instances2",new WeakMap);var Gg=_(f(),1);var fg=_(f(),1);var HS=_(f(),1);var xS=_(f(),1);var GT=_(f(),1);var Du=(window==null?void 0:window.requestIdleCallback)||function(i){let t=Date.now();return setTimeout(()=>{i({didTimeout:!1,timeRemaining(){return Math.max(0,50-(Date.now()-t))}})},1e3)},Km=(window==null?void 0:window.cancelIdleCallback)||function(i){clearTimeout(i)},jm=(window==null?void 0:window.cancelAnimationFrame)||(window==null?void 0:window.mozCancelAnimationFrame),on=class{static generateTaskID(){return this.currentTaskID++}static run(t=xr,e,r){t===Gd?r=B({delay:2e3,count:0,backgroundTask:!0},r):t===kt?r=B({delay:1e4,count:0},r):t===ii?r=B({fps:60,delay:16.6,count:0,backgroundTask:!0},r):r=B({delay:2e3,count:0,backgroundTask:!0},r),yi(e)&&(r=B(B({},r),e)),ue(t)&&(e=t,t=xr);let n=B({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:t,callback:e},r);return this.taskMap.set(n.taskID,n),this[t](n),n.taskID}static interval(t){let e=()=>{t.callback(),t.loopCount+=1,this.isBreakLoop(t)};return t.intervalID=setInterval(e,t.delay)}static timeout(t){let e=()=>{if(t.callback(),t.loopCount+=1,!this.isBreakLoop(t))return t.timeoutID=setTimeout(e,t.delay)};return t.timeoutID=setTimeout(e,t.delay)}static ric(t){let e=q(),r,n=()=>{if(r=q()-e,r>=t.delay&&(e=q()-Math.floor(r%t.delay),t.callback(),t.loopCount+=1),!this.isBreakLoop(t))return t.ricID=Du(n,{timeout:t.delay})};return t.ricID=Du(n,{timeout:t.delay})}static raf(t){t.delay=(1e3/t.fps).toFixed(2);let e=q(),r,n=()=>{if(document.hidden&&t.backgroundTask)return r=q()-e,e=q(),t.callback(),t.loopCount+=1,this.isBreakLoop(t)?void 0:t.timeoutID=setTimeout(n,t.delay-Math.floor(r%t.delay));if(r=q()-e,r>=t.delay&&(e=q()-Math.floor(r%t.delay),t.callback(),t.loopCount+=1),!this.isBreakLoop(t))return t.rafID=requestAnimationFrame(n)};if(t.rafID=requestAnimationFrame(n),t.backgroundTask){let s=()=>{if(document.hidden){let o=q()-e;o>=t.delay?n():t.timeoutID=setTimeout(n,t.delay-o)}};document.addEventListener("visibilitychange",s),t.onVisibilitychange=s,document.hidden&&s()}return t.taskID}static hasTask(t){return this.taskMap.has(t)}static clearTask(t){if(!this.taskMap.has(t))return!0;let{intervalID:e,timeoutID:r,rafID:n,ricID:s,onVisibilitychange:o}=this.taskMap.get(t);return e&&clearInterval(e),r&&clearTimeout(r),n&&jm(n),s&&Km(s),o&&document.removeEventListener("visibilitychange",o),this.taskMap.delete(t),!0}static isBreakLoop(t){return this.taskMap.has(t.taskID)?t.count!==0&&t.loopCount>=t.count?(this.clearTask(t.taskID),!0):!1:!0}};on.taskMap=new Map,on.currentTaskID=1;var me=on;var YT=_(f(),1);var Ou={STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",STREAM_UPDATED:"stream-updated",STREAM_PUBLISHED:"stream-published",STREAM_SUBSCRIBED:"stream-subscribed",STREAM_UNSUBSCRIBED:"stream-unsubscribed",STATE_CHANGED:"state-changed",ERROR:"error",CONNECTION_STATE_CHANGED:"connection-state-changed",SEI_MESSAGE:m.SEI_MESSAGE},jT={STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",STREAM_UPDATED:"stream-updated",STREAM_SUBSCRIBED:"stream-subscribed",CONNECTION_STATE_CHANGED:"connection-state-changed",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",MUTE_AUDIO:"mute-audio",MUTE_VIDEO:"mute-video",UNMUTE_AUDIO:"unmute-audio",UNMUTE_VIDEO:"unmute-video",CLIENT_BANNED:"client-banned",NETWORK_QUALITY:"network-quality",AUDIO_VOLUME:"audio-volume",SEI_MESSAGE:m.SEI_MESSAGE,ERROR:"error"};var Nt={LOADED_DATA:m.LOADEDDATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed"};var mS=_(f(),1);var sS=_(f(),1);var pa=class{constructor(){this._roomIdMap=new Map;typeof registerProcessor=="undefined"&&(this._configs={sdkAppId:"",userId:"",version:We,env:ei.QCLOUD,browserVersion:tr.name+tr.version,ua:navigator.userAgent})}setConfig({sdkAppId:t,env:e,userId:r,roomId:n}){t!==this._configs.sdkAppId&&(this._configs.sdkAppId=String(t)),this._configs.env=e,this._configs.userId=r,this._roomIdMap.set(r,String(n))}logSuccessEvent(t){Rt||!M.isAbleToUpload||this._configs.env===ei.QCLOUD&&this.uploadEventToKibana(te(B({},t),{result:"success"}))}logFailedEvent(t){if(Rt||!M.isAbleToUpload)return;let{eventType:e,code:r,error:n,userId:s}=t,o={roomId:this._roomIdMap.get(s||this._configs.userId),userId:s,eventType:e,result:"failed",code:r||(n==null?void 0:n.extraCode)||(n==null?void 0:n.code)||v.UNKNOWN};this._configs.env===ei.QCLOUD&&this.uploadEventToKibana(te(B({},o),{error:n}))}uploadEventToKibana(t){let e=`stat-${t.eventType}-${t.result}`;(t.eventType==="delta-join"||t.eventType==="delta-leave"||t.eventType==="delta-publish")&&(e=`${t.eventType}:${t.delta}`),this.uploadEvent({log:e,userId:t.userId}),t.result==="failed"&&(e=`stat-${t.eventType}-${t.result}-${t.code}`,this.uploadEvent({log:e,userId:t.userId,error:t.error}))}uploadEvent({log:t,userId:e,error:r}){let n={timestamp:Xn(),sdkAppId:this._configs.sdkAppId,userId:e||this._configs.userId,version:We,log:t};r&&(n.errorInfo=r.message),this.sendRequest(Ci(this._configs.sdkAppId,Xi.LOG),n)}sendRequest(t,e){if(!M.isAbleToUpload){setTimeout(()=>{this.sendRequest(t,e)},1e3);return}ai({url:t,body:JSON.stringify(e)}).catch(()=>{})}},Ee=new pa;var $t="trtc_autoplay",ha=`${$t}_mask`,or=`${$t}_wrapper`,Pu=`${$t}_header`,ma=`${$t}_content`,gs=`${$t}_action_wrapper`,_a=`${$t}_question`,fa=`${$t}_collapse`,Is=`${$t}_action_confirm`,Mu=`${$t}_detail`,Lu="#2473E8",Ta="dialog",Jm=`${Ta}-show`,Ym=`${Ta}-1`,Xm=`${Ta}-2`,ku=!1,Sa=()=>!!document.querySelector(`.${or}`),Uu=`${Ji}/${Ct()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,xu=`<br><a href='${Uu}' target='_blank'>${Ct()?"\u5176\u4ED6\u65B9\u6848\uFF1F":"Any other solution?"}</a>`,zm=`${Ct()?`\u6D4F\u89C8\u5668\u81EA\u52A8\u64AD\u653E\u7B56\u7565\uFF1A\u5728\u7528\u6237\u4E0E\u9875\u9762\u4EA7\u751F\u4EA4\u4E92\uFF08\u70B9\u51FB\u3001\u89E6\u6478\uFF09\u4E4B\u524D\uFF0C\u6D4F\u89C8\u5668\u7981\u6B62\u64AD\u653E\u6709\u58F0\u5A92\u4F53\u3002\u8BE5\u5F39\u7A97\u7528\u4E8E\u5E2E\u52A9\u7528\u6237\u6062\u590D\u97F3\u89C6\u9891\u64AD\u653E\u3002${xu}`:`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. ${xu}`}`,Ea=class{constructor(){p(this,"content","\u97F3\u89C6\u9891\u64AD\u653E\u88AB\u6D4F\u89C8\u5668\u62E6\u622A\uFF0C\u8BF7\u70B9\u51FB\u201C\u6062\u590D\u64AD\u653E\u201D\u3002");p(this,"_dialogNode",null);p(this,"_bodyPosition","");p(this,"_showDetail",!1);p(this,"_isCollapseClicked",!1);p(this,"_isQuestionClicked",!1);if(Ct()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!ku){let t=document.createElement("style");t.innerHTML=`.${ha}{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;}.${ha} div:not(.${gs}){display:block !important;}.${or}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${or} a{color:${Lu};}.${Pu}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${ma}{margin:8px 0;}.${gs}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${fa}{margin-right:auto;cursor:pointer}.${_a}{height:100%;line-height:16px;cursor:pointer;}.${Is}{margin-left:8px;color:#fff;background:${Lu};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${Is}:hover{opacity:0.9;}.${fa},.${Is},.${ma},.${_a}{font-size:14px;}@media screen and (max-width:750px){.${or}{width:80vw;}}`,document.head.appendChild(t),ku=!0}this.addDiaLog()}createDiaLog(){let t=document.createElement("template");t.innerHTML=`<div class="${ha}"><div class='${or}'><div class='${Pu}'>${location.host}</div><div class='${ma}'>${this.content}</div><div class='${Mu}' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">${zm}</div><div class='${gs}'></div></div></div>`.trim();let e=document.createElement("button");e.className=Is,e.innerText=Ct()?"\u6062\u590D\u64AD\u653E":"Resume",e.onclick=this.onConfirm.bind(this);let r=document.createElement("div");r.className=_a,r.innerHTML=`<?xml version="1.0" encoding="UTF-8"?>
81
+ Refer to: ${Su("en",a)}
82
+ `),u}var le={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},__=new Map([[ue,["Firefox",ps]],[cr,["Edg",ms]],[_r,["Chrome",bs]],[ht,["Safari",Er]],[At,["TBS",Es]],[nn,["XWEB",Ts]],[dr&&si,["WeChat",Ss]],[sn,["QQ(Win)",gs]],[lr,["QQ(Mobile)",sr]],[ur,["QQ(Mobile X5)",sr]],[on,["QQ(Mac)",Is]],[an,["QQ(iPad)",Rs]],[cn,["MI",As]],[dn,["HW",Cs]],[un,["Samsung",ys]],[ln,["OPPO",vs]],[pn,["VIVO",Ns]],[ar,["EDGE",hs]],[tn,["SogouMobile",_s]],[rn,["Sogou",fs]]]);function f_(){let i=__.get(!0),t=i?i[0]:"unknown",e=i?i[1]:"unknown";return{browserName:t,browserVersion:e}}var Da=function(){return!(na||ar||cr&&ra<80||ue&&ia<56)},Ru=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder","MediaStreamTrackGenerator"].every(t=>t in window)},Fs=function(){if(!navigator.mediaDevices)return O.error(xe.NOT_SUPPORTED_MEDIA),!1;let i=["getUserMedia","enumerateDevices"];return i.filter(t=>t in navigator.mediaDevices).length===i.length},gu=!1;function Oa(){return location.protocol==="http:"&&!mt&&!gu?(gu=!0,O.warn(B({key:V.NOT_SUPPORTED_HTTP})),!0):!1}var Pa=function(){return(window==null?void 0:window.OffscreenCanvas)&&(window==null?void 0:window.MediaStreamTrackProcessor)&&(window==null?void 0:window.MediaStreamTrackGenerator)},Au=function(){return E(this,null,function*(){if(le.detail.isH264EncodeSupported||le.detail.isVp8EncodeSupported)return{isH264EncodeSupported:le.detail.isH264EncodeSupported,isVp8EncodeSupported:le.detail.isVp8EncodeSupported};let i,t=!1,e=!1;try{let r=new RTCPeerConnection,n=document.createElement(m.CANVAS);n.getContext("2d");let s=n.captureStream(0);return r.addTrack(s.getVideoTracks()[0],s),i=yield r.createOffer(),i.sdp.toLowerCase().indexOf("h264")!==-1&&(t=!0),i.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0),r.close(),le.detail.isH264EncodeSupported=t,le.detail.isVp8EncodeSupported=e,{isH264EncodeSupported:le.detail.isH264EncodeSupported,isVp8EncodeSupported:le.detail.isVp8EncodeSupported}}catch(r){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1}}})},Gs=function(){return E(this,null,function*(){if(le.detail.isH264DecodeSupported&&le.detail.isVp8DecodeSupported)return{isH264DecodeSupported:le.detail.isH264DecodeSupported,isVp8DecodeSupported:le.detail.isVp8DecodeSupported};let i,t=!1,e=!1;try{let r=new RTCPeerConnection;return i=yield r.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0}),i.sdp.toLowerCase().indexOf("h264")!==-1&&(t=!0),i.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0),r.close(),{isH264DecodeSupported:t,isVp8DecodeSupported:e}}catch(r){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1}}})},Ma=function(){return E(this,null,function*(){if(le.result)return le;let i=Da(),t=xa(),e=Ru(),r=Fs(),{isH264EncodeSupported:n,isVp8EncodeSupported:s}=yield Au(),{isH264DecodeSupported:o,isVp8DecodeSupported:a}=yield Gs();return le.result=i&&t&&r&&(n||s)&&(o||a),le.detail.isBrowserSupported=i,le.detail.isWebRTCSupported=t,le.detail.isWebCodecsSupported=e,le.detail.isMediaDevicesSupported=r,le.detail.isScreenShareSupported=La(),le.detail.isSmallStreamSupported=Ws(),le.detail.isH264EncodeSupported=n,le.detail.isVp8EncodeSupported=s,le.detail.isH264DecodeSupported=o,le.detail.isVp8DecodeSupported=a,le.result||O.error(`${navigator.userAgent} isBrowserSupported: ${i}isWebCodecsSupported: ${e} isMediaSupported: ${r} isH264EncodeSupported: ${n} isVp8EncodeSupported: ${s} isH264DecodeSupported: ${o} isVp8DecodeSupported: ${a} `),le})},E_=function(){return le.result},La=function(){return!!(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)},T_=(i,t,e)=>{location.protocol==="http:"&&!mt&&(i[t]=()=>{throw new M({code:v.INVALID_OPERATION,message:xe.NOT_SUPPORTED_HTTP})})},hi=function(i){return i.type==="candidate-pair"&&i.nominated&&(i.state==="in-progress"||i.state==="succeeded")?!(Ne(i.selected)&&!i.selected):!1},Iu=new Map([[st,"Android"],[nt,"iOS"],[pr,"Windows"],[Ct,"MacOS"],[hr,"Linux"]]),Cu=function(){return Iu.get(!0)?Iu.get(!0):"unknown"};function yu(){let i="";if(screen.width){let t=screen.width?screen.width*window.devicePixelRatio:"",e=screen.height?screen.height*window.devicePixelRatio:"";i+=`${t} * ${e}`}return i}function vu(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function Nu(){let i={isSupported:!1},t=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"];for(let e=0;e<t.length;e++)if(t[e]in window){i.isSupported=!0;break}return i.isSupported}function bu(){return"captureStream"in HTMLCanvasElement.prototype}function Ws(){return dr||nt||fr&&fr<63?!1:!!(Da()&&bu())}var S_=function(){if(b(window.RTCRtpTransceiver)||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let i=null,t=!1;try{i=new RTCPeerConnection({sdpSemantics:ci}),i.addTransceiver(m.AUDIO),t=!0}catch(e){}return i==null||i.close(),t};function Hi(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function Dr(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function at(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function mi(){return"RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype}var Ks=mi();function g_(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}function I_(){return"RTCRtpSender"in window&&"replaceTrack"in window.RTCRtpSender.prototype}function Dn(){return"RTCRtpSender"in window&&"setParameters"in window.RTCRtpSender.prototype&&Dr()}var Ft=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,ka=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,_i="RTCRtpSender"in window&&"createEncodedStreams"in window.RTCRtpSender.prototype&&mr()>=86,xa=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(t=>t in window).length>0};function Du(){let i={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return b(window.AudioDecoder)||(i.AudioDecoder=!0),b(window.AudioEncoder)||(i.AudioEncoder=!0),b(window.VideoDecoder)||(i.VideoDecoder=!0),b(window.VideoEncoder)||(i.VideoEncoder=!0),b(window.ImageDecoder)||(i.ImageDecoder=!0),i}function Ou(){return"mediaSession"in navigator&&!b(navigator.mediaSession.setActionHandler)}function Pu(){return!b(window.WebTransport)}function R_(){let i={browser:`${bi.name}/${bi.version}`,os:Cu(),displayResolution:yu(),isScreenShareSupported:La(),isWebRTCSupported:xa(),isGetUserMediaSupported:vu(),isWebAudioSupported:Nu(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:Du(),isMediaSessionSupported:Ou(),isWebTransportSupported:Pu()};return navigator.userAgent.includes("miniProgram")&&(i.browser=`mini/${i.browser}`),i}var iS=_(f(),1),Lu=_(rt(),1);var Mu=Symbol("instance"),On=Symbol("abortCtrl"),Fi=Symbol("cacheResult"),Ua=class{constructor(t,e,r){p(this,"oldState");p(this,"newState");p(this,"action");p(this,"error");this.oldState=t,this.newState=e,this.action=r}toString(){return`${this.action}ing`}},Pn=class extends Error{constructor(e,r,n){super(r);p(this,"state");p(this,"message");p(this,"cause");this.state=e,this.message=r,this.cause=n}},Mn=new Map,A_=Object.getPrototypeOf((()=>E(void 0,null,function*(){}))()).constructor;function Ke(i,t,e={}){return(r,n,s)=>{let o=e.action||n;if(!e.context){let c=Mn.get(r)||[];Mn.has(r)||Mn.set(r,c),c.push({from:i,to:t,action:o})}let a=s.value;s.value=function(...c){return E(this,null,function*(){var I;let d=this;if(e.context&&(d=he.get(typeof e.context=="function"?e.context.call(this,...c):e.context)),d.state===t)return d[Fi];let u=null;if(Array.isArray(i)?i.length==0?d[On]&&(d[On].aborted=!0):(typeof d.state!="string"||!i.includes(d.state))&&(u=new Pn(d._state,`${d.name} ${o} to ${t} failed: current state ${d._state} not in from config`)):i!==d.state&&(u=new Pn(d._state,`${d.name} ${o} to ${t} failed: current state ${d._state} not from ${i}`)),u)if(e.fail)e.fail.call(this,u);else{if(e.ignoreError)return u;throw u}let l=d.state;js.call(d,new Ua(l,t,o));let h={aborted:!1};d[On]=h;try{let T=a.apply(this,c);return T instanceof A_?d[Fi]=yield T:d[Fi]=T,h.aborted||(d[On]=void 0,js.call(d,t),(I=e.success)==null||I.call(this,d[Fi])),d[Fi]}catch(T){let N=T instanceof Error?T.message:String(T);if(js.call(d,l,N),e.fail)e.fail.call(this,new Pn(d._state,`action '${o}' failed :${N}`,T instanceof Error?T:new Error(N)));else{if(e.ignoreError)return T;throw T}}})}}}var C_=(()=>typeof window!="undefined"&&window.__AFSM__?(e,r)=>{window.dispatchEvent(new CustomEvent(e,{detail:r}))}:typeof importScripts!="undefined"?(e,r)=>{postMessage({type:e,payload:r})}:()=>{})();function js(i,t){let e=this._state;this._state=i;let r=i.toString();i&&this.emit(r,e),this.emit(he.STATECHANGED,i,e,t),this.updateDevTools({value:i,old:e,err:t})}var y_,v_,Je=class extends Lu.default{constructor(e,r,n){super();p(this,"name");p(this,"groupName");p(this,"_state",Je.INIT);p(this,y_);p(this,v_);this.name=e,this.groupName=r,e||(e=Date.now().toString(36)),n?Object.setPrototypeOf(this,n):n=Object.getPrototypeOf(this),r||(this.groupName=this.constructor.name);let s=n[Mu];s?this.name=s.name+"-"+s.count++:n[Mu]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),r=Mn.get(e)||[],n=new Set,s=[],o=[],a=new Set,c=Object.getPrototypeOf(e);Mn.has(c)&&(c.stateDiagram.forEach(u=>n.add(u)),c.allStates.forEach(u=>a.add(u))),r.forEach(({from:u,to:l,action:h})=>{typeof u=="string"?s.push({from:u,to:l,action:h}):u.length?u.forEach(I=>{s.push({from:I,to:l,action:h})}):o.push({to:l,action:h})}),s.forEach(({from:u,to:l,action:h})=>{a.add(u),a.add(l),a.add(h+"ing"),n.add(`${u} --> ${h}ing : ${h}`),n.add(`${h}ing --> ${l} : ${h} \u{1F7E2}`),n.add(`${h}ing --> ${u} : ${h} \u{1F534}`)}),o.forEach(({to:u,action:l})=>{n.add(`${l}ing --> ${u} : ${l} \u{1F7E2}`),a.forEach(h=>{h!==u&&n.add(`${h} --> ${l}ing : ${l}`)})});let d=[...n];return Object.defineProperties(e,{stateDiagram:{value:d},allStates:{value:a}}),d}static get(e){let r;return typeof e=="string"?(r=Je.instances.get(e),r||Je.instances.set(e,r=new Je(e,void 0,Object.create(Je.prototype)))):(r=Je.instances2.get(e),r||Je.instances2.set(e,r=new Je(e.constructor.name,void 0,Object.create(Je.prototype)))),r}static getState(e){var r;return(r=Je.get(e))==null?void 0:r.state}updateDevTools(e={}){C_(Je.UPDATEAFSM,w({name:this.name,group:this.groupName},e))}get state(){return this._state}set state(e){js.call(this,e)}},he=Je;y_=Fi,v_=On,p(he,"STATECHANGED","stateChanged"),p(he,"UPDATEAFSM","updateAFSM"),p(he,"INIT","[*]"),p(he,"ON","on"),p(he,"OFF","off"),p(he,"instances",new Map),p(he,"instances2",new WeakMap);var aI=_(f(),1);var kg=_(f(),1);var sg=_(f(),1);var ZS=_(f(),1);var aS=_(f(),1);var ku=(window==null?void 0:window.requestIdleCallback)||function(i){let t=Date.now();return setTimeout(()=>{i({didTimeout:!1,timeRemaining(){return Math.max(0,50-(Date.now()-t))}})},1e3)},N_=(window==null?void 0:window.cancelIdleCallback)||function(i){clearTimeout(i)},b_=(window==null?void 0:window.cancelAnimationFrame)||(window==null?void 0:window.mozCancelAnimationFrame),Ln=class{static generateTaskID(){return this.currentTaskID++}static run(t=yr,e,r){t===Ia?r=w({delay:2e3,count:0,backgroundTask:!0},r):t===vt?r=w({delay:1e4,count:0},r):t===$t?r=w({fps:60,delay:16.6,count:0,backgroundTask:!0},r):r=w({delay:2e3,count:0,backgroundTask:!0},r),Bi(e)&&(r=w(w({},r),e)),ce(t)&&(e=t,t=yr);let n=w({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:t,callback:e},r);return this.taskMap.set(n.taskID,n),this[t](n),n.taskID}static interval(t){let e=()=>{t.callback(),t.loopCount+=1,this.isBreakLoop(t)};return t.intervalID=setInterval(e,t.delay)}static timeout(t){let e=()=>{if(t.callback(),t.loopCount+=1,!this.isBreakLoop(t))return t.timeoutID=setTimeout(e,t.delay)};return t.timeoutID=setTimeout(e,t.delay)}static ric(t){let e=z(),r,n=()=>{if(r=z()-e,r>=t.delay&&(e=z()-Math.floor(r%t.delay),t.callback(),t.loopCount+=1),!this.isBreakLoop(t))return t.ricID=ku(n,{timeout:t.delay})};return t.ricID=ku(n,{timeout:t.delay})}static raf(t){t.delay=(1e3/t.fps).toFixed(2);let e=z(),r,n=()=>{if(document.hidden&&t.backgroundTask)return r=z()-e,e=z(),t.callback(),t.loopCount+=1,this.isBreakLoop(t)?void 0:t.timeoutID=setTimeout(n,t.delay-Math.floor(r%t.delay));if(r=z()-e,r>=t.delay&&(e=z()-Math.floor(r%t.delay),t.callback(),t.loopCount+=1),!this.isBreakLoop(t))return t.rafID=requestAnimationFrame(n)};if(t.rafID=requestAnimationFrame(n),t.backgroundTask){let s=()=>{if(document.hidden){let o=z()-e;o>=t.delay?n():t.timeoutID=setTimeout(n,t.delay-o)}};document.addEventListener("visibilitychange",s),t.onVisibilitychange=s,document.hidden&&s()}return t.taskID}static hasTask(t){return this.taskMap.has(t)}static clearTask(t){if(!this.taskMap.has(t))return!0;let{intervalID:e,timeoutID:r,rafID:n,ricID:s,onVisibilitychange:o}=this.taskMap.get(t);return e&&clearInterval(e),r&&clearTimeout(r),n&&b_(n),s&&N_(s),o&&document.removeEventListener("visibilitychange",o),this.taskMap.delete(t),!0}static isBreakLoop(t){return this.taskMap.has(t.taskID)?t.count!==0&&t.loopCount>=t.count?(this.clearTask(t.taskID),!0):!1:!0}};Ln.taskMap=new Map,Ln.currentTaskID=1;var me=Ln;var pS=_(f(),1);var xu={STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",STREAM_UPDATED:"stream-updated",STREAM_PUBLISHED:"stream-published",STREAM_SUBSCRIBED:"stream-subscribed",STREAM_UNSUBSCRIBED:"stream-unsubscribed",STATE_CHANGED:"state-changed",ERROR:"error",CONNECTION_STATE_CHANGED:"connection-state-changed",SEI_MESSAGE:m.SEI_MESSAGE},uS={STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",STREAM_UPDATED:"stream-updated",STREAM_SUBSCRIBED:"stream-subscribed",CONNECTION_STATE_CHANGED:"connection-state-changed",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",MUTE_AUDIO:"mute-audio",MUTE_VIDEO:"mute-video",UNMUTE_AUDIO:"unmute-audio",UNMUTE_VIDEO:"unmute-video",CLIENT_BANNED:"client-banned",NETWORK_QUALITY:"network-quality",AUDIO_VOLUME:"audio-volume",SEI_MESSAGE:m.SEI_MESSAGE,ERROR:"error"};var Pt={LOADED_DATA:m.LOADEDDATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed"};var MS=_(f(),1);var AS=_(f(),1);var Va=class{constructor(){this._roomIdMap=new Map;typeof registerProcessor=="undefined"&&(this._configs={sdkAppId:"",userId:"",version:$e,env:wt.QCLOUD,browserVersion:bi.name+bi.version,ua:navigator.userAgent})}setConfig({sdkAppId:t,env:e,userId:r,roomId:n}){t!==this._configs.sdkAppId&&(this._configs.sdkAppId=String(t)),this._configs.env=e,this._configs.userId=r,this._roomIdMap.set(r,String(n))}logSuccessEvent(t){mt||!O.isAbleToUpload||this._configs.env===wt.QCLOUD&&this.uploadEventToKibana(ee(w({},t),{result:"success"}))}logFailedEvent(t){if(mt||!O.isAbleToUpload)return;let{eventType:e,code:r,error:n,userId:s}=t,o={roomId:this._roomIdMap.get(s||this._configs.userId),userId:s,eventType:e,result:"failed",code:r||(n==null?void 0:n.extraCode)||(n==null?void 0:n.code)||v.UNKNOWN};this._configs.env===wt.QCLOUD&&this.uploadEventToKibana(ee(w({},o),{error:n}))}uploadEventToKibana(t){let e=`stat-${t.eventType}-${t.result}`;(t.eventType==="delta-join"||t.eventType==="delta-leave"||t.eventType==="delta-publish")&&(e=`${t.eventType}:${t.delta}`),this.uploadEvent({log:e,userId:t.userId}),t.result==="failed"&&(e=`stat-${t.eventType}-${t.result}-${t.code}`,this.uploadEvent({log:e,userId:t.userId,error:t.error}))}uploadEvent({log:t,userId:e,error:r}){let n={timestamp:ls(),sdkAppId:this._configs.sdkAppId,userId:e||this._configs.userId,version:$e,log:t};r&&(n.errorInfo=r.message),this.sendRequest(wi(this._configs.sdkAppId,Li.LOG),n)}sendRequest(t,e){if(!O.isAbleToUpload){setTimeout(()=>{this.sendRequest(t,e)},1e3);return}pi({url:t,body:JSON.stringify(e)}).catch(()=>{})}},_e=new Va;var Wt="trtc_autoplay",wa=`${Wt}_mask`,Or=`${Wt}_wrapper`,Uu=`${Wt}_header`,Ba=`${Wt}_content`,Js=`${Wt}_action_wrapper`,$a=`${Wt}_question`,Ha=`${Wt}_collapse`,Ys=`${Wt}_action_confirm`,Vu=`${Wt}_detail`,wu="#2473E8",Ga="dialog",D_=`${Ga}-show`,O_=`${Ga}-1`,P_=`${Ga}-2`,Bu=!1,Wa=()=>!!document.querySelector(`.${Or}`),Hu=`${Pi}/${Nt()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,$u=`<br><a href='${Hu}' target='_blank'>${Nt()?"\u5176\u4ED6\u65B9\u6848\uFF1F":"Any other solution?"}</a>`,M_=`${Nt()?`\u6D4F\u89C8\u5668\u81EA\u52A8\u64AD\u653E\u7B56\u7565\uFF1A\u5728\u7528\u6237\u4E0E\u9875\u9762\u4EA7\u751F\u4EA4\u4E92\uFF08\u70B9\u51FB\u3001\u89E6\u6478\uFF09\u4E4B\u524D\uFF0C\u6D4F\u89C8\u5668\u7981\u6B62\u64AD\u653E\u6709\u58F0\u5A92\u4F53\u3002\u8BE5\u5F39\u7A97\u7528\u4E8E\u5E2E\u52A9\u7528\u6237\u6062\u590D\u97F3\u89C6\u9891\u64AD\u653E\u3002${$u}`:`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. ${$u}`}`,Fa=class{constructor(){p(this,"content","\u97F3\u89C6\u9891\u64AD\u653E\u88AB\u6D4F\u89C8\u5668\u62E6\u622A\uFF0C\u8BF7\u70B9\u51FB\u201C\u6062\u590D\u64AD\u653E\u201D\u3002");p(this,"_dialogNode",null);p(this,"_bodyPosition","");p(this,"_showDetail",!1);p(this,"_isCollapseClicked",!1);p(this,"_isQuestionClicked",!1);if(Nt()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!Bu){let t=document.createElement("style");t.innerHTML=`.${wa}{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;}.${wa} div:not(.${Js}){display:block !important;}.${Or}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${Or} a{color:${wu};}.${Uu}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${Ba}{margin:8px 0;}.${Js}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${Ha}{margin-right:auto;cursor:pointer}.${$a}{height:100%;line-height:16px;cursor:pointer;}.${Ys}{margin-left:8px;color:#fff;background:${wu};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${Ys}:hover{opacity:0.9;}.${Ha},.${Ys},.${Ba},.${$a}{font-size:14px;}@media screen and (max-width:750px){.${Or}{width:80vw;}}`,document.head.appendChild(t),Bu=!0}this.addDiaLog()}createDiaLog(){let t=document.createElement("template");t.innerHTML=`<div class="${wa}"><div class='${Or}'><div class='${Uu}'>${location.host}</div><div class='${Ba}'>${this.content}</div><div class='${Vu}' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">${M_}</div><div class='${Js}'></div></div></div>`.trim();let e=document.createElement("button");e.className=Ys,e.innerText=Nt()?"\u6062\u590D\u64AD\u653E":"Resume",e.onclick=this.onConfirm.bind(this);let r=document.createElement("div");r.className=$a,r.innerHTML=`<?xml version="1.0" encoding="UTF-8"?>
85
83
  <svg class="icon" width="18" height="18" p-id="2030" t="1639646523624" version="1.1" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
86
84
  <path d="m464 784.35c0 26.51 21.49 48 48 48s48-21.49 48-48-21.49-48-48-48-48 21.49-48 48z" p-id="2031"/>
87
85
  <path d="m512 960c-247.04 0-448-200.96-448-448s200.96-448 448-448 448 200.96 448 448-200.96 448-448 448zm0-831.71c-211.58 0-383.71 172.13-383.71 383.71 0 211.55 172.13 383.71 383.71 383.71 211.55 0 383.71-172.16 383.71-383.71 0-211.58-172.16-383.71-383.71-383.71z" p-id="2032"/>
88
86
  <path d="m512 673.7c-17.665 0-32.001-14.336-32.001-31.999v-54.112c0-52.353 40-92.352 75.328-127.65 25.887-25.92 52.672-52.672 52.672-74.017 0-53.343-43.072-96.735-95.999-96.735-53.823 0-95.999 41.536-95.999 94.559 0 17.665-14.336 31.999-32.001 31.999s-32.001-14.336-32.001-31.999c0-87.424 71.775-158.56 160-158.56s160 72.095 160 160.74c0 47.904-36.32 84.192-71.424 119.3-27.84 27.776-56.576 56.512-56.576 82.336v54.112c0 17.665-14.336 32.032-32.001 32.032z" p-id="2033"/>
89
87
  </svg>
90
- `,r.onclick=this.onQuestionClick.bind(this);let n=document.createElement("div");n.className=fa,n.innerText=`${Ct()?"\u8BE6\u60C5 >":"Detail >"}`,n.onclick=this.onCollapseClick.bind(this);let s=t.content.firstChild,o=s.querySelector(`.${gs}`);return o.appendChild(n),o.appendChild(r),o.appendChild(e),s}addDiaLog(){Sa()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${or}`).onclick=t=>t.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",M.info("show autoplay dialog"),Ee.uploadEvent({log:Jm}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){M.warn("confirm clicked, try resume stream"),C.emit(S.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let t=this._dialogNode.querySelector(`.${Mu}`);t.style.visibility=`${this._showDetail?"hidden":"visible"}`,t.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||Ee.uploadEvent({log:Ym}),this._isCollapseClicked=!0}onQuestionClick(){window.open(Uu,"_blank"),this._isQuestionClicked||Ee.uploadEvent({log:Xm}),this._isQuestionClicked=!0}},Vu=Ea;var ar={};oo(ar,{create:()=>ot,remove:()=>Be});var fS=_(f(),1),an=new WeakMap;function ot(i,t){an.has(i)||an.set(i,[]);let e=an.get(i),n={add:(s,o)=>("addEventListener"in t?(e.push(t.removeEventListener.bind(t,s,o)),t.addEventListener(s,o)):(e.push(t.off.bind(t,s,o)),t.on(s,o)),n)};return n}function Be(i){let t=an.get(i);t&&(t.forEach(e=>e()),an.delete(i))}var Ht=class extends he{constructor(e,r){super(e.id,`${r}-player`);this.kind=r;p(this,"id");p(this,"element",null);p(this,"container",null);p(this,"mediaStream",new MediaStream);p(this,"track");p(this,"url");p(this,"attr");p(this,"muted");p(this,"_log");p(this,"_pausedRetryCount");p(this,"_isElementPlayingFired",!1);p(this,"_interval");this.id=e.id,this._log=e.log,this.track=e.track,this.container=e.container,this.muted=e.muted,this._pausedRetryCount=Hd,this._state="STOPPED",this.bindTrackEvents()}get isPlaying(){return this._state==="PLAYING"}get isStopped(){return this._state==="STOPPED"}setAttr(e){this.attr=e}setTrack(e){if(e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(Nt.MEDIA_TRACK_CHANGED,e),e!==null&&(this.bindTrackEvents(),this.element))){let r=new MediaStream;r.addTrack(e),this.element.srcObject=r}}setUrl(e){this.track&&(this.unbindTrackEvents(),this.element&&(this.element.srcObject=null),this.track=null),e!==this.url&&(this.url=e,e!==null&&this.element&&(this.element.crossOrigin="anonymous",this.element.src=e))}setContainer(e){this.container=e,this.track&&this.element&&this.container&&this.container.appendChild(this.element)}play(){return E(this,null,function*(){if(this.element&&this.element.parentElement!==this.container&&this.container&&this.container.append(this.element),!this.isPlaying)try{this.bindAutoPlayEvent(),yield this.element.play()}catch(e){let r=$({key:w.PLAY_FAILED,data:{media:this.kind,error:e}});if(this.track&&!this.track.muted&&this._log.warn(e),r.includes("NotAllowedError"))throw new L({code:v.PLAY_NOT_ALLOWED,message:r})}})}stop(){this.unbindEvents(),this._isElementPlayingFired=!1,this.element&&(this.container&&this.container.removeChild(this.element),this.element.srcObject=null,this.element=null),this.handleStopped(m.ENDED),this._interval>0&&me.clearTask(this._interval)}pause(){var e;this.isPlaying&&((e=this.element)==null||e.pause())}resume(){return this.isPlaying?Promise.resolve():er?this.replay():this.play().catch(()=>{})}setMuted(e){this.element&&(this.element.muted=e),this.muted=e}setRect(e,r){this.element&&(this.element.style.width=`${e}px`,this.element.style.height=`${r}px`)}replay(){return this.stop(),this.play().catch(()=>{})}bindElementEvents(){if(this.element){let e=this.handleElementEvent.bind(this);ot(this.element,this.element).add(m.PLAYING,e).add(m.ENDED,e).add(m.PAUSE,e).add(m.ERROR,e).add(m.LOADEDDATA,e)}}bindTrackEvents(){if(this.track){let e=this.handleTrackEvent.bind(this);ar==null||ar.create(this.track,this.track).add(m.ENDED,e).add(m.MUTE,e).add(m.UNMUTE,e),this.track.readyState===m.ENDED&&this.handleTrackEvent({type:m.ENDED}),this.track.muted&&this.handleTrackEvent({type:m.MUTE})}}bindAutoPlayEvent(){C.on(S.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(){this.track&&Be(this.track)}unbindEvents(){this.element&&Be(this.element),this.unbindTrackEvents(),C.off(S.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){var n;switch(e.type){case m.PLAYING:this._isElementPlayingFired=!0,this._log.info(`${this.kind} player is playing`),this.handlePlaying(m.PLAYING),this._interval&&(me.clearTask(this._interval),this._interval=-1);break;case m.ENDED:this._log.info(`${this.kind} player is ended`),this.handleStopped(m.ENDED);break;case m.PAUSE:this._log.info(`${this.kind} player is paused`),this.handlePaused(m.PAUSE);let s=this.container&&document.getElementById(this.container.id);s||this._log.warn(`${this.kind} player has been remove, element ID: ${(n=this.container)==null?void 0:n.id}`);let o=jr();this._pausedRetryCount>0&&(this.kind===m.VIDEO&&!Sa()||this.kind===m.AUDIO&&(de(o)&&o<=70||!s))&&(this._log.info(`${this.kind} player auto resume when paused`),this.resume(),this._pausedRetryCount--),It&&(this._interval=me.run(xr,()=>{this.element&&this._state==="PAUSED"&&this.resume()},{delay:3e3}));break;case m.ERROR:if(this.element&&this.element.error){let{code:a,message:c}=this.element.error;this._log.error(`${this.kind} player error observed. code: ${a} message: ${c} userAgent: ${navigator.userAgent}`),Ee.uploadEvent({log:`stat-${this.kind}-${Lt.PLAYER_ERROR}-${a}-${navigator.userAgent}`,error:this.element.error})}break;case m.LOADEDDATA:this.kind===m.VIDEO&&this.emit(Nt.LOADED_DATA);break}}handleTrackEvent(e){switch(e.type){case m.ENDED:this._log.info(`${this.kind} track is ended`),this.handleStopped(m.ENDED);break;case m.MUTE:this._log.info(`${this.kind} track is unable to provide media output`),this.handlePaused(m.MUTE);break;case m.UNMUTE:this._log.info(`${this.kind} track is able to provide media output`),this._isElementPlayingFired&&this.handlePlaying(m.UNMUTE);break}}handlePlaying(e){this.emit(Nt.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this.emit(Nt.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this.emit(Nt.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};F([je([],"PLAYING")],Ht.prototype,"handlePlaying",1),F([je("PLAYING","PAUSED",{ignoreError:!0})],Ht.prototype,"handlePaused",1),F([je([],"STOPPED")],Ht.prototype,"handleStopped",1);var bi=class extends Ht{constructor(e){super(e,m.VIDEO);p(this,"mirror");p(this,"objectFit");b(e.mirror)||(this.mirror=e.mirror),b(e.objectFit)||(this.objectFit=e.objectFit)}initializeElement(){var n;let e=document.createElement(m.VIDEO);if(this.track){let s=new MediaStream;s.addTrack(this.track),e.srcObject=s}e.muted=!0;let r=`width: 100%; height: 100%; object-fit: ${this.objectFit};background-color: black;`;this.mirror&&(r+="transform: scaleX(-1);"),e.setAttribute("id",`video_${this.id}`),e.setAttribute("style",r),e.setAttribute("autoplay","autoplay"),e.setAttribute("playsinline","playsinline"),(n=this.container)==null||n.appendChild(e),this.element=e,this.bindElementEvents()}setAttr(e){let r=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},e);r.style=Object.assign({width:"100%",height:"100%"},r.style),super.setAttr(r)}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}play(){return this.element||this.initializeElement(),super.play()}getVideoFrame(){if(!this.element)return"";let e=document.createElement("canvas");return e.width=this.element.videoWidth,e.height=this.element.videoHeight,e.getContext("2d").drawImage(this.element,0,0),e.toDataURL("image/png")}getElement(){return this.element}};var hg=_(f(),1);var og=_(f(),1);var JS=_(f(),1);var qm="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<firstChannel.length;++i){sum+=firstChannel[i]*firstChannel[i]}rms=Math.sqrt(sum/firstChannel.length);this.volume=Math.max(rms,this.volume*0.95);this.tick-=firstChannel.length;if(this.tick<0){this.tick+=(this.intervalTime/1000)*sampleRate;this.port.postMessage({volume:this.volume})}}return true}}registerProcessor('volume-meter',VolumeMeter);",Bu=!1,ga=class{constructor(t){p(this,"context_");p(this,"blob_");this.context_=t.context,this.blob_=new Blob([qm],{type:"application/javascript"}),this.addModuleToContext()}addModuleToContext(){return E(this,null,function*(){try{yield this.context_.audioWorklet.addModule(URL.createObjectURL(this.blob_)),M.info("worklet addModule success"),C.emit(S.WORKLET_LOADED_SUCCESS),Bu=!0}catch(t){M.info(`worklet addModule catch error. ${t.message}`),C.emit(S.WORKLET_LOADED_FAILED)}})}get initWorkletSuccess(){return Bu}},$u=ga;var qS=_(f(),1);typeof window!="undefined"&&(window.AudioContext=window.AudioContext||window.webkitAudioContext||window.mozAudioContext);var cr=()=>{let i=new window.AudioContext,t=()=>{i.state==="suspended"?(i.resume(),document.addEventListener("click",t)):i.state==="interrupted"?i.resume():document.removeEventListener("click",t)};return document.addEventListener("click",t),i.onstatechange=()=>{M.info(`audioSource context state: ${i.state}`),t()},i};var lt,Rs,As=0,Ia=class{constructor(t){p(this,"_volume");p(this,"_log");p(this,"_track");p(this,"_stream");p(this,"_audioCtx");p(this,"_destination");p(this,"_streamSource");p(this,"_scriptProcessorNode");p(this,"_audioWorkletNode");p(this,"_interval");let{track:e,log:r}=t;this._volume=0,this._log=r,this._track=e,lt||(lt=cr()),this._audioCtx=lt,this._destination=this._audioCtx.destination;let n=new MediaStream;n.addTrack(this._track),this._streamSource=this._audioCtx.createMediaStreamSource(n),this._audioWorkletNode=null,this._scriptProcessorNode=null,this._interval=200,C.on(S.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this),zo?(C.on(S.WORKLET_LOADED_SUCCESS,this.initAudioWorklet,this),C.on(S.WORKLET_LOADED_FAILED,this.initScriptProcessor,this),this.preload()):this.initScriptProcessor(),As+=1}preload(){Rs?Rs.initWorkletSuccess&&this.initAudioWorklet():Rs=new $u({context:lt})}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(this._audioCtx,"volume-meter"),this._audioWorkletNode.port.onmessage=t=>{this._volume=t.data.volume||0},this._streamSource.connect(this._audioWorkletNode).connect(this._destination),this.handleAudioLevelInterval({interval:this._interval})}catch(t){Ee.logFailedEvent({userId:this._log.userId,eventType:Lt.LOAD_WORKLET,error:t}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=this._audioCtx.createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=t=>{let e=t.inputBuffer.getChannelData(0),r=0;for(let n=0;n<e.length;++n)r+=e[n]*e[n];this._volume=Math.sqrt(r/e.length)||0},this._streamSource.connect(this._scriptProcessorNode),this._scriptProcessorNode.connect(this._destination)}catch(t){this._log.error(`volumeMeter init script processor error: ${t}`)}}destroy(){this._streamSource&&this._streamSource.disconnect(),this._scriptProcessorNode&&(this._scriptProcessorNode.onaudioprocess=null,this._scriptProcessorNode.disconnect()),this._audioWorkletNode&&(this._audioWorkletNode.port.postMessage({name:"stop"}),this._audioWorkletNode.port.onmessage=null,this._audioWorkletNode.disconnect()),this._audioWorkletNode=null,this._scriptProcessorNode=null,this._audioCtx=null,C.off(S.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this),C.off(S.WORKLET_LOADED_SUCCESS,this.initAudioWorklet,this),C.off(S.WORKLET_LOADED_FAILED,this.initScriptProcessor,this),As>0&&(As-=1),As===0&&(lt==null||lt.close(),lt=null,Rs=null)}resume(){lt==null||lt.resume()}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}handleAudioLevelInterval(t){var r;let{interval:e}=t;this._interval=e,(r=this._audioWorkletNode)==null||r.port.postMessage({name:"setIntervalTime",intervalTime:e})}},Hu=Ia;var Di=class extends Ht{constructor(e){super(e,m.AUDIO);p(this,"_volumeMeter");p(this,"gainedTrack");p(this,"_outputDeviceId");p(this,"_volume",1);p(this,"_loop",!1);e.gainedTrack&&(this.gainedTrack=e.gainedTrack),this._outputDeviceId=e.outputDeviceId,this.track&&this.initVolumeMeter(this.track)}setTrack(e){this.track!==e&&(this._volumeMeter&&(this._volumeMeter.destroy(),this._volumeMeter=null),e!==null&&this.initVolumeMeter(e)),super.setTrack(e)}initVolumeMeter(e){this._volumeMeter=new Hu({track:this.gainedTrack||e,log:this._log})}initializeElement(){if((Zi==="15.2"||Zi==="15.3"||Zi==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}let r=document.createElement(m.AUDIO);if(this.gainedTrack||this.track){let n=new MediaStream;n.addTrack(this.gainedTrack||this.track),r.srcObject=n}r.muted=this.muted,r.setAttribute("id",`audio_${this.id}`),r.setAttribute("autoplay","autoplay"),r.setAttribute("playsinline","playsinline"),this.element=r,this.bindElementEvents()}play(){return E(this,null,function*(){this.element||this.initializeElement(),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),!this._volumeMeter&&this.track&&this.initVolumeMeter(this.track),this.setVolume(this._volume),yield Ei(Di.prototype,this,"play").call(this)})}stop(){this._volumeMeter&&(this._volumeMeter.destroy(),this._volumeMeter=null),super.stop()}resume(){return E(this,null,function*(){yield Ei(Di.prototype,this,"resume").call(this),this._volumeMeter&&this._volumeMeter.resume()})}setSinkId(e){return E(this,null,function*(){this._outputDeviceId!==e&&(this.element&&(yield this.element.setSinkId(e)),this._outputDeviceId=e)})}setVolume(e){!this.element||(this.element.volume=e,this._volume=e)}setLoop(e){!this.element||(this.element.loop=e,this._loop=e)}getAudioLevel(){var e;return((e=this._volumeMeter)==null?void 0:e.getCalculatedVolume())||0}getInternalAudioLevel(){var e;return(e=this._volumeMeter)==null?void 0:e.getInternalAudioLevel()}};var Oi=class extends he{constructor({userId:e,sdkAppId:r,mediaType:n,room:s}){var o;super();p(this,"id",da());p(this,"userId");p(this,"isRemote");p(this,"mediaType");p(this,"room");p(this,"user");p(this,"_log");p(this,"isPlayCalled");p(this,"mediaTrack",null);p(this,"mediaStream");p(this,"container",null);p(this,"subVideoPlayerMap");p(this,"playerMuted",!1);p(this,"abortCtrl");p(this,"audioOutputDeviceId");p(this,"audioVolume");p(this,"objectFit","cover");p(this,"mirror",!1);p(this,"gain");p(this,"isScreen",!1);b(e)||(this.userId=e),this.mediaType=n,this._log=M.createLogger({id:`${this.kind[0]}t`,userId:(o=s||this.room)==null?void 0:o.userId,remoteUserId:this instanceof $e?void 0:this.userId,sdkAppId:r,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof $e}),this.initPlayer()}get log(){return this._log||M}get kind(){return this.mediaType===1?m.AUDIO:m.VIDEO}get muted(){return!!(this.mediaTrack&&!this.mediaTrack.enabled)}get strMediaType(){return this.mediaType===4?m.VIDEO:this.mediaType===2?m.SCREEN:m.AUDIO}uninstallEvents(){}play(e,r){return E(this,null,function*(){let n=Ve(e)?e[0]:e;if(this.isPlayCalled){r&&!b(r.muted)&&this.setPlayerMute(r.muted),r&&!b(r.objectFit)&&(this.objectFit=r.objectFit),this.isScreen?this.mirror=!1:r&&!b(r.mirror)&&(this.mirror=r.mirror),this.kind===m.VIDEO&&(this.player.setObjectFit(this.objectFit),this.player.setMirror(this.mirror),this.container!==n&&n&&(this.container=n,this.player.setContainer(n)),Ve(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),r)));return}if((!this.isRemote||this.kind===m.VIDEO)&&this.setPlayerMute(!0),r&&!b(r.muted)&&this.setPlayerMute(r.muted),r&&!b(r.objectFit)&&(this.objectFit=r.objectFit),this.isRemote||(this.mirror=!0),this.isScreen?this.mirror=!1:r&&!b(r.mirror)&&(this.mirror=r.mirror),this.kind===m.VIDEO&&(this.player.setObjectFit(this.objectFit),this.player.setMirror(this.mirror)),this.isPlayCalled=!0,n&&(this.container=n,this.player.setContainer(n)),C.emit(S.PLAY_TRACK_START,{track:this}),!!this.mediaTrack){this._log.info(`play with options: ${JSON.stringify(r)}`);try{yield this.player.play(),Ve(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),r))}catch(s){throw this.handleAutoPlayFailed(),this.emit("error",s),s}}})}playSubContainer(e,r){return E(this,null,function*(){if(!this.mediaTrack||this.kind===m.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((s,o)=>{var a;e.find(c=>o===c)||(s.stop(),s.setContainer(null),(a=this.subVideoPlayerMap)==null||a.delete(o))});for(let[s,o]of e.entries()){let a=this.subVideoPlayerMap.get(o);a?r&&(b(r.mirror)||a.setMirror(r.mirror),b(r.objectFit)||a.setObjectFit(r.objectFit)):this.subVideoPlayerMap.set(o,new bi({id:this.userId||this.id,track:this.mediaTrack,container:o,muted:this.playerMuted,objectFit:this.objectFit,mirror:this.mirror,log:this.log.createChild({id:`vp-sub${s+1}`})}))}let n=[...this.subVideoPlayerMap.values()];for(let s of n)yield s.play()})}initPlayer(){var e;this.log.info(`create ${this.kind}Player`),this.kind===m.AUDIO?this.player=new Di({id:this.userId||this.id,track:this.mediaTrack,gainedTrack:(e=this.gain)==null?void 0:e.audioTrack,container:this.container||null,muted:this.playerMuted,outputDeviceId:this.audioOutputDeviceId,log:this.log}):(this.player=new bi({id:this.userId||this.id,track:this.mediaTrack,container:this.container||null,muted:this.playerMuted,objectFit:this.objectFit,mirror:this.mirror,log:this.log}),this.player.on(Nt.LOADED_DATA,()=>{C.emit(S.VIDEO_LOADED_DATA,{track:this})}),this.player.on(Nt.MEDIA_TRACK_CHANGED,r=>{var n;(n=this.subVideoPlayerMap)==null||n.forEach(s=>s.setTrack(r))})),this.player.on(Nt.PLAYER_STATE_CHANGED,r=>{C.emit(S.PLAYER_STATE_CHANGED,B({track:this},r)),this.emit("player-state-changed",r)})}setAudioOutput(e){return E(this,null,function*(){var r;this.audioOutputDeviceId=e,yield(r=this.player)==null?void 0:r.setSinkId(e)})}setAudioVolume(e){var r;this.audioVolume=e,this.log.info(`setAudioVolume to ${e}`),(r=this.player)==null||r.setVolume(e)}getAudioLevel(){var e;return((e=this.player)==null?void 0:e.getAudioLevel())||0}getInternalAudioLevel(){var e;return((e=this.player)==null?void 0:e.getInternalAudioLevel())||0}stop(){!this.isPlayCalled||(this.isPlayCalled=!1,this.player&&(this.log.info(`stop ${this.kind} player`),this.player.stop(),this.player.setContainer(null)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(e=>{e.stop(),e.setContainer(null)}),this.container=null)}resume(){return E(this,null,function*(){var e;!this.isPlayCalled||(yield(e=this.player)==null?void 0:e.resume())})}close(){var e;this.log.info("close"),this.isPlayCalled&&this.stop(),!this.isRemote&&((e=this.mediaTrack)==null||e.stop(),this.mediaTrack=null,this.uninstallEvents())}setMute(e){return this.mediaTrack?(this.mediaTrack.enabled=!e,this.emit(e?"mute":"unmute",this),C.emit(e?S.TRACK_MUTED:S.TRACK_UNMUTED,{track:this}),!0):!1}setPlayerMute(e){this.playerMuted=e,this.player.setMuted(e)}setMediaStream(e){e!==this.mediaStream&&(this.mediaStream=e)}setMediaStreamTrack(e){this.mediaStream||(this.mediaStream=new MediaStream),this.mediaTrack&&this.mediaStream.removeTrack(this.mediaTrack);let r=this.mediaTrack;this.mediaTrack=e,this.mediaTrack&&(this.mediaTrack.enabled=!this.muted,this.mediaStream.addTrack(this.mediaTrack),this.isRemote||this.player.setTrack(this.mediaTrack)),this.updatePlayingState(!!e),this.emit("media-track-changed",this.mediaTrack,r)}setMediaType(e){this.mediaType=e}updatePlayingState(e){if(!(!this.isPlayCalled||e&&!this.player.isStopped||!e&&this.player.isStopped)&&this.isPlayCalled&&this.player.isStopped===e){if(this.log.info(`playing state updated, ${e?"play":"stop"} ${this.kind}`),e&&this.player.isStopped){if(this instanceof Xe&&(!this.isSubscribed||!this.hasFlag))return;this.player.play().catch(()=>this.handleAutoPlayFailed())}!e&&!this.player.isStopped&&this.player.stop()}}handleAutoPlayFailed(){if(this.room&&this.room.enableAutoPlayDialog)new Vu;else{let e=()=>{this.resume().then(()=>{document.removeEventListener("click",e,!0),document.removeEventListener("touchstart",e,!0)})};document.addEventListener("click",e,!0),document.addEventListener("touchstart",e,!0)}}};F([je([],he.INIT)],Oi.prototype,"close",1);var pI=_(f(),1);var Yg=_(f(),1);var Qm=Object.prototype.hasOwnProperty,{toString:jg}=Object.prototype;function Zm(i){if(i==null)return!0;if(typeof i=="boolean")return!1;if(typeof i=="number")return i===0;if(typeof i=="string"||typeof i=="function"||Array.isArray(i))return i.length===0;if(i instanceof Error)return i.message==="";if(ni(i))switch(Object.prototype.toString.call(i)){case"[object File]":case"[object Map]":case"[object Set]":return i.size===0;case"[object Object]":{for(let t in i)if(Qm.call(i,t))return!1;return!0}}return!1}var Ft=Zm;var Zg=_(f(),1),Gu=_(nt(),1);var Fu=i=>t=>t.deviceId===i;var cn=class{constructor(t,e="Input"){p(this,"kind");p(this,"type");p(this,"devices",[]);this.kind=t,this.type=e}update(t,e){let r=t.filter(n=>n.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);e&&(r.forEach(n=>{if(n.deviceId&&!this.devices.find(Fu(n.deviceId))){let s=`${this.kind}${this.type}Added`;M.warn(`${s}: ${JSON.stringify(n)}`),e.emit(s,n)}}),this.devices.forEach(n=>{if(n.deviceId&&!r.find(Fu(n.deviceId))){let s=`${this.kind}${this.type}Removed`;M.warn(`${s}: ${JSON.stringify(n)}`),e.emit(s,n)}})),this.devices=r}hasDevice(t){return!!this.devices.find(e=>e.deviceId===t)}},Aa=class extends Gu.EventEmitter{constructor(){super();p(this,"audioInputs",new cn(m.AUDIO));p(this,"videoInputs",new cn(m.VIDEO));p(this,"audioOutputs",new cn(m.AUDIO,"Output"));this.init(),navigator.mediaDevices&&navigator.mediaDevices.addEventListener("devicechange",this.update.bind(this))}init(){Cs().then(e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)})}update(){return E(this,null,function*(){let e=yield Cs();return this.audioInputs.update(e,this),this.videoInputs.update(e,this),this.audioOutputs.update(e,this),this})}},Se=Bn||wn?null:new Aa;function Cs(){return E(this,null,function*(){return ra()||!_s()?[]:(yield navigator.mediaDevices.enumerateDevices()).map((t,e)=>{let r={kind:t.kind,deviceId:t.deviceId,groupId:t.groupId,label:t.label||`${t.kind}_${e}`};return t.deviceId.length>0&&Ca.add(`${t.deviceId}_${t.kind}`),t.getCapabilities&&(r.getCapabilities=()=>t.getCapabilities()),r})})}function at(){return Se.update().then(i=>i.audioInputs.devices)}function ht(){return Se.update().then(i=>i.videoInputs.devices)}function dr(){return E(this,null,function*(){return Se.update().then(i=>i.audioOutputs.devices)})}var Ca=new Set;function Wu(i){if(i instanceof CanvasCaptureMediaStreamTrack||!(i instanceof MediaStreamTrack))return!1;let t=i.label.toLocaleLowerCase();if(t.includes("camera")||t.includes("webcam"))return!0;let r=`${((i==null?void 0:i.getSettings())||{}).deviceId}_${m.VIDEO_INPUT}`;return!!Ca.has(r)}function Ku(i){if(i instanceof CanvasCaptureMediaStreamTrack||!(i instanceof MediaStreamTrack))return!1;let t=i.label.toLocaleLowerCase();if(t.includes("mic")||t.includes("\u9EA6\u514B\u98CE"))return!0;let r=`${((i==null?void 0:i.getSettings())||{}).deviceId}_${m.AUDIO_INPUT}`;return!!Ca.has(r)}function ya(i,t){return E(this,null,function*(){let r=(yield at()).find(n=>n.deviceId===Qi);return(r==null?void 0:r.groupId)===i&&r.label===t})}function ju(s){return E(this,arguments,function*({newDeviceId:i,oldDeviceId:t,oldGroupId:e,oldLabel:r,kind:n}){return i!==t?!1:n===m.AUDIO&&i===Qi?yield ya(e,r):!0})}var e_=function(i){return E(this,null,function*(){let t=i_(i);M.info(`getUserMedia with constraints: ${JSON.stringify(t)}`);let e,r;t.audio&&(e=yield at(),M.info(`microphones: ${JSON.stringify(e)}`)),t.video&&(r=yield ht(),M.info(`cameras: ${JSON.stringify(r)}`));try{let n=yield navigator.mediaDevices.getUserMedia(t);return aa&&n.getTracks().forEach(s=>{M.info(`${s.kind} settings: ${JSON.stringify((s==null?void 0:s.getSettings())||{})}\r
91
- capabilities: ${JSON.stringify(s.getCapabilities())}`)}),n}catch(n){if(n.name==="NotFoundError"){if(r&&r.length===0)throw new L({code:v.DEVICE_NOT_FOUND,message:$({key:w.CAMERA_NOT_FOUND})});if(e&&e.length===0)throw new L({code:v.DEVICE_NOT_FOUND,message:$({key:w.MICROPHONE_NOT_FOUND})})}throw new L({code:v.INITIALIZE_FAILED,name:n.name,message:n.message,constraint:n.constraint})}})},t_=vt({retryFunction:e_,settings:{retries:3,timeout:500},onError:(i,t,e,r)=>{i.name==="NotReadableError"?(r[0].video&&(r[0].maxResolution=!1,r[0].frameRate&&(r[0].frameRate=r[0].frameRate>10?10:5)),t()):e(i)},onRetrying:i=>{M.warn(`getUserMedia NotReadableError observed, retrying [${i}/3]`)}});function i_(i){return{audio:r_(i),video:n_(i)}}function r_(i){if(!i.audio)return!1;let t={};return Ft(i.microphoneId)||(t.deviceId=i.useExact?{exact:i.microphoneId}:i.microphoneId),de(i.channelCount)&&i.channelCount>1&&(t.channelCount=i.channelCount),be(i.echoCancellation)&&!i.echoCancellation&&(t.echoCancellation=!1),be(i.noiseSuppression)&&!i.noiseSuppression&&(t.noiseSuppression=!1),be(i.autoGainControl)&&!i.autoGainControl&&(t.autoGainControl=!1),Ft(t)?!0:t}function n_(i){if(!i.video)return!1;let{maxResolution:t=!0}=i,e={};return i.cameraId?e.deviceId=i.useExact?{exact:i.cameraId}:i.cameraId:i.facingMode&&(e.facingMode=i.facingMode),i.width&&(e.width={ideal:i.width},t&&(e.width.max=i.width)),i.height&&(e.height={ideal:i.height},t&&(e.height.max=i.height)),pe&&Ut&&i.width&&i.height&&i.width*i.height<352*288&&(e.width=i.width,e.height=i.height),i.frameRate&&(e.frameRate=i.frameRate),Ft(e)?!0:e}var Ju=t_;var _I=_(f(),1);function ys(i){return ce((t,e)=>function(...r){return E(this,null,function*(){return yield i.apply(this,r),t.apply(this,r)})})}function vs(i){return ce((t,e)=>function(...r){return E(this,null,function*(){return i.call(this,t.apply(this,r))})})}function ce(i){return function(t,e,r){return r.value=i(r.value,e),r}}var $e=class extends Oi{constructor(e){super({mediaType:e});p(this,"isRemote",!1);p(this,"deviceId");p(this,"groupId","");p(this,"label","");p(this,"_isRecapturing",!1);p(this,"_lastRecaptureTime",0);p(this,"_onMuteTimeoutId",-1);this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this)}installTrackEvent(e){e.addEventListener(m.MUTE,this.onTrackMuted),e.addEventListener(m.UNMUTE,this.onTrackUnmuted),e.addEventListener(m.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===m.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){e.removeEventListener(m.MUTE,this.onTrackMuted),e.removeEventListener(m.UNMUTE,this.onTrackUnmuted),e.removeEventListener(m.ENDED,this.onTrackEnded)}setStateToCapture(){}capture(e){return E(this,null,function*(){try{C.emit(S.LOCAL_TRACK_CAPTURE_START,{track:this});let r;e.customSource?(r=new MediaStream,r.addTrack(e.customSource)):r=yield Ju(e);let n=r.getTracks()[0];return this.setMediaStream(r),this.setMediaStreamTrack(n),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),C.emit(S.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this}),r}catch(r){throw C.emit(S.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:r}),this.log.error(`getUserMedia error observed ${r}`),r}})}setMediaStreamTrack(e){this.state===he.INIT&&this.setStateToCapture(),this.mediaTrack&&this.uninstallTrackEvent(this.mediaTrack),super.setMediaStreamTrack(e),e&&this.installTrackEvent(e)}setPublishStarting(e){this.room=e}setPublishStarted(){}setPublishStopped(e,r){}publish(e){this.room=e,this.userId=e.userId,this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),C.emit(S.LOCAL_TRACK_PUBLISHED,{track:this}),this.setPublishStarted()}unpublish(){this.room=void 0,this.mediaType===2&&(this.mediaType=4),C.emit(S.LOCAL_TRACK_UNPUBLISHED,{track:this}),this.setPublishStopped("api-call")}get isPublishing(){return this.state==="publish"}updateDeviceIdInUse(){return E(this,null,function*(){if(this.mediaTrack&&wt){let{deviceId:e,groupId:r}=this.mediaTrack.getSettings(),{label:n}=this.mediaTrack;(yield ju({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=n,r&&(this.groupId=r),Cs().then(o=>{let a=o.find(c=>c.deviceId===e);a&&this.emit("2",a)}))}})}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(e=!1){return!(!this.deviceId||!this.mediaTrack||this.kind===m.AUDIO&&!Ku(this.mediaTrack)||this.kind===m.VIDEO&&!Wu(this.mediaTrack)||this._isRecapturing||e&&Ut&&Vt)}onTrackMuted(){if(!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<kr){setTimeout(()=>this.onTrackMuted(),kr);return}this._onMuteTimeoutId=setTimeout(()=>E(this,null,function*(){var e;((e=this.mediaTrack)==null?void 0:e.muted)&&document.visibilityState==="visible"&&this.recapture(yield this.getRecoverCaptureDeviceId())}),5e3)}}onTrackUnmuted(){this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return E(this,null,function*(){if(!!this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<kr){setTimeout(()=>this.onTrackEnded(),kr);return}this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e){return E(this,null,function*(){var s;if(this._isRecapturing||!this.mediaTrack)return;let r;return this.log.warn("recapture trying"),(s=this.mediaTrack)==null||s.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now(),(this.kind==="audio"?yield at():yield ht()).find(o=>o.deviceId===e)&&(r=e),this.capture({deviceId:r,useExact:!0}).then(()=>{var o;return(o=this.room)==null?void 0:o.replaceTrack(this)}).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId})}).catch(o=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${o.message}`),this.emit("5",o)})})}getRecoverCaptureDeviceId(){return E(this,null,function*(){let{deviceId:e}=this;if(e){let r=(dn.get(e)||0)+1;if(dn.set(e,r),r>=3){let n=this.kind==="video"?(yield ht()).find(s=>!dn.has(s.deviceId)):(yield at()).find(s=>!dn.has(s.deviceId));n&&(this.log.warn(`${e} capture fail ${r} times, change new ${n.deviceId}`),e=n.deviceId)}}return e})}};F([je(he.INIT,"capture")],$e.prototype,"setStateToCapture",1),F([je("capture","publish_starting",{success(){this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"})}})],$e.prototype,"setPublishStarting",1),F([je("publish_starting","publish",{success(){this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"})}})],$e.prototype,"setPublishStarted",1),F([ce(i=>function(t,e){let r=this.state.oldState||this.state;i.call(this,t,e),r!=="capture"&&this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:this.state.oldState==="publish_starting"?"starting":"started",reason:t,error:e})}),je(["publish","publish_starting"],"capture",{ignoreError:!0})],$e.prototype,"setPublishStopped",1);var dn=new Map;C.on(S.SWITCH_DEVICE_SUCCESS,i=>{i.track.deviceId&&dn.delete(i.track.deviceId)});var JI=_(f(),1);var Gt=class extends $e{constructor(){super(1);p(this,"mediaType",1);p(this,"volume",0);p(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40});p(this,"playerMuted",!0)}getAudioLevel(){return this.volume||super.getAudioLevel()}capture({deviceId:e,useExact:r=!1}={}){return super.capture({video:!1,audio:!0,microphoneId:e,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExact:r})}switchDevice(e){return E(this,null,function*(){if(!(!this.mediaStream||!this.mediaTrack)){if(this.deviceId===e)if(e===Qi){if(yield ya(this.groupId,this.label))return}else return;try{this.log.info(`switchDevice audio to: ${e}`),this.mediaTrack&&this.mediaTrack.stop(),yield this.capture({deviceId:e,useExact:!0}),this.room&&(yield this.room.replaceTrack(this)),C.emit(S.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(r){throw this.log.error(`switch microphone failed ${r}`),this.deviceId&&this.recapture(this.deviceId),r}}})}listenDeviceChange(){Se&&!Se.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&Se.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return E(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current microphone is lost: ${JSON.stringify(e)}`);let r=yield at();r[0]?this.recapture(r[0].deviceId):Se.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){return E(this,null,function*(){this.log.warn(`microphone added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)})}close(){Se.off("audioInputAdded",this.handleMicrophoneAdded,this),Se.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}};var oR=_(f(),1);var mt=class extends $e{constructor(){super(4);p(this,"mediaType",4);p(this,"profile",{width:640,height:480,frameRate:15,bitrate:900});p(this,"states",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0});p(this,"small");p(this,"facingMode");p(this,"_canvas");p(this,"_canvasInterval");p(this,"canvasTrack")}capture({deviceId:e,facingMode:r,useExact:n=!1,customSource:s}={}){return super.capture({audio:!1,video:!0,facingMode:r||this.facingMode,cameraId:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExact:n,customSource:s})}genCanvasTrack(){if(this.canvasTrack||!this.mediaTrack)return;this.log.info("gen canvas track");let{width:e,height:r,frameRate:n}=this.mediaTrack.getSettings();this._canvas=document.createElement("canvas");let s=this._canvas.getContext("2d");e&&r&&(this._canvas.width=e,this._canvas.height=r),this._canvasInterval=me.run(ii,()=>{if(!this._canvas)return;if(this.mediaTrack){let c=this.mediaTrack.getSettings();(c.width!==this._canvas.width||c.height!==this._canvas.height)&&(this._canvas.width=c.width,this._canvas.height=c.height)}let a=this.player.getElement();a&&(s==null||s.drawImage(a,0,0,this._canvas.width,this._canvas.height))},{fps:Math.max(15,n||0)});let o=this._canvas.captureStream();this.canvasTrack=o.getVideoTracks()[0]}destoryCanvasTrack(){this._canvasInterval&&(me.clearTask(this._canvasInterval),this._canvasInterval=void 0,this._canvas=void 0,this.canvasTrack=void 0)}setPublishStarting(e){super.setPublishStarting(e),this.isNeedToResetVideoProfile(this.profile)&&this.setProfile(this.profile)}setMediaStreamTrack(e){super.setMediaStreamTrack(e),this.isNeedToResetVideoProfile(this.profile)&&this.setProfile(this.profile)}setProfile(e){var n;if(!e)return;let r=e.bitrate&&e.bitrate!==this.profile.bitrate;return this.isNeedToResetVideoProfile(e)&&(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),e.width=1920,e.height=1080),super.setProfile(e),(n=this.mediaTrack)==null?void 0:n.applyConstraints({width:e.width,height:e.height,frameRate:e.frameRate}).then(()=>{if(r&&this.room&&this.room.setBandWidth)return this.room.setBandWidth({bandwidth:e.bitrate,type:m.VIDEO,videoType:m.BIG})})}isNeedToResetVideoProfile(e){return!!(this.room&&this.room.scheduleResult&&!((this.room.scheduleResult.trtcAutoConf||{})["2k4k"]===1)&&!this.isScreen&&e.height*e.width>=2560*1440)}switchDevice(e){return E(this,null,function*(){try{if(!this.mediaStream||this.deviceId===e||this.facingMode===e)return;(e===m.FACING_MODE_USER||e===m.FACING_MODE_ENVIRONMENT)&&(this.facingMode=e,e=void 0),this.mediaTrack&&this.mediaTrack.stop(),yield this.capture({deviceId:e,useExact:!0}),this.room&&(yield this.room.replaceTrack(this)),C.emit(S.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(r){throw this.log.error(`switch camera failed ${r}`),this.deviceId&&this.recapture(this.deviceId),r}})}listenDeviceChange(){Se&&!Se.listeners("audioInputRemoved").includes(this.handleCameraRemoved)&&Se.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return E(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current camera is lost: ${JSON.stringify(e)}`);let r=yield ht();r[0]?this.recapture(r[0].deviceId):Se.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return E(this,null,function*(){this.log.warn(`camera added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)})}close(){Se.off("videoInputAdded",this.handleCameraAdded,this),Se.off("videoInputRemoved",this.handleCameraRemoved,this),this.destoryCanvasTrack(),super.close()}};var SR=_(f(),1);var pR=_(f(),1);var o_=function(i){return E(this,null,function*(){let t=null,e=c_(i);M.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let r=yield navigator.mediaDevices.getDisplayMedia(e);if(i.systemAudio&&r.getAudioTracks().length===0&&(Jr&&Yr<74||Vt||pe)&&M.warn("Your browser not support capture system audio"),i.frameRate&&r.getVideoTracks()[0]&&r.getVideoTracks()[0].applyConstraints({frameRate:{min:i.frameRate,ideal:i.frameRate}}).catch(n=>{M.warn(`screen applyConstraints failed: ${n}`)}),i.audio){let n=a_(i);M.info(`getUserMedia with constraints: ${JSON.stringify(n)}`),t=yield navigator.mediaDevices.getUserMedia(n),r.addTrack(t.getAudioTracks()[0])}return r})};function a_(i){let t={echoCancellation:i.echoCancellation,autoGainControl:i.autoGainControl,noiseSuppression:i.noiseSuppression,sampleRate:i.sampleRate,channelCount:i.channelCount};return b(i.microphoneId)||(t.deviceId=i.microphoneId),{audio:t,video:!1}}function c_(i){let t={systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:Vt?{max:i.width}:{ideal:i.width,max:i.width},height:Vt?{max:i.height}:{ideal:i.height,max:i.height},frameRate:i.frameRate,displaySurface:"monitor"};if(t.video=e,i.systemAudio){let{echoCancellation:r=!0,noiseSuppression:n=!1,autoGainControl:s=!1}=i;t.audio={echoCancellation:r,noiseSuppression:n,autoGainControl:s,sampleRate:48e3}}return t}var Xu=o_;var bt=class extends mt{constructor(){super();p(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600});p(this,"objectFit","contain");p(this,"isScreen",!0);this._log.id=`s-${this._log.id}`}capture(){return E(this,arguments,function*({systemAudio:e=!1,autoGainControl:r,echoCancellation:n,noiseSuppression:s,audioTrack:o,videoTrack:a}={}){try{let c;return a||o?(c=new MediaStream,a&&c.addTrack(a),o&&c.addTrack(o)):c=yield Xu({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:r,echoCancellation:n,noiseSuppression:s}),this.setMediaStream(c),this.setMediaStreamTrack(c.getVideoTracks()[0]),c}catch(c){throw this.log.error(`getDisplayMedia error observed ${c}`),c instanceof L?c:new L({code:v.INITIALIZE_FAILED,name:c.name,message:c.message})}})}switchDevice(e){return E(this,null,function*(){throw new Error("Method not implemented.")})}};var AR=_(f(),1);var Pi=class extends Gt{constructor(){super(),this._log.id=`s-${this._log.id}`}setScreenAudioTrack(t,e){this.setMediaStream(e),this.setMediaStreamTrack(t)}};var VR=_(f(),1);var OR=_(f(),1);var un=class extends $e{constructor(e){super(1);p(this,"musicId");p(this,"mediaType",1);p(this,"volume",0);p(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40});p(this,"playerMuted",!1);p(this,"_audioContext");p(this,"_destination");p(this,"_source",null);this.initAudioContext(),this._destination=this._audioContext.createMediaStreamDestination(),this._destination.channelCount=1,this.setPlayerMute(!1),this.player.initializeElement(),this.player.setUrl(e.url),be(e.loop)&&this.player.setLoop(e.loop),de(e.volume)&&this.player.setVolume(e.volume),e.id&&(this.musicId=e.id),this._source=this._audioContext.createMediaElementSource(this.player.getElement()),this._source.connect(this._destination),this.setMediaStream(this._destination.stream)}initAudioContext(){this._audioContext=cr(),this._audioContext.state!=="running"&&this._log.warn(`local music ${this.musicId} context state: ${this._audioContext.state}`)}destroy(){var e,r;(e=this._source)==null||e.disconnect(),(r=this._destination)==null||r.disconnect(),this.player.stop(),this._audioContext.close().then(()=>{this._source=null,this._destination=null,this._audioContext=null})}getStream(){var e;return((e=this._destination)==null?void 0:e.stream)||null}setPosition(e){if(e<0&&e>this.duration()){M.warn("Time beyond song duration.");return}this.player&&this.player.getElement()&&(this.player.getElement().currentTime=e)}getPosition(){var e;if(this.player)return((e=this.player.getElement())==null?void 0:e.currentTime)||0}setVolume(e){if(e>1&&e<0){this.log.warn("volume is out of range");return}this.player.setVolume(e)}getVolume(){let e=this.player.getElement();return(e==null?void 0:e.volume)||0}setPlayBackRate(e){if(e>8&&e<0){this.log.warn("rate is out of range");return}let r=this.player.getElement();r&&(r.playbackRate=e)}getPlayBackRate(){let e=this.player.getElement();return(e==null?void 0:e.playbackRate)||0}duration(){let e=this.player.getElement();return(e==null?void 0:e.duration)||0}loop(e){let r=this.player.getElement();return r&&be(e)&&(r.loop=e),(r==null?void 0:r.loop)||!1}setOperation(e){e==="pause"&&this.player.pause(),e==="resume"&&this.player.resume(),e==="stop"&&this.player.stop()}listenDeviceChange(){}};var Ns=class{constructor({room:t}){p(this,"audioContext",null);p(this,"_destination",null);p(this,"_localAudioTrack",null);p(this,"_localScreenAudioTrack",null);p(this,"_localMediaStreamAudioTrack",null);p(this,"_audioTrackStreamSource",null);p(this,"_screenAudioTrackStreamSource",null);p(this,"_mixedMusicSet",new Set);p(this,"hasMusic",!1);p(this,"mixedMusicMap",new Map);p(this,"cacheMusicMap",new Map);p(this,"_log");p(this,"_originTrack",null);this._log=M.createLogger({id:"am",userId:t.userId,sdkAppId:t.sdkAppId}),this.initAudioContext()}get hasScreenAudioTrack(){return this._localScreenAudioTrack!==null}get hasAudioTrack(){return this._localAudioTrack!==null}get isMixed(){return(this.hasMusic?1:0)+(this._localAudioTrack?1:0)+(this._localScreenAudioTrack?1:0)>=1}get mediaStreamTrack(){return this._destination.stream.getAudioTracks()[0]}addMusicSource(t){return E(this,null,function*(){this._log.info(`add music source, id: ${t.id} url: ${t.url}`),this.initAudioContext();let{id:e,url:r,loop:n,volume:s}=t;if(this.mixedMusicMap.has(e))return;let o;this.cacheMusicMap.has(e)?o=this.cacheMusicMap.get(e).localMusicTrack:o=new un(t);let{stream:a}=o._destination,c=document.createElement("audio");c.srcObject=a,o.play(),yield c.play(),this._log.info(`start mix audio ${e} success.`);let d=this.audioContext.createMediaStreamSource(a),u=this.audioContext.createGain();return d.connect(u),u.connect(this._destination),this._mixedMusicSet.add(e),this.mixedMusicMap.set(e,{localMusicTrack:o,streamSource:d,gainNode:u,audioPlayer:c}),this.cacheMusicMap.set(e,{localMusicTrack:o}),this.hasMusic=!0,o})}updateMusicSource(t){return E(this,null,function*(){let{id:e,volume:r,loop:n,operation:s}=t;if(this._log.info(`update music source, id: ${t.id} operation: ${s}`),this.mixedMusicMap.has(e)){let{localMusicTrack:o}=this.mixedMusicMap.get(e);b(r)||o.setVolume(r),b(n)||o.loop(n),b(s)||o.setOperation(s)}})}addAudioTrack(t){return E(this,null,function*(){var r;if(this._log.info(`start add audioTrack, userId: ${t.userId}`),this.initAudioContext(),!(t!=null&&t.mediaStream))return;if(this._localMediaStreamAudioTrack===t.mediaTrack){this._log.info("addAudioTrack duplicate.");return}let e=yield(r=t.mediaTrack)==null?void 0:r.getSettings();this._destination.channelCount=(e==null?void 0:e.channelCount)||1,this._localAudioTrack=t,this._localMediaStreamAudioTrack=t.mediaTrack,this._audioTrackStreamSource=this.audioContext.createMediaStreamSource(t.mediaStream),this._audioTrackStreamSource.connect(this._destination)})}removeAudioTrack(t){var e,r,n,s;this._localAudioTrack===t&&(this._log.info(`start remove audioTrack, userId: ${t.userId}`),(e=this._audioTrackStreamSource)==null||e.disconnect(),(r=this._localMediaStreamAudioTrack)==null||r.stop(),this._localMediaStreamAudioTrack=null,(n=this._localAudioTrack)==null||n.stop(),this._localAudioTrack=null),this._localScreenAudioTrack===t&&(this._log.info(`start remove screenTrack, userId: ${t.userId}`),(s=this._screenAudioTrackStreamSource)==null||s.disconnect(),this._localScreenAudioTrack.stop(),this._localScreenAudioTrack=null)}addScreenAudioTrack(t){this._log.info(`start add screenAudioTrack, userId: ${t.userId}`),this.initAudioContext(),!!(t!=null&&t.mediaStream)&&this._localScreenAudioTrack!==t&&(this._localScreenAudioTrack=t,this._screenAudioTrackStreamSource=this.audioContext.createMediaStreamSource(t.mediaStream),this._screenAudioTrackStreamSource.connect(this._destination))}removeAudioTrackSource(t){var e,r;this._log.info(`remove audio track source, type: ${t}`),t==="main"&&((e=this._audioTrackStreamSource)==null||e.disconnect(),this._audioTrackStreamSource=null,this._localAudioTrack=null),t==="screen"&&((r=this._screenAudioTrackStreamSource)==null||r.disconnect(),this._screenAudioTrackStreamSource=null,this._localScreenAudioTrack=null)}removeMusicSource({id:t}){if(this.mixedMusicMap.has(t)){this._log.info(`start remove music source, music id: ${t}`);let{localMusicTrack:e,streamSource:r,gainNode:n,audioPlayer:s}=this.mixedMusicMap.get(t);r.disconnect(),n.disconnect(),s.pause(),s.srcObject=null,e.stop(),this.mixedMusicMap.delete(t),this._mixedMusicSet.delete(t),this._mixedMusicSet.size===0&&(this.hasMusic=!1)}t==="*"&&this.destroyAllMusic()}destroyAllMusic(){this._log.info("destroy all music source."),this._mixedMusicSet.forEach(t=>{this.removeMusicSource({id:t})})}destroyAllCache(){this._log.info("destroy all music cache."),this.cacheMusicMap.forEach(t=>{t.localMusicTrack.stop()})}initAudioContext(){this.audioContext||(this.audioContext=cr(),this.audioContext.state!=="running"&&this._log.warn(`context state: ${this.audioContext.state}`),this._destination=this.audioContext.createMediaStreamDestination(),this._destination.channelCount=1)}initDenoiser(s){return E(this,arguments,function*({assetsPath:t,sdkAppId:e,userId:r,userSig:n}){})}enableDenoiser(t){return E(this,null,function*(){})}disableDenoiser(){return E(this,null,function*(){})}destroy(){this.removeAudioTrackSource("main"),this.removeAudioTrackSource("aux"),this.audioContext.close(),this.destroyAllMusic(),this.destroyAllCache()}};var rA=_(f(),1);var XR=_(f(),1);var va=class extends Oi{constructor(e,r,n){super({userId:r.userId,sdkAppId:e.sdkAppId,mediaType:n,room:e});this.room=e;this.user=r;p(this,"userId");p(this,"tinyId");p(this,"isRemote",!0);this.tinyId=r.tinyId,this.userId=r.userId}play(e,r){return this.hasFlag?super.play(e,r):(this.isPlayCalled=!0,this.container=e,e&&this.player.setContainer(e),Promise.resolve())}setMute(e){return this.hasFlag&&super.setMute(e)}setMediaStreamTrack(e){super.setMediaStreamTrack(e),this.mediaTrack&&this.hasFlag&&this.isSubscribed&&this.player.setTrack(this.mediaTrack)}get isSubscribed(){return this.state===va.STATE_SUBSCRIBE}get streamType(){return(this.mediaType&2)===0?"main":"auxiliary"}subscribe(e=!0){this.mediaTrack&&this.hasFlag&&this.player.setTrack(this.mediaTrack),e&&C.emit(S.REMOTE_TRACK_SUBSCRIBED,{track:this})}unsubscribe(e=!0){this.player.setTrack(null),e&&C.emit(S.REMOTE_TRACK_UNSUBSCRIBED,{track:this}),this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}onFlagChanged(){this.updatePlayingState(this.hasFlag),this.mediaTrack&&this.hasFlag&&this.player.setTrack(this.mediaTrack)}},Xe=va;p(Xe,"STATE_SUBSCRIBE","subscribe"),F([je(he.INIT,Xe.STATE_SUBSCRIBE,{success(){this.updatePlayingState(!0)}})],Xe.prototype,"subscribe",1),F([je(Xe.STATE_SUBSCRIBE,he.INIT,{success(){this.updatePlayingState(!1)}})],Xe.prototype,"unsubscribe",1);var ur=class extends Xe{constructor(e,r){super(e,r,1);p(this,"volume",0);p(this,"mediaType",1);p(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0})}getAudioLevel(){return this.volume||super.getAudioLevel()}get hasFlag(){return this.user.muteState.hasAudio&&!this.user.muteState.audioMuted}isFlagChanged(e){let r=e.hasAudio&&!e.audioMuted;return this.hasFlag||(this.volume=0),this.hasFlag!==r}};var uA=_(f(),1);var Mi=class extends Xe{constructor(e,r,n=4){super(e,r,n);p(this,"mediaType",4);p(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0})}changeType(e){this.room.changeType(e,this.user)}get hasFlag(){return this.user.muteState.hasVideo&&!this.user.muteState.videoMuted}isFlagChanged(e){let r=e.hasVideo&&!e.videoMuted;return this.hasFlag!==r}},lr=class extends Mi{constructor(e,r){super(e,r,2);p(this,"mediaType",2);p(this,"objectFit","contain")}get hasFlag(){return this.user.muteState.hasAuxiliary}isFlagChanged(e){let r=e.hasAuxiliary;return this.hasFlag!==r}};var MC=_(f(),1);var _C=_(f());var hA=_(f());function ve(...i){}var d_=i=>i();function ba(){this.dispose()}var u_=()=>typeof __FASTRX_DEVTOOLS__!="undefined",l_=1,Wt=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(t){let e=new Na(t,this,this.streamId++);return _t.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},ln=class{constructor(){this.defers=new Set,this.disposed=!1}next(t){}complete(){this.dispose()}error(t){this.dispose()}get bindDispose(){return()=>this.dispose()}dispose(){this.disposed=!0,this.complete=ve,this.error=ve,this.next=ve,this.dispose=ve,this.subscribe=ve,this.doDefer()}subscribe(t){return t instanceof Wt?t.subscribe(this):t(this),this}get bindSubscribe(){return t=>this.subscribe(t)}doDefer(){this.defers.forEach(d_),this.defers.clear()}defer(t){this.defers.add(t)}removeDefer(t){this.defers.delete(t)}reset(){this.disposed=!1,delete this.complete,delete this.next,delete this.dispose,delete this.next,delete this.subscribe}resetNext(){delete this.next}resetComplete(){delete this.complete}resetError(){delete this.error}},z=class extends ln{constructor(t){super(),this.sink=t,t.defer(this.bindDispose)}next(t){this.sink.next(t)}complete(){this.sink.complete()}error(t){this.sink.error(t)}};function zu(i,...t){return t.reduce((e,r)=>r(e),i)}function Kt(i,t,e){if(u_()){let r=Object.defineProperties(Object.setPrototypeOf(i,Wt.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:t,writable:!0,configurable:!0},args:{value:e,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});_t.create(r);for(let n=0;n<e.length;n++){let s=e[n];typeof s=="function"&&s instanceof Wt&&_t.addSource(r,s)}return r}return i}function ee(i,t){return function(...e){return r=>{if(r instanceof Wt){let n=Kt(s=>{let o=new i(s,...e);o.sourceId=n.id,o.subscribe(r)},t,arguments);return n.source=r,_t.pipe(n),n}else return n=>r(new i(n,...e))}}}function li(i,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:i,payload:t}})}var Na=class extends z{constructor(t,e,r){super(t),this.source=e,this.id=r,this.sourceId=t.sourceId,this.defer(()=>{_t.defer(this.source,this.id)})}next(t){_t.next(this.source,this.id,t),this.sink.next(t)}complete(){_t.complete(this.source,this.id),this.sink.complete()}error(t){_t.complete(this.source,this.id,t),this.sink.error(t)}},_t={addSource(i,t){li("addSource",{id:i.id,name:i.toString(),source:{id:t.id,name:t.toString()}})},next(i,t,e){li("next",{id:i.id,streamId:t,data:e&&e.toString()})},subscribe({id:i,end:t},e){li("subscribe",{id:i,end:t,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(i,t,e){li("complete",{id:i.id,streamId:t,err:e?e.toString():null})},defer(i,t){li("defer",{id:i.id,streamId:t})},pipe(i){li("pipe",{name:i.toString(),id:i.id,source:{id:i.source.id,name:i.source.toString()}})},update(i){li("update",{id:i.id,name:i.toString()})},create(i){i.id||(i.id=l_++),li("create",{name:i.toString(),id:i.id})}},bs=class extends Error{constructor(t){super(`timeout after ${t}ms`),this.timeout=t}};var AA=_(f());var SA=_(f());var Da=class extends ln{constructor(t){super(),this.source=t,this.sinks=new Set}add(t){t.defer(()=>this.remove(t)),this.sinks.add(t).size===1&&(this.reset(),this.subscribe(this.source))}remove(t){this.sinks.delete(t),this.sinks.size===0&&this.dispose()}next(t){this.sinks.forEach(e=>e.next(t))}complete(){this.sinks.forEach(t=>t.complete()),this.sinks.clear()}error(t){this.sinks.forEach(e=>e.error(t)),this.sinks.clear()}};function Ds(){return i=>{let t=new Da(i);if(i instanceof Wt){let e=Kt(r=>{t.add(r)},"share",arguments);return t.sourceId=e.id,e.source=i,_t.pipe(e),e}return Kt(t.add.bind(t),"share",arguments)}}function p_(...i){return Kt(t=>{let e=i.length,r=e,n=e,s=new Array(e),o=()=>{--n===0&&t.complete()},a=(c,d)=>{let u=new z(t);u.next=l=>{--r===0?(u.next=h=>{s[d]=h,t.next(s)},u.next(l)):s[d]=l},u.complete=o,u.subscribe(c)};i.forEach(a)},"combineLatest",arguments)}var Oa=class extends z{constructor(t,...e){super(t);let r=new z(this.sink);r.next=n=>this.buffer=n,r.complete=ve,r.subscribe(p_(...e))}next(t){this.buffer&&this.sink.next([t,...this.buffer])}},_A=ee(Oa,"withLatestFrom"),Pa=class extends z{constructor(t,e,r){super(t),this.bufferSize=e,this.startBufferEvery=r,this.buffer=[],this.count=0,this.startBufferEvery&&(this.buffers=[[]])}next(t){this.startBufferEvery?(this.count++===this.startBufferEvery&&(this.buffers.push([]),this.count=1),this.buffers.forEach(e=>{e.push(t)}),this.buffers[0].length===this.bufferSize&&this.sink.next(this.buffers.shift())):(this.buffer.push(t),this.buffer.length===this.bufferSize&&(this.sink.next(this.buffer),this.buffer=[]))}complete(){this.buffer.length?this.sink.next(this.buffer):this.buffers.length&&this.buffers.forEach(t=>this.sink.next(t)),super.complete()}},fA=ee(Pa,"bufferCount"),Ma=class extends z{constructor(t,e){super(t),this.buffer=[];let r=new z(t);r.next=n=>{t.next(this.buffer),this.buffer=[]},r.complete=ve,r.subscribe(e)}next(t){this.buffer.push(t)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},EA=ee(Ma,"buffer");function La(i){let t=arguments,e=Ds()(Kt(r=>{e.next=n=>r.next(n),e.complete=()=>r.complete(),e.error=n=>r.error(n),i&&r.subscribe(i)},"subject",t));return e.next=ve,e.complete=ve,e.error=ve,e}function qu(i){return Kt(t=>{let e=0,r=setInterval(()=>t.next(e++),i);return t.defer(()=>{clearInterval(r)}),"interval"},"interval",arguments)}var GA=_(f());var vA=_(f());var ka=class extends z{constructor(t,e,r){super(t),this.f=e;let n=()=>{this.sink.next(this.acc),this.sink.complete()};typeof r=="undefined"?this.next=s=>{this.acc=s,this.complete=n,this.resetNext()}:(this.acc=r,this.complete=n)}next(t){this.acc=this.f(this.acc,t)}},h_=ee(ka,"reduce");var xa=class extends z{constructor(t,e,r){super(t),this.filter=e,this.thisArg=r}next(t){this.filter.call(this.thisArg,t)&&this.sink.next(t)}},m_=ee(xa,"filter"),Ua=class extends z{next(t){}},PA=ee(Ua,"ignoreElements"),Va=class extends z{constructor(t,e){super(t),this.count=e}next(t){this.sink.next(t),--this.count===0&&this.complete()}},__=ee(Va,"take"),wa=class extends z{constructor(t,e){super(t);let r=new z(t);r.next=()=>t.complete(),r.complete=ba,r.subscribe(e)}},MA=ee(wa,"takeUntil"),Ba=class extends z{constructor(t,e){super(t),this.f=e}next(t){this.f(t)?this.sink.next(t):this.complete()}},f_=ee(Ba,"takeWhile");var $a=class extends z{constructor(t,e){super(t),this.count=e}next(t){--this.count===0&&(this.next=super.next)}},LA=ee($a,"skip"),Ha=class extends z{constructor(t,e){super(t),t.next=ve;let r=new z(t);r.next=()=>{r.dispose(),t.resetNext()},r.complete=ba,r.subscribe(e)}},kA=ee(Ha,"skipUntil"),Fa=class extends z{constructor(t,e){super(t),this.f=e}next(t){this.f(t)||(this.next=super.next,this.next(t))}},E_=ee(Fa,"skipWhile"),T_={leading:!0,trailing:!1},Ga=class extends z{constructor(t,e,r){super(t),this.durationSelector=e,this.trailing=r}cacheValue(t){this.last=t,this.disposed&&this.throttle(t)}send(t){this.sink.next(t),this.throttle(t)}throttle(t){this.reset(),this.subscribe(this.durationSelector(t))}next(){this.complete()}complete(){this.dispose(),this.trailing&&this.send(this.last)}},Wa=class extends z{constructor(t,e,r=T_){super(t),this.durationSelector=e,this.config=r,this._throttle=new Ga(this.sink,this.durationSelector,this.config.trailing),this._throttle.dispose()}next(t){this._throttle.disposed&&this.config.leading?this._throttle.send(t):this._throttle.cacheValue(t)}complete(){this._throttle.throttle=ve,this._throttle.complete(),super.complete()}},xA=ee(Wa,"throttle");var Ka=class extends z{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},ja=class extends z{constructor(t,e){super(t),this.durationSelector=e,this._debounce=new Ka(this.sink),this._debounce.dispose()}next(t){this._debounce.dispose(),this._debounce.reset(),this._debounce.last=t,this._debounce.subscribe(this.durationSelector(t))}complete(){this._debounce.complete(),super.complete()}},UA=ee(ja,"debounce");var Ja=class extends z{constructor(t,e,r){super(t),this.count=e,this.defaultValue=r}next(t){this.count--===0&&(this.defaultValue=t,this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("not enough elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},VA=ee(Ja,"elementAt");var Ya=class extends z{constructor(t,e){super(t),this.f=e,this.i=0}next(t){this.f(t)?(this.sink.next(this.i++),this.complete()):++this.i}},wA=ee(Ya,"findIndex"),Xa=class extends z{constructor(t,e,r){super(t),this.f=e,this.defaultValue=r,this.index=0}next(t){(!this.f||this.f(t,this.index++))&&(this.defaultValue=t,this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},BA=ee(Xa,"first"),za=class extends z{constructor(t,e,r){super(t),this.f=e,this.defaultValue=r,this.index=0}next(t){(!this.f||this.f(t,this.index++))&&(this.defaultValue=t)}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},$A=ee(za,"last"),qa=class extends z{constructor(t,e){super(t),this.predicate=e,this.index=0}next(t){this.predicate(t,this.index++)?this.result=!0:(this.result=!1,this.complete())}complete(){if(this.result===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.result);super.complete()}},HA=ee(qa,"every");var aC=_(f());var Qa=class extends z{constructor(t,e,r){super(t),this.f=e,typeof r=="undefined"?this.next=n=>{this.acc=n,this.resetNext(),this.sink.next(this.acc)}:this.acc=r}next(t){this.sink.next(this.acc=this.f(this.acc,t))}},jA=ee(Qa,"scan"),Za=class extends z{constructor(){super(...arguments),this.hasLast=!1}next(t){this.hasLast?this.sink.next([this.last,t]):this.hasLast=!0,this.last=t}},JA=ee(Za,"pairwise"),ec=class extends z{constructor(t,e,r){super(t),this.mapper=e,this.thisArg=r}next(t){super.next(this.mapper.call(this.thisArg,t))}},Qu=ee(ec,"map");var pr=class extends z{constructor(t,e,r){super(t),this.data=e,this.context=r}next(t){let e=this.context.combineResults;e?this.sink.next(e(this.data,t)):this.sink.next(t)}tryComplete(){this.context.resetComplete(),this.dispose()}},hr=class extends z{constructor(t,e,r){super(t),this.makeSource=e,this.combineResults=r,this.index=0}subInner(t,e){let r=this.currentSink=new e(this.sink,t,this);this.complete=this.tryComplete,r.complete=r.tryComplete,r.subscribe(this.makeSource(t,this.index++))}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},Os=class extends pr{},Ps=class extends hr{next(t){this.subInner(t,Os),this.next=e=>{this.currentSink.dispose(),this.subInner(e,Os)}}},S_=ee(Ps,"switchMap");function xs(i){return(t,e)=>i(()=>t,e)}var YA=xs(ee(Ps,"switchMapTo")),tc=class extends pr{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},Ms=class extends hr{constructor(){super(...arguments),this.sources=[],this.next2=this.sources.push.bind(this.sources)}next(t){this.next2(t),this.subNext()}subNext(){this.next=this.next2,this.subInner(this.sources.shift(),tc),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},XA=ee(Ms,"concatMap"),zA=xs(ee(Ms,"concatMapTo")),ic=class extends pr{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},Ls=class extends hr{constructor(){super(...arguments),this.inners=new Set}next(t){this.subInner(t,ic),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(t=>t.resetComplete()):this.dispose()}},qA=ee(Ls,"mergeMap"),QA=xs(ee(Ls,"mergeMapTo")),rc=class extends pr{dispose(){this.context.resetNext(),super.dispose()}},ks=class extends hr{next(t){this.next=ve,this.subInner(t,rc)}},ZA=ee(ks,"exhaustMap"),eC=xs(ee(ks,"exhaustMapTo")),nc=class extends z{constructor(t,e){super(t),this.f=e,this.groups=new Map}next(t){let e=this.f(t),r=this.groups.get(e);typeof r=="undefined"&&(r=La(),r.key=e,this.groups.set(e,r),super.next(r)),r.next(t)}complete(){this.groups.forEach(t=>t.complete()),super.complete()}error(t){this.groups.forEach(e=>e.error(t)),super.error(t)}},tC=ee(nc,"groupBy"),sc=class extends z{constructor(){super(...arguments),this.start=new Date}next(t){this.sink.next({value:t,interval:Number(new Date)-Number(this.start)}),this.start=new Date}},iC=ee(sc,"timeInterval"),oc=class extends z{constructor(t,e){super(t),this.miniseconds=e,this.buffer=[],this.id=setInterval(()=>{this.sink.next(this.buffer.concat()),this.buffer.length=0},this.miniseconds)}next(t){this.buffer.push(t)}complete(){this.sink.next(this.buffer),super.complete()}dispose(){clearInterval(this.id),super.dispose()}},rC=ee(oc,"bufferTime"),ac=class extends z{constructor(t,e){super(t),this.buffer=[],this.delayTime=e}dispose(){clearTimeout(this.timeoutId),super.dispose()}delay(t){this.timeoutId=setTimeout(()=>{let e=this.buffer.shift();if(e){let{time:r,data:n}=e;super.next(n),this.buffer.length&&this.delay(Number(this.buffer[0].time)-Number(r))}},t)}next(t){this.buffer.length||this.delay(this.delayTime),this.buffer.push({time:new Date,data:t})}complete(){this.timeoutId=setTimeout(()=>super.complete(),this.delayTime)}},nC=ee(ac,"delay"),cc=class extends z{constructor(t,e){super(t),this.selector=e}error(t){this.dispose(),this.selector(t)(this.sink)}},sC=ee(cc,"catchError");var hC=_(f());var dc=class extends z{constructor(t,e){super(t),e instanceof Function?this.next=r=>{e(r),t.next(r)}:(e.next&&(this.next=r=>{e.next(r),t.next(r)}),e.complete&&(this.complete=()=>{e.complete(),t.complete()}),e.error&&(this.error=r=>{e.error(r),t.error(r)}))}},uC=ee(dc,"tap"),uc=class extends z{constructor(t,e){super(t),this.timeout=e,this.id=setTimeout(()=>this.error(new bs(this.timeout)),this.timeout)}next(t){super.next(t),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},lC=ee(uc,"timeout");var OC=zu(qu(250),Qu(()=>performance.now()),Ds());var HC=_(f(),1);var mr=new Map;C.on(S.JOIN_SUCCESS,({room:i})=>{De(i.userId,{eventId:32788,eventDesc:"join room"})});C.on(S.LEAVE_START,({room:i})=>{De(i.userId,{eventId:32789,eventDesc:"leave room"})});C.on(S.LOCAL_TRACK_PUBLISHED,({track:i})=>{i.room&&De(i.room.userId,{eventId:i.kind===m.AUDIO?32769:32768,eventDesc:`publish ${i.kind}`})});C.on(S.LOCAL_TRACK_UNPUBLISHED,({track:i})=>{i.room&&De(i.room.userId,{eventId:i.kind===m.AUDIO?32771:32770,eventDesc:`unpublish ${i.kind}`})});C.on(S.TRACK_MUTED,({track:i})=>{i.room&&(i.kind===m.AUDIO?De(i.room.userId,{eventId:i.isRemote?32785:32772,eventDesc:"mute audio",remoteUserId:i.isRemote?i.userId:void 0}):De(i.room.userId,{eventId:i.isRemote?32784:32773,eventDesc:"mute video",remoteUserId:i.isRemote?i.userId:void 0}))});C.on(S.TRACK_UNMUTED,({track:i})=>{i.room&&(i.kind===m.AUDIO?De(i.room.userId,{eventId:i.isRemote?32787:32774,eventDesc:"unmute audio",remoteUserId:i.isRemote?i.userId:void 0}):De(i.room.userId,{eventId:i.isRemote?32786:32775,eventDesc:"unmute video",remoteUserId:i.isRemote?i.userId:void 0}))});C.on(S.REMOTE_TRACK_SUBSCRIBED,({track:i})=>{i.mediaType===1&&De(i.room.userId,{eventId:32777,eventDesc:`${m.SUBSCRIBE} ${i.kind}`,remoteUserId:i.userId}),i.mediaType===4&&De(i.room.userId,{eventId:32776,eventDesc:`${m.SUBSCRIBE} ${i.kind}`,remoteUserId:i.userId}),i.mediaType===8&&De(i.room.userId,{eventId:32803,eventDesc:`${m.SUBSCRIBE} ${m.SMALL_VIDEO}`,remoteUserId:i.userId})});C.on(S.REMOTE_TRACK_UNSUBSCRIBED,({track:i})=>{i.mediaType===1&&De(i.room.userId,{eventId:32779,eventDesc:`${m.UNSUBSCRIBE} ${i.kind}`,remoteUserId:i.userId}),i.mediaType===4&&De(i.room.userId,{eventId:32778,eventDesc:`${m.UNSUBSCRIBE} ${i.kind}`,remoteUserId:i.userId}),i.mediaType===8&&De(i.room.userId,{eventId:32804,eventDesc:`${m.UNSUBSCRIBE} ${m.SMALL_VIDEO}`,remoteUserId:i.userId})});C.on(S.SWITCH_DEVICE_SUCCESS,({track:i})=>{i.room&&De(i.room.userId,{eventId:i.kind===m.VIDEO?32780:32781,eventDesc:`switch ${i.kind===m.VIDEO?"camera":"microphone"}`})});C.on(S.LOCAL_TRACK_REPLACED,({track:i})=>{i.room&&De(i.room.userId,{eventId:i.kind===m.VIDEO?32782:32783,eventDesc:`replace ${i.kind}`})});C.on(S.SIGNAL_CONNECTION_STATE_CHANGED,({room:i,prevState:t,state:e})=>{let r,n;switch(e){case"CONNECTED":t==="RECONNECTING"?(r=32795,n="signal reconnected"):(r=32791,n="signal connected");break;case"DISCONNECTED":t==="RECONNECTING"?(r=32796,n="signal reconnect fail"):(r=32790,n="signal disconnected");break;case"RECONNECTING":r=32794,n="signal reconnecting";break}r&&n&&De(i.userId,{eventId:r,eventDesc:n})});C.on(S.PEER_CONNECTION_STATE_CHANGED,({room:i,prevState:t,state:e,remoteUserId:r})=>{let n=!!r,s=n?"downlink":"uplink",o,a;switch(e){case"CONNECTED":t==="RECONNECTING"?(o=n?32801:32798,a=`${s} reconnected`):(o=n?32793:32792,a=`${s} connected`);break;case"DISCONNECTED":t==="RECONNECTING"&&(o=n?32802:32799,a=`${s} reconnect fail`);break;case"RECONNECTING":o=n?32800:32797,a=`${s} reconnecting`;break}o&&a&&De(i.userId,{eventId:o,eventDesc:a,remoteUserId:r})});function De(i,t){let e=te(B({},t),{timestamp:Ur()});mr.has(i)?mr.get(i).push(e):mr.set(i,[e])}function Zu(i){if(mr.has(i)){let t=mr.get(i).map(e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,str_event_json:e.eventDesc}));return mr.delete(i),t}return[]}var QC=_(f(),1);var oy=_(f(),1);var el=_(nt(),1);var Us=class extends el.EventEmitter{constructor(e,r,n="userId"){super();this.mySelfId=e;this._log=r;this.key=n;p(this,"userMap",new Map);p(this,"remotePublishedUserMap",new Map)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let r=e[this.key],{userId:n,tinyId:s,role:o}=e;if(this.userMap.has(r))return;let a={userId:n,tinyId:s,role:o===20?"anchor":"audience"};this.userMap.set(r,a),this.emit("1",a)}deleteUser(e,r){let n=this.userMap.get(e);if(!n)return;let s=`peer leave [${e}]`;b(r)||(s+=`:${Fd[r]}`),this._log.info(s);let o=this.remotePublishedUserMap.get(e);if(o){let a=o.muteState;o.flag=0,this.emit("5",o.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:a,muteState:o.muteState,flag:0})}this.userMap.delete(e),this.emit("2",n.userId)}setUserList(e){this.userMap.forEach(r=>{e.findIndex(n=>n[this.key]===r[this.key])<0&&this.deleteUser(r[this.key],0)}),e.forEach(r=>{!this.userMap.has(r[this.key])&&r[this.key]!==this.mySelfId&&this.addUser(r)})}addRemotePublishedUser(e){this.remotePublishedUserMap.has(e[this.key])||this.remotePublishedUserMap.set(e[this.key],e)}deleteRemotePublishedUser(e){!this.remotePublishedUserMap.has(e)||this.remotePublishedUserMap.delete(e)}setRemotePublishedUserList(e){this.remotePublishedUserMap.forEach(r=>{let n=r[this.key];if(e.findIndex(s=>s[this.key]===r[this.key])<0){this._log.info(`remote [${n}] unpublish`);let s=r.muteState;r.flag=0,this.emit("5",r.userId),this.deleteRemotePublishedUser(n),this.emit("6",{prevMuteState:s,muteState:r.muteState,flag:0})}}),e.forEach(r=>{var u;let n=r[this.key];if(n===this.mySelfId)return;let{flag:s,userId:o,tinyId:a}=r,c=oi(s,o),d=(u=this.remotePublishedUserMap.get(n))==null?void 0:u.muteState;if(d){let l=this.remotePublishedUserMap.get(n);l&&l.flag!==s&&(l.flag=s,this._log.info(`remote publish updated: ${JSON.stringify(l.muteState)}`),this.emit("6",{prevMuteState:d,muteState:c,flag:s}))}else this._log.info(`remote publish. state: ${JSON.stringify(c)}`),this.addUser({userId:o,tinyId:a,role:20}),this.emit("3",r),this.emit("6",{prevMuteState:oi(0,o),muteState:c,flag:s})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};var Fy=_(f());var hn={SCENE_LIVE:"live",SCENE_RTC:"rtc",ROLE_ANCHOR:"anchor",ROLE_AUDIENCE:"audience",STREAM_TYPE_MAIN:"main",STREAM_TYPE_SUB:"sub",AUDIO_PROFILE_STANDARD:"standard",AUDIO_PROFILE_STANDARD_STEREO:"standard-stereo",AUDIO_PROFILE_HIGH:"high",AUDIO_PROFILE_HIGH_STEREO:"high-stereo",QOS_PREFERENCE_SMOOTH:"smooth",QOS_PREFERENCE_CLEAR:"clear"};var pv=_(f());var Ky=_(f(),1);var xe=class extends Error{};function g_(i,t){let e=[];return yt(e,i),yt(e,t),e}function I_(i){this._resolve=Promise.resolve(i)}function R_(i){this._reject=Promise.reject(i)}var _r=class{constructor(t,e){this.instance=t;this.group=e;this.started=!1;this.ops=[];this.startSame=()=>!0;this.mergeUpdate=g_;let r=_r.instances.get(t);r?r.set(e,this):_r.instances.set(t,new Map([[e,this]]))}static get(t,e){let r=_r.instances.get(t);return r&&r.get(e)||new _r(t,e)}action(t,e,r){let n=a=>{var c;return t===0?this.started=!0:t===3&&(this.started=!1),this.ops.shift(),(c=this.currentOp)==null||c.action(),a},s=a=>{var c,d;throw this.ops.shift(),t===0&&((c=this.currentOp)==null?void 0:c.type)===2&&this.ops.shift().reject(new xe("start failed")),(d=this.currentOp)==null||d.action(),a},o={type:t,action:()=>e(...o.args).then(n,s),args:r,resolve:I_,reject:R_};try{switch(this.state){case 1:if(t===0)throw new xe("already started");break;case 4:if(t===2)throw new xe("not started");break;default:return this.cacheOp(o)}}catch(a){return Promise.reject(a)}return this.ops.push(o),o.promise=e(...o.args).then(n,s)}cacheOp(t){if(this.ops.length===1)switch(this.state){case 0:case 2:if(t.type===0)throw new xe("already start");break;case 3:switch(t.type){case 2:throw new xe("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new xe("unknown state")}else switch(t.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let r=new xe("keep stop");if(this.ops.slice(1).forEach(n=>n.reject(r)),this.ops=this.ops.slice(0,1),this.state===3)return this.currentOp.promise}break;case 2:switch(this.lastOpType){case 2:return this.lastOp.args=this.mergeUpdate(this.lastOp.args,t.args),this.lastOp.promise;case 3:throw new xe("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new xe("start not allowed after update");case 0:throw new xe("duplicate start");case 3:if(this.startSame(this.currentOp.args,t.args))throw this.ops.pop().reject(new xe("keep start")),new xe("already start")}}t.promise=new Promise((r,n)=>{t._resolve?t._resolve.then(r):t.resolve=r,t._reject?t._reject.catch(n):t.reject=n});let{action:e}=t;return t.action=()=>e().then(t.resolve,t.reject),this.ops.push(t),t.promise}get lastOp(){return this.ops[this.ops.length-1]}get lastOpType(){return this.lastOp.type}get currentOp(){return this.ops[0]}get state(){return this.currentOp?this.currentOp.type:this.started?1:4}},Li=_r;Li.instances=new WeakMap;var rv=_(f());var Jy=_(f()),Q={INVALID_PARAMETER:5e3,INVALID_OPERATION:5100,ENV_NOT_SUPPORTED:5200,DEVICE_ERROR:5300,SERVER_ERROR:5400,OPERATION_FAILED:5500,OPERATION_ABORT:5998,UNKNOWN_ERROR:5999},hi=(O=>(O[O.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",O[O.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",O[O.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",O[O.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",O[O.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",O[O.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",O[O.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",O[O.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",O[O.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",O[O.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",O[O.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",O[O.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",O[O.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",O[O.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",O[O.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",O[O.MIX_PARAMS_USER_Z_ORDER=5015]="MIX_PARAMS_USER_Z_ORDER",O[O.MIX_PARAMS_VIDEO_FRAMERATE=5016]="MIX_PARAMS_VIDEO_FRAMERATE",O[O.MIX_PARAMS_VIDEO_GOP=5017]="MIX_PARAMS_VIDEO_GOP",O[O.MIX_PARAMS_AUDIO_BITRATE=5018]="MIX_PARAMS_AUDIO_BITRATE",O[O.MIX_PARAMS_NOT_SELF=5019]="MIX_PARAMS_NOT_SELF",O[O.MIX_PARAMS_USER_STREAM=5020]="MIX_PARAMS_USER_STREAM",O[O.INVALID_OPERATION=5100]="INVALID_OPERATION",O[O.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",O[O.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",O[O.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",O[O.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",O[O.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",O[O.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",O[O.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",O[O.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",O[O.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",O[O.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",O[O.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",O[O.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",O[O.DEVICE_ERROR=5300]="DEVICE_ERROR",O[O.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",O[O.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",O[O.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",O[O.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",O[O.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",O[O.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",O[O.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",O[O.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",O[O.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",O[O.SERVER_ERROR=5400]="SERVER_ERROR",O[O.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",O[O.OPERATION_FAILED=5500]="OPERATION_FAILED",O[O.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",O[O.REJOIN_FAILED=5502]="REJOIN_FAILED",O[O.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",O[O.OPERATION_ABORT=5998]="OPERATION_ABORT",O[O.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",O))(hi||{});var Qy=_(f());function il({code:i,params:t,enableDocLink:e=!1}){let r="",n,s=hi[i];try{n=tl[s]}catch(o){n=tl.UNKNOWN_ERROR}return ue(n)?r=n(t):oe(n)&&(r=n),e&&(r+=" doc:"),r}var tl={INVALID_PARAMETER({fnName:i}){return`the parameters of the '${i}' you called does not meet the requirements, please check the API documentation.`},INVALID_PARAMETER_REQUIRED({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' is a required param when calling ${e}(), received: ${r}.`},INVALID_PARAMETER_TYPE({key:i,rule:t,fnName:e,value:r}){let n=`${i||t.name}`,s="";return Array.isArray(t.type)?s=t.type.join("|"):s=t.type,`'${n}' must be type of ${s} when calling ${e}(), received type: ${Te(r)}.`},INVALID_PARAMETER_EMPTY({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' cannot be '${r}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:i,rule:t,fnName:e,value:r}){let n=`${i||t.name}`,s=`${t.instanceOf.name||t.instanceOf}`;return`'${n}' must be instanceof ${s} when calling ${e}(), received type: ${Te(r)}.`},INVALID_PARAMETER_RANGE({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' must be one of ${t.values.join("|")} when calling ${e}(), received: ${r}.`},INVALID_PARAMETER_LESS_THAN_ZERO({key:i,rule:t,fnName:e}){return`'${i||t.name}' cannot be less than 0 when calling ${e}().`},INVALID_PARAMETER_MIN({key:i,rule:t,value:e}){return`the min value of ${i||t.name} is ${t.min}, received: ${e}.`},INVALID_PARAMETER_MAX({key:i,rule:t,value:e}){return`the max value of ${i||t.name} is ${t.max}, received: ${e}.`},INVALID_ELEMENT_ID({key:i,fnName:t}){return`'${i}' is not found in the document object when calling ${t}().`},INVALID_ELEMENT_ID_TYPE({key:i,fnName:t,type:e}){return`the element corresponding to '${i}' must be instanceof HTMLElement when calling ${t}(), received: ${e}.`},INVALID_STREAM_ID({key:i}){return`'${i}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},INVALID_ROOM_ID_STRING({key:i}){return`'${i}' must be validate string when useStringRoomId is true.`},INVALID_ROOM_ID_INTEGER({key:i}){return`'${i}' must be an integer between [1, 4294967294] when useStringRoomId is false.`},INVALID_STREAM_TYPE:({fnName:i})=>`'streamType' is required when 'userId' is not '*', calling ${i}()`,MIX_PARAMS_USER_Z_ORDER({key:i}){return`'${i}' is required and must be between 1 and 15.`},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_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_OPERATION({fnName:i}){return`the API '${i}' you called does not meet the requirements, please check the API documentation.`},INVALID_OPERATION_NOT_JOINED({fnName:i}){return`cannot ${i} because you are not enter room yet.`},INVALID_OPERATION_REMOTE_USER_NOT_EXIST({fnName:i,value:t}){return`cannot ${i} because remote user(userId: ${t.userId}) does not publishing stream.`},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST({fnName:i,value:t}){return`cannot ${i} because remote user(userId: ${t.userId}) does not publishing ${t.streamType} video.`},INVALID_OPERATION_REPEAT_CALL({fnName:i}){return`you are already ${i}(), cannot repeated call '${i}'.`},ENV_NOT_SUPPORTED({fnName:i}){return`the current browser does not support the capability of the function '${i}' you are calling, please check the API documentation.`},NOT_SUPPORTED_HTTP:"http protocol does not support the ability to capture and publish streams, please use the https protocol.",NOT_SUPPORTED_WEBRTC:"the current browser does not support WebRTC capability, please check the SDK documentation.",NOT_SUPPORTED_H264_ENCODE:"this browser does not support H264 encode.",NOT_SUPPORTED_H264_DECODE:"this browser does not support H264 decode.",NOT_SUPPORTED_SCREEN_SHARE:"this browser does not support screen share, please check the browser version.",NOT_SUPPORTED_SMALL_VIDEO:"this browser does not support small video, please check the browser version.",NOT_SUPPORTED_SEI:"this browser does not support SEI, please check the browser version.",DEVICE_ERROR({fnName:i,error:t}){return`'${i}' got server exception${t?`, error: ${t.toString()}.`:"."}`},DEVICE_NOT_FOUND_ERROR({fnName:i,deviceType:t=ki(i),error:e}){return`NotFoundError, no ${t} detected, please check your device and the configuration on '${i}'${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_ALLOWED_ERROR({fnName:i,deviceType:t=ki(i),error:e}){return`NotAllowedError, you have disabled ${t} access, please allow the current application to use the ${t}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_READABLE_ERROR({fnName:i,deviceType:t=ki(i),error:e}){return`NotReadableError, the ${t} maybe in use by another APP, please check if the device is pre-occupied by another APP.`},DEVICE_OVERCONSTRAINED_ERROR({fnName:i,deviceType:t=ki(i),error:e}){return`OverconstrainedError, the device ID is incorrect, please check whether the device ID passed in is correct${e?`, error: ${e.toString()}.`:"."}`},DEVICE_INVALID_STATE_ERROR({fnName:i,deviceType:t=ki(i),error:e}){return`InvalidStateError, after the user clicks and interacts with the page, turn on the ${t}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_SECURITY_ERROR({fnName:i,deviceType:t=ki(i),error:e}){return`SecurityError, check whether the system security policy restricts the use of the ${t}, and it is recommended to turn on the ${t} after the user interacts with the page${e?`, error: ${e.toString()}.`:"."}`},DEVICE_ABORT_ERROR({fnName:i,deviceType:t=ki(i),error:e}){return`AbortError, an unknown exception in the system makes the device unusable, recommended to change the device or browser and re-check whether the device is normal${e?` error: ${e.toString()}.`:"."}`},CAMERA_RECOVER_FAILED({error:i}){return`camera recover capture failed ${(i==null?void 0:i.name)||""}: ${(i==null?void 0:i.originMessage)||(i==null?void 0:i.message)}`},MICROPHONE_RECOVER_FAILED({error:i}){return`microphone recover capture failed ${(i==null?void 0:i.name)||""}: ${(i==null?void 0:i.originMessage)||(i==null?void 0:i.message)}`},OPERATION_FAILED({fnName:i,error:t}){return`'${i}' failed, reason: ${t==null?void 0:t.toString()}`},FIREWALL_RESTRICTION(){return"media connection failure due to firewall restrictions, please try to change your network."},EVENT_HANDLER_ERROR({eventName:i}){return`an error was caught on trtc.on('${i}', handler), please check your code on 'handler'.`},SERVER_ERROR({fnName:i,error:t}){return`'${i}' got server error: ${t==null?void 0:t.toString()}, please check the SDK documentation.`},ACCOUNT_NO_MONEY:({fnParams:i})=>`your TRTC account run out of credit, please recharge.${i.sdkAppId?` SDKAppId: ${i.sdkAppId}`:""}`,OPERATION_ABORT({fnName:i}){return`'${i}' abort`},UNKNOWN_ERROR({fnName:i,error:t}){return`'${i}' throw unknown exception${t?`, error: ${t.toString()}.`:"."}`}};function ki(i){if(!i)return"camera";let t=i.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var fr=class extends Error{constructor({code:e,extraCode:r,message:n="",messageParams:s,fnName:o="",originError:a}){let c;n?c=n:c=il({code:r||e,params:B({fnName:o,error:a},s)});super(c);p(this,"name","RtcError");p(this,"code");p(this,"extraCode");p(this,"functionName");p(this,"message");p(this,"originError");this.name=hi[e],this.code=e,this.extraCode=r,this.functionName=o,this.originError=a,this.message=c}static convertFrom(e,r,n){let s=e;if(e instanceof L){let{stack:o}=e,a={code:Q.UNKNOWN_ERROR,fnName:r,originError:e};switch(e.getCode()){case v.INVALID_PARAMETER:a.code=Q.INVALID_PARAMETER;break;case v.INVALID_OPERATION:a.code=Q.INVALID_OPERATION;break;case v.NOT_SUPPORTED:case v.NOT_SUPPORTED_H264:a.code=Q.ENV_NOT_SUPPORTED,e.getCode()===v.NOT_SUPPORTED_H264&&(a.extraCode=e.message.includes(Le.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case v.DEVICE_NOT_FOUND:case v.DEVICE_AUTO_RECOVER_FAILED:a.code=Q.DEVICE_ERROR;break;case v.JOIN_ROOM_FAILED:a.messageParams={fnParams:n};case v.SERVER_TIMEOUT:case v.SWITCH_ROLE_FAILED:a.code=Q.SERVER_ERROR,a.extraCode=e.getExtraCode();break;case v.API_CALL_ABORTED:a.code=Q.OPERATION_ABORT;break;case v.INITIALIZE_FAILED:a.code=5300,a.extraCode=A_(e.name);break;case v.UNKNOWN:break;default:a.code=Q.OPERATION_FAILED}s=new fr(a),o&&(s.stack+=o.substr(o.indexOf(`
92
- `)))}else s=new fr({code:Q.UNKNOWN_ERROR,fnName:r,originError:e});return s}};function A_(i){let t;switch(i){case"NotFoundError":t=5301;break;case"NotAllowedError":t=5302;break;case"NotReadableError":t=5303;break;case"OverconstrainedError":t=5304;break;case"InvalidStateError":t=5305;break;case"SecurityError":t=5306;break;case"AbortError":t=5307;break;default:t=5300}return t}var J=fr;var lc=(i,t)=>{if(t instanceof xe){let{stack:e}=t;t=new J({code:Q.OPERATION_ABORT,message:`${i} abort: ${t.message}`,fnName:i}),e&&(t.stack+=e.substr(e.indexOf(`
93
- `)))}throw t};function xi(i,t){return ce((e,r)=>function(...n){let s=Li.get(this,typeof i=="string"?i:i(...n));return t&&(s.startSame=t.bind(this)),s.action(0,e.bind(this),n).catch(lc.bind(null,r))})}function Er(i,t){return ce((e,r)=>function(...n){let s=Li.get(this,typeof i=="string"?i:i(...n));return t&&(s.mergeUpdate=t.bind(this)),s.action(2,e.bind(this),n).catch(lc.bind(null,r))})}function Ui(i){return ce((t,e)=>function(...r){return Li.get(this,typeof i=="string"?i:i(...r)).action(3,t.bind(this),r).catch(lc.bind(null,e))})}var Av=_(f());var rl={type:D.Object,properties:{cameraId:{type:D.String},useFrontCamera:{type:D.Boolean},fillMode:{type:D.String,values:["contain","cover","fill"]},mirror:{type:D.Boolean},small:{properties:{width:{type:D.Number},height:{type:D.Number},frameRate:{type:D.Number},bitrate:{type:D.Number}}},videoTrack:{instanceOf:MediaStreamTrack}}},nl={type:D.Object,properties:{systemAudio:{type:D.Boolean},fillMode:{type:D.String,values:["contain","cover","fill"]},profile:{type:[D.String,D.Object],properties:{width:{type:D.Number},height:{type:D.Number},frameRate:{type:D.Number},bitrate:{type:D.Number}}},videoTrack:{instanceOf:MediaStreamTrack},audioTrack:{instanceOf:MediaStreamTrack}}},Tr={type:[D.String,HTMLElement,null,D.Array],arrayItem:{instanceOf:HTMLElement},validate(i,t,e){if(oe(i)){let r=document.getElementById(i);if(!r)throw new J({code:Q.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:t}});if(!(r instanceof HTMLElement))throw new J({code:Q.INVALID_PARAMETER,extraCode:5010,fnName:e,messageParams:{key:t,type:Te(r)}})}}},sl={name:"userId",required:!0,type:D.String},ol={type:D.Object,properties:{microphoneId:{type:D.String},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:D.Number,min:0,max:100},earMonitorVolume:{type:D.Number,min:0,max:100},echoCancellation:{type:D.Boolean},autoGainControl:{type:D.Boolean},noiseSuppression:{type:D.Boolean}}};function al(i,t,e,r){if(!/^[A-Za-z\d_-]*$/.test(i))throw new J({code:Q.INVALID_PARAMETER,extraCode:5011,fnName:e,messageParams:{key:t}})}function cl(i,t,e,r){if(oe(i)){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(i))throw new J({code:Q.INVALID_PARAMETER,extraCode:5012,fnName:e,messageParams:{key:t}})}else if(!(/^[1-9]\d*$/.test(String(i))&&i<4294967295))throw new J({code:Q.INVALID_PARAMETER,extraCode:5013,fnName:e,messageParams:{key:t}})}function ws(i,t){if(!i)throw new J({code:Q.INVALID_OPERATION,extraCode:5101,fnName:t})}function dl(i,t,e){if(!i)throw new J({code:Q.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:e}})}var mi={type:D.Number,notLessThanZero:!0},C_={enterRoom:{name:"EnterRoomConfig",type:D.Object,required:!0,validate(i,t,e){if(this._room.isJoined)throw new J({code:Q.INVALID_OPERATION,extraCode:5104,fnName:e})},properties:{sdkAppId:{required:!0,type:D.Number,allowEmpty:!1},userId:{required:!0,type:D.String,allowEmpty:!1},userSig:{required:!0,type:D.String,allowEmpty:!1},scene:{type:D.String,values:["live","rtc"]},role:{type:D.String,values:["audience","anchor"]},roomId:{required:!0,type:[D.String,D.Number],validate:cl},proxy:{type:[D.Object,D.String],properties:{websocketProxy:{type:D.String},turnServer:{type:[D.Object,D.Array],properties:{url:{required:!0,type:D.String},username:{type:D.String},credential:{type:D.String},credentialType:{type:D.String,values:["password"]}}},loggerProxy:{type:D.String},webtransportProxy:{type:D.String}}},enableAutoPlayDialog:{type:D.Boolean},streamId:{type:D.String},userDefineRecordId:{type:D.String}}},startLocalVideo:{name:"LocalVideoConfig",type:D.Object,properties:{view:Tr,publish:{type:D.Boolean},option:rl}},updateLocalVideo:{name:"updateLocalVideoConfig",type:D.Object,required:!0,properties:{view:te(B({},Tr),{required:!1}),publish:{type:D.Boolean},mute:{type:D.Boolean},option:rl}},startLocalAudio:{name:"LocalAudioConfig",type:D.Object,properties:{publish:{type:D.Boolean},option:ol}},updateLocalAudio:{name:"updateLocalAudioConfig",type:D.Object,required:!0,properties:{publish:{type:D.Boolean},mute:{type:D.Boolean},option:ol}},startScreenShare:{name:"ScreenShareConfig",type:D.Object,properties:{view:Tr,publish:{type:D.Boolean},option:nl}},updateScreenShare:{name:"updateScreenShareConfig",type:D.Object,required:!0,properties:{view:Tr,publish:{type:D.Boolean},option:nl}},muteRemoteAudio:[sl,{name:"mute",required:!0,type:D.Boolean}],setRemoteAudioVolume:[sl,{name:"volume",required:!0,type:D.Number,min:0,max:100}],startRemoteVideo:{name:"startRemoteVideoConfig",type:D.Object,required:!0,properties:{view:Tr,userId:{type:D.String,required:!0},streamType:{values:["main","sub"],required:!0},option:{type:D.Object,properties:{fillMode:{type:D.String,values:["contain","cover","fill"]},mirror:{type:D.Boolean}}}},validate(i,t,e){ws(this._room.isJoined,e);let r=this._room.remotePublishedUserMap.get(i.userId);if(dl(!!r,e,i),r&&(i.streamType==="main"&&!r.muteState.videoAvailable||i.streamType==="sub"&&!r.muteState.hasAuxiliary))throw new J({code:Q.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:i}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:D.Object,required:!0,properties:{view:te(B({},Tr),{required:!1}),userId:{type:D.String,required:!0},streamType:{values:["main","sub"],required:!0},option:{type:D.Object,properties:{fillMode:{type:D.String,values:["contain","cover","fill"]},mirror:{type:D.Boolean}}}},validate(i,t,e){ws(this._room.isJoined,e);let r=this._room.remotePublishedUserMap.get(i.userId);if(dl(!!r,e,i),r&&(i.streamType==="main"&&!r.muteState.videoAvailable||i.streamType==="sub"&&!r.muteState.hasAuxiliary))throw new J({code:Q.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:i}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:D.Object,required:!0,properties:{userId:{type:D.String,required:!0},streamType:{values:["main","sub"]}},validate(i,t,e){if(i.userId!=="*"&&b(i.streamType))throw new J({code:Q.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(i,t,e){ws(this._room.isJoined,e)}},enableAudioVolumeEvaluation:[{name:"interval",type:D.Number},{name:"enableInBackground",type:D.Boolean}],startMixTranscode:{name:"config",required:!0,type:D.Object,properties:{mode:{type:D.String,values:["preset-layout","manual"]},streamId:{type:D.String,validate:al},videoWidth:mi,videoHeight:mi,videoBitrate:te(B({},mi),{allowEmpty:!1}),videoFramerate:{type:D.Number,validate(i,t,e,r){if(i<=0||i>30)throw new J({code:Q.INVALID_PARAMETER,extraCode:5016,fnName:e})}},videoGop:{type:D.Number,validate(i,t,e,r){if(i<1||i>8)throw new J({code:Q.INVALID_PARAMETER,extraCode:5017,fnName:e})}},audioSampleRate:mi,audioBitrate:{type:D.Number,validate(i,t,e,r){if(i<32||i>192)throw new J({code:Q.INVALID_PARAMETER,extraCode:5018,fnName:e})}},audioChannels:{type:D.Number,values:[1,2]},backgroundColor:{type:D.Number},backgroundImage:{type:D.String},mixUsers:{required:!0,type:D.Array,arrayItem:{require:!0,type:D.Object,properties:{userId:{required:!0,type:D.String},roomId:{type:[D.String,D.Number],validate:cl},pureAudio:{type:D.Boolean},width:mi,height:mi,locationX:mi,locationY:mi,zOrder:{type:D.Number},streamType:{values:["main","sub"]},renderMode:{type:D.Number,values:[0,1,2,4]}}}}},validate(i,t,e,r){let n=0,s=0,{mixUsers:o}=i,a=[];if(o.forEach((c,d)=>{if(a.push(c.userId),!c.pureAudio){if(!c.zOrder||c.zOrder<1||c>15)throw new J({code:Q.INVALID_PARAMETER,extraCode:5015,fnName:e,messageParams:{key:`config.mixUsers[${d}].zOrder`}});c.width+c.locationX>n&&(n=c.width+c.locationX),c.height+c.locationY>s&&(s=c.height+c.locationY)}}),a.indexOf(this._room.userId)<0)throw new J({code:Q.INVALID_PARAMETER,extraCode:5019,fnName:e});if(i.videoWidth<n||i.videoHeight<s)throw new J({code:Q.INVALID_PARAMETER,extraCode:5020,fnName:e})}},startPublishCDNStream:{name:"options",required:!1,properties:{streamId:{type:D.String,validate:al},streamType:{values:["main","sub"]},appId:{type:D.Number,allowEmpty:!1},bizId:{type:D.Number,allowEmpty:!1},url:{type:D.String,allowEmpty:!1}}},sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(i,t,e,r){if(!ui)throw new J({code:Q.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new J({code:Q.INVALID_OPERATION,messageParams:{key:w.SEI_DISABLED}});if(i.byteLength>1e3)throw new J({code:Q.INVALID_PARAMETER,messageParams:{key:w.SEI_OVERSIZE,data:i.byteLength}});if(i.byteLength===0)throw new J({code:Q.INVALID_PARAMETER,messageParams:{key:w.SEI_EMPTY}});if(ws(this._room.isJoined,e),!this._room.isMainStreamPublished)throw new J({code:Q.INVALID_PARAMETER,messageParams:{key:w.SEI_BEFORE_PUBLISH}})}},{name:"options",type:D.Object,properties:{seiPayloadType:{type:D.Number,values:[5,243]}}}]},Oe={TRTC:C_};var kv=_(f(),1);function ll({timesInSecond:i,maxSizeInSecond:t,getSize:e}){return ce((r,n)=>{let s=new Map;return C.on(S.ROOM_DESTROY,({room:o})=>s.delete(o)),function(...o){let a=s.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},s.set(this,a)),a.timestamp===0?a.timestamp=Date.now():Date.now()-a.timestamp>1e3&&(a.timestamp=Date.now(),a.callCountInSecond=0,a.totalSizeInSecond=0),e&&(a.totalSizeInSecond+=e(...o)),a.timestamp!==0&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=i||a.totalSizeInSecond>t))throw new L({code:v.INVALID_OPERATION,message:$({key:w.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=i,isSize:a.totalSizeInSecond>t,name:n,timesInSecond:i,maxSizeInSecond:t}})});a.callCountInSecond++,r.call(this,...o)}})}var wv=_(f());function Bs(i){return i==="sub"?"auxiliary":i==="auxiliary"?"sub":"main"}function mn(i){return i===hn.QOS_PREFERENCE_CLEAR?"detail":i===hn.QOS_PREFERENCE_SMOOTH?"motion":""}var pl="5.0.2";var Jv=_(f());function He(...i){return ce((t,e)=>function(...r){try{hl.call(this,i,r,e,this._name)}catch(n){return Promise.reject(n)}return t.apply(this,r)})}function pc(...i){return ce((t,e)=>function(...r){try{hl.call(this,i,r,e,this._name)}catch(n){throw n}return t.apply(this,r)})}function hl(i,t,e,r){if(Ve(i))for(let n=0;n<i.length;n++)$s.call(this,{rule:i[n],value:t[n],key:i[n].name,fnName:e,className:r});else $s.call(this,{rule:i,value:t[0],key:i.name,fnName:e,className:r})}function $s({rule:i,value:t,key:e,fnName:r,className:n}){function s(c){return{code:Q.INVALID_PARAMETER,extraCode:c,fnName:r,messageParams:{key:e,rule:i,value:t}}}if(b(t)){if(i.required)throw new J(s(5001));if(b(i.defaultValue))return;t=i.defaultValue}if(Array.isArray(i.type)){let c=!1;for(let d=0;d<i.type.length;d++)i.type[d]===null&&t===null&&(c=!0),ue(i.type[d])&&t instanceof i.type[d]&&(c=!0),oe(i.type[d])&&Te(t)===i.type[d].toLowerCase()&&(c=!0);if(!c)throw new J({code:Q.INVALID_PARAMETER,extraCode:5002,fnName:r,messageParams:{key:e,rule:{type:i.type.map(d=>qr(d)?ps(d):oe(d)?d:Te(d))},value:t}})}else if(!b(i.type)&&Te(t)!==i.type)throw new J(s(5002));if(i.allowEmpty===!1){let c=de(t)&&(t===0||Number.isNaN(t)),d=oe(t)&&t.trim()==="";if(c||d)throw new J(s(5003))}if(i.notLessThanZero&&de(t)&&t<0)throw new J(s(5006));if(!b(i.min)&&de(t)&&t<i.min)throw new J(s(5007));if(!b(i.max)&&de(t)&&t>i.max)throw new J(s(5008));if(oe(i.instanceOf)){if(!t||t._name!==i.instanceOf)throw new J(s(5004))}else if(ue(i.instanceOf)&&!(t instanceof i.instanceOf))throw new J(s(5004));if(Array.isArray(i.values)&&!i.values.includes(t))throw new J(s(5005));let{properties:o}=i;ni(o)&&yi(t)&&Object.keys(o).forEach(c=>{$s.call(this,{rule:o[c],value:t&&t[c],key:`${c}`,fnName:r,className:n})});let{arrayItem:a}=i;ni(a)&&Ve(t)&&t.forEach((c,d)=>{$s.call(this,{rule:a,value:c,key:`${e}[${d}]`,fnName:r,className:n})}),ue(i.validate)&&i.validate.call(this,t,e,r,n,this)}var tN=_(f());function Ne(){return ce((i,t)=>function(...e){let r=this._log||loggerManager;e.length>0?r.info(`${t}() ${JSON.stringify(e,(n,s)=>{if(s===e||n in e)return s;try{return s instanceof HTMLElement?`id: ${s.id} type:${Te(s)}`:(JSON.stringify(s),s)}catch(o){return`type:${Te(s)}`}})}`):r.info(`${t}()`);try{let n=i.apply(this,e),s=q();return ls(n)?n.then(o=>(r.info(`${t}() success`),C.emit(S.API_SUCCESS_RATE,{room:this._room,apiName:t,cost:q()-s}),o)).catch(o=>{throw o=J.convertFrom.call(this,o,t,e.length===1?e[0]:e),r.error(`${t}() failed ${o}`),C.emit(S.API_SUCCESS_RATE,{room:this._room,apiName:t,error:o}),o}):(C.emit(S.API_SUCCESS_RATE,{room:this._room,apiName:t,cost:q()-s}),n)}catch(n){throw n=J.convertFrom.call(this,n,t),r.error(`${t}() failed ${n}`),C.emit(S.API_SUCCESS_RATE,{room:this._room,apiName:t,error:n}),n}})}var sN=_(f(),1);var Hs=new WeakMap;function ml(i,t){return ce((e,r)=>function(...n){var a,c;let s=(a=Hs.get(this))==null?void 0:a.get(t(...n));s&&s>0&&clearTimeout(s);let o=window.setTimeout(()=>{e.apply(this,n)},i);Hs.has(this)?(c=Hs.get(this))==null||c.set(t(...n),o):Hs.set(this,new Map([[t(...n),o]]))})}var N_=0,hc=new Set,ze=null;bd(pl);var _n=class extends fl.EventEmitter{constructor(e,r){super();p(this,"_room");p(this,"_eventListened",new Set);p(this,"_localVideoTrack",null);p(this,"_localAudioTrack",null);p(this,"_localScreenTrack",null);p(this,"_localScreenAudioTrack",null);p(this,"_localVideoConfig",null);p(this,"_localScreenConfig",null);p(this,"_localAudioConfig",null);p(this,"_remoteVideoConfigMap",new Map);p(this,"_remoteAudioConfigMap",new Map);p(this,"_remoteAudioMuteMap",new Map);p(this,"_log",M.createLogger({id:`t${++N_}`}));this._room=new e(B({logger:this._log,frameWorkType:_n.frameWorkType},r)),this._room.on("audio-volume",n=>{!n.find(s=>s.userId==="")&&this._localAudioTrack&&n.push({userId:"",volume:Math.floor(this._localAudioTrack.getAudioLevel()*100)}),this.emit(X.AUDIO_VOLUME,{result:n.sort((s,o)=>o.volume-s.volume)})}),this.on(X.REMOTE_AUDIO_UNAVAILABLE,({userId:n})=>{this._stopRemoteAudio({userId:n},!1).catch(()=>{})}),this.on(X.REMOTE_VIDEO_UNAVAILABLE,({userId:n,streamType:s})=>{this._stopRemoteVideo({userId:n,streamType:s},!1).catch(()=>{})}),ot(Se,Se).add("audioInputAdded",n=>{this.emit(X.DEVICE_CHANGED,{type:"microphone",action:"add",device:n})}).add("audioInputRemoved",n=>{this.emit(X.DEVICE_CHANGED,{type:"microphone",action:"remove",device:n})}).add("videoInputAdded",n=>{this.emit(X.DEVICE_CHANGED,{type:"camera",action:"add",device:n})}).add("videoInputRemoved",n=>{this.emit(X.DEVICE_CHANGED,{type:"camera",action:"remove",device:n})}).add("audioOutputAdded",n=>E(this,null,function*(){if(this.emit(X.DEVICE_CHANGED,{type:"speaker",action:"add",device:n}),ze&&ze.deviceId===Yn){let s=(yield dr()).find(o=>o.deviceId===Yn);s&&ze.groupId!==s.groupId&&(ze=s,this.emit(X.DEVICE_CHANGED,{type:"speaker",action:"active",device:s}))}})).add("audioOutputRemoved",n=>E(this,null,function*(){this.emit(X.DEVICE_CHANGED,{type:"speaker",action:"remove",device:n});let s=(yield dr())[0];s&&ze&&(ze.deviceId===n.deviceId||ze.deviceId===Yn&&ze.groupId!==s.groupId)&&(ze=s,this.emit(X.DEVICE_CHANGED,{type:"speaker",action:"active",device:s}))})),Qo(this,"trtc")}static create(){}static _create(e,r){hu();let n=new _n(e,r);return hc.add(n),ze?n.emit(X.DEVICE_CHANGED,{type:"speaker",action:"active",device:ze}):dr().then(s=>{s[0]&&(ze=s[0],n.emit(X.DEVICE_CHANGED,{type:"speaker",action:"active",device:s[0]}))}),n}enterRoom(e){return E(this,null,function*(){var c,d;let{scene:r="rtc",enableAutoPlayDialog:n=!0,autoReceiveAudio:s=!0,autoReceiveVideo:o=!0}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!oe(e.proxy)&&e.proxy.turnServer&&((d=(c=this._room).setTurnServer)==null||d.call(c,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=n,this._room.autoReceiveAudio=s,this._room.autoReceiveVideo=o;let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,role:e.role==="audience"?21:20,roomId:0,strRoomId:"",businessInfo:e.businessInfo||null,streamId:e.streamId||null,userDefineRecordId:e.userDefineRecordId||null};oe(e.roomId)?(a.strRoomId=e.roomId,this._room.useStringRoomId=!0):a.roomId=e.roomId,ot(this,this._room).add("peer-join",u=>{let{userId:l}=u;this.emit(X.REMOTE_USER_ENTER,{userId:l})}).add("peer-leave",u=>{this.emit(X.REMOTE_USER_EXIT,{userId:u})}).add("banned",u=>{this._exitRoom().then(()=>{this.emit(X.KICKED_OUT,{reason:u.reason})})}).add("error",u=>{this._exitRoom().then(()=>{this.emit(X.ERROR,J.convertFrom(u))})}).add("signal-connection-state-changed",u=>{this.emit(X.CONNECTION_STATE_CHANGED,u)}).add("network-quality",u=>{this.emit(X.NETWORK_QUALITY,u)}).add("remote-published",u=>{[u.remoteAudioTrack,u.remoteVideoTrack,u.remoteAuxiliaryTrack].forEach(h=>{ot(h,h).add("player-state-changed",I=>{let T=te(B({},I),{userId:u.userId});h.kind===m.VIDEO&&(T.streamType=Bs(h.streamType)),this.emit(h.kind===m.AUDIO?X.AUDIO_PLAY_STATE_CHANGED:X.VIDEO_PLAY_STATE_CHANGED,T)}).add("error",I=>{I.getCode()===v.PLAY_NOT_ALLOWED&&this.emit(X.AUTOPLAY_FAILED)})})}).add("remote-unpublished",u=>{[u.remoteAudioTrack,u.remoteVideoTrack,u.remoteAuxiliaryTrack].forEach(h=>{Be(h)})}).add("remote-publish-state-changed",({prevMuteState:u,muteState:l})=>{let{userId:h}=l,I=this._room.remotePublishedUserMap.get(h),T=u.audioAvailable,N=u.videoAvailable,{audioAvailable:H,videoAvailable:U}=l;H||this._remoteAudioConfigMap.delete(h),U||this._remoteVideoConfigMap.delete(`${h}_${"main"}`),l.hasAuxiliary||this._remoteVideoConfigMap.delete(`${h}_${"sub"}`),T!==H&&this.emit(H?X.REMOTE_AUDIO_AVAILABLE:X.REMOTE_AUDIO_UNAVAILABLE,{userId:h}),N!==U&&this.emit(U?X.REMOTE_VIDEO_AVAILABLE:X.REMOTE_VIDEO_UNAVAILABLE,{userId:h,streamType:"main"}),u.hasAuxiliary!==l.hasAuxiliary&&this.emit(l.hasAuxiliary?X.REMOTE_VIDEO_AVAILABLE:X.REMOTE_VIDEO_UNAVAILABLE,{userId:h,streamType:"sub"})}).add("firewall-restriction",()=>{this.emit(X.ERROR,new J({code:Q.OPERATION_FAILED,extraCode:5501}))}).add("sei-message",u=>{this.emit(X.SEI_MESSAGE,u)}),this._handleReceiveMode(),yield this._room.join(a,r,_n.frameWorkType),this._checkTrackToPublish()})}exitRoom(){return E(this,null,function*(){return yield this._exitRoom()})}switchRole(e){return E(this,null,function*(){yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){Be(Se),this.removeAllListeners(),this._room.destroy(),hc.delete(this),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare()}startLocalAudio(){return E(this,arguments,function*(e={publish:!0}){if(this._localAudioTrack){this._log.warn("local audio is already started");return}let{publish:r=!0,option:n}=e,s=new Gt,o={},a={muted:!0};n&&(b(n.microphoneId)?b(n.audioTrack)||(o.customSource=n.audioTrack):o.deviceId=n.microphoneId,b(n.captureVolume),b(n.profile)||(oe(n.profile)?Co[n.profile]&&s.setProfile(Co[n.profile]):s.setProfile(n.profile)),de(n.earMonitorVolume)&&(a.muted=!(n.earMonitorVolume>0),a.volume=n.earMonitorVolume),b(n.echoCancellation)||(s.profile.echoCancellation=n.echoCancellation),b(n.noiseSuppression)||(s.profile.noiseSuppression=n.noiseSuppression),b(n.autoGainControl)||(s.profile.autoGainControl=n.autoGainControl)),s.on("5",c=>{this.emit(X.ERROR,new J({code:Q.DEVICE_ERROR,extraCode:5309,messageParams:{error:c}}))}),s.on("2",c=>{this.emit(X.DEVICE_CHANGED,{type:"microphone",action:"active",device:c})}),s.on("4",c=>{let d;c.error&&(d=J.convertFrom(c.error)),this.emit(X.PUBLISH_STATE_CHANGED,te(B({},c),{error:d}))}),yield s.capture(o),ot(s,s).add("player-state-changed",c=>{this.emit(X.AUDIO_PLAY_STATE_CHANGED,te(B({},c),{userId:""}))}),yield this._updateAudioPlayOption({playOption:a,track:s}),r&&this._room.isJoined&&this._room.publish(s).catch(()=>{}),this._localAudioTrack=s,this._localAudioConfig=te(B({},e),{publish:r})})}updateLocalAudio(e){return E(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:r,mute:n,option:s}=e,o={};s&&(s.microphoneId?yield this._localAudioTrack.switchDevice(s.microphoneId):b(s.audioTrack)||(this._localAudioTrack.setMediaStreamTrack(s.audioTrack),yield this._room.replaceTrack(this._localAudioTrack)),b(s.captureVolume),b(s.earMonitorVolume)||(o.muted=!(s.earMonitorVolume>0),o.volume=s.earMonitorVolume)),yield this._updateAudioPlayOption({playOption:o,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),this._room.isJoined&&!b(r)&&(r&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!r&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),b(n)||this._localAudioTrack.setMute(n),yt(this._localAudioConfig,e)})}stopLocalAudio(){return E(this,null,function*(){!this._localAudioTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),this._localAudioTrack.stop(),this._localAudioTrack.close(),Be(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)})}startLocalVideo(){return E(this,arguments,function*(e={publish:!0,view:null}){if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:r,publish:n=!0,option:s}=e,o=new mt,a={},c={};if(s&&(s.cameraId?a.deviceId=s.cameraId:b(s.useFrontCamera)?b(s.videoTrack)||(a.customSource=s.videoTrack):a.facingMode=s.useFrontCamera?m.FACING_MODE_USER:m.FACING_MODE_ENVIRONMENT,b(s.profile)||(oe(s.profile)?zi[s.profile]&&o.setProfile(zi[s.profile]):o.setProfile(s.profile)),b(s.fillMode)||(c.objectFit=s.fillMode),b(s.mirror)||(c.mirror=s.mirror),b(s.small)||(Es()?oe(s.small)?o.small=zi[s.small]:o.small=s.small:this._log.warn("small stream is not supported"))),o.on("5",d=>{this.emit(X.ERROR,new J({code:Q.DEVICE_ERROR,extraCode:5308,messageParams:{error:d}}))}),o.on("2",d=>{this.emit(X.DEVICE_CHANGED,{type:"camera",action:"active",device:d})}),o.on("4",d=>{let u;d.error&&(u=J.convertFrom(d.error)),this.emit(X.PUBLISH_STATE_CHANGED,te(B({},d),{error:u}))}),yield o.capture(a),(s==null?void 0:s.qosPreference)&&o.mediaTrack){let d=mn(s.qosPreference);o.mediaTrack.contentHint=d}ot(o,o).add("player-state-changed",d=>{this.emit(X.VIDEO_PLAY_STATE_CHANGED,te(B({},d),{userId:"",streamType:"main"}))}),yield this._updateVideoPlayOption({view:r,playOption:c,track:o}),n&&this._room.isJoined&&this._room.publish(o).catch(()=>{}),this._localVideoTrack=o,this._localVideoConfig=te(B({},e),{view:r,publish:n})})}updateLocalVideo(e){return E(this,null,function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:r,publish:n,mute:s,option:o}=e,a={};if(o&&(o.cameraId?yield this._localVideoTrack.switchDevice(o.cameraId):b(o.useFrontCamera)?b(o.videoTrack)||(this._localVideoTrack.setMediaStreamTrack(o.videoTrack),yield this._room.replaceTrack(this._localVideoTrack)):yield this._localVideoTrack.switchDevice(o.useFrontCamera?m.FACING_MODE_USER:m.FACING_MODE_ENVIRONMENT),b(o.profile)||(oe(o.profile)?zi[o.profile]&&this._localVideoTrack.setProfile(zi[o.profile]):this._localVideoTrack.setProfile(o.profile)),b(o.fillMode)||(a.objectFit=o.fillMode),b(o.mirror)||(a.mirror=o.mirror),o.qosPreference&&this._localVideoTrack.mediaTrack)){let c=mn(o.qosPreference);this._localVideoTrack.mediaTrack.contentHint=c}yield this._updateVideoPlayOption({view:r,playOption:a,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),this._room.isJoined&&!b(n)&&(n&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._localVideoConfig.publish&&!n&&this._room.unpublish(this._localVideoTrack).catch(()=>{})),b(s)||this._localVideoTrack.setMute(s),yt(this._localVideoConfig,e)})}stopLocalVideo(){return E(this,null,function*(){!this._localVideoTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),Be(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return E(this,arguments,function*(e={publish:!0,view:null}){if(this._localScreenTrack){this._log.warn("screen share is already started");return}let{view:r=null,publish:n=!0,option:s}=e,o=new bt;o.on("4",l=>{let h;l.error&&(h=J.convertFrom(l.error)),this.emit(X.PUBLISH_STATE_CHANGED,te(B({},l),{error:h}))});let a=null;o.setMediaType(2);let c={},d={};s&&(b(s.profile)||(oe(s.profile)?yo[s.profile]&&o.setProfile(yo[s.profile]):o.setProfile(s.profile)),s.systemAudio&&(c.systemAudio=!0,c.echoCancellation=s.echoCancellation,c.noiseSuppression=s.noiseSuppression,c.autoGainControl=s.autoGainControl),b(s.fillMode)||(d.objectFit=s.fillMode),s.videoTrack&&(c.videoTrack=s.videoTrack),s.audioTrack&&(c.audioTrack=s.audioTrack));let u=yield o.capture(c);if(s!=null&&s.qosPreference){let l=mn(s.qosPreference);o.mediaTrack.contentHint=l}if(o.mediaTrack.addEventListener(m.ENDED,()=>{this._stopScreenShare(),this.emit(X.SCREEN_SHARE_STOPPED)}),u.getAudioTracks()[0]&&(a=new Pi,a.setScreenAudioTrack(u.getAudioTracks()[0],u)),ot(o,o).add("player-state-changed",l=>{this.emit(X.VIDEO_PLAY_STATE_CHANGED,te(B({},l),{userId:"",streamType:"sub"}))}),yield this._updateVideoPlayOption({view:r,playOption:d,track:o}),n&&this._room.isJoined){let l=[o];a&&l.push(a),this._room.publish(...l).catch(()=>{})}this._localScreenTrack=o,this._localScreenAudioTrack=a,this._localScreenConfig=te(B({},e),{view:r,publish:n})})}updateScreenShare(e){return E(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:r,publish:n,option:s}=e,o={};if(s&&(b(s.fillMode)||(o.objectFit=s.fillMode),s.qosPreference)){let a=mn(s.qosPreference);this._localScreenTrack.mediaTrack.contentHint=a}yield this._updateVideoPlayOption({view:r,playOption:o,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),this._room.isJoined&&!b(n)&&(n&&!this._localScreenConfig.publish&&this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenConfig.publish&&!n&&this._room.unpublish(this._localScreenTrack).catch(()=>{})),yt(this._localScreenConfig,e)})}stopScreenShare(){return E(this,null,function*(){return yield this._stopScreenShare()})}startPlugin(e,r){return E(this,null,function*(){e==="AudioMixer"&&(yield this._room.startPlugin("AudioMixer",r)),e==="AIDenoiser"&&(yield this._room.startPlugin("AIDenoiser",r))})}updatePlugin(e,r){return E(this,null,function*(){e==="AudioMixer"&&(yield this._room.updatePlugin("AudioMixer",r))})}stopPlugin(e,r){return E(this,null,function*(){e==="AudioMixer"&&(yield this._room.stopPlugin("AudioMixer",r)),e==="AIDenoiser"&&(yield this._room.stopPlugin("AIDenoiser",r))})}startRemoteVideo(e){return E(this,null,function*(){let{view:r,userId:n,streamType:s,option:o}=e,a=`${n}_${s}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${n}, streamType:${s}`);return}let c=this._room.remotePublishedUserMap.get(n);if(!c)return;let d={},u=s==="main"?c.remoteVideoTrack:c.remoteAuxiliaryTrack;o&&(b(o.fillMode)||(d.objectFit=o.fillMode),b(o.mirror)||(d.mirror=o.mirror),s==="main"&&!b(o.small)&&this._room.changeType(o.small,u.user)),yield this._room.subscribe(u),yield this._updateVideoPlayOption({view:r,playOption:d,track:u}),this._remoteVideoConfigMap.set(a,e)})}updateRemoteVideo(e){return E(this,null,function*(){let{view:r,userId:n,streamType:s,option:o}=e,a=`${n}_${s}`;if(!this._remoteVideoConfigMap.has(a)||!this._room.remotePublishedUserMap.has(n))return;let c={};o&&(b(o.fillMode)||(c.objectFit=o.fillMode),b(o.mirror)||(c.mirror=o.mirror));let d=null,u=this._room.remotePublishedUserMap.get(n);s==="main"&&(u==null?void 0:u.muteState.hasVideo)&&(d=u.remoteVideoTrack),s==="sub"&&(u==null?void 0:u.muteState.hasAuxiliary)&&(d=u.remoteAuxiliaryTrack);let l=this._remoteVideoConfigMap.get(a);d&&(s==="main"&&o&&!b(o.small)&&this._room.changeType(o.small,d.user),yield this._updateVideoPlayOption({view:r,playOption:c,track:d,prevConfig:l})),yt(l,e)})}stopRemoteVideo(e){return E(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,r=!0){return E(this,null,function*(){let n=[],s=this._room.remotePublishedUserMap.get(e.userId);if(s){let{muteState:o,remoteVideoTrack:a,remoteAuxiliaryTrack:c}=s;a.stop(),o.hasVideo&&e.streamType==="main"&&n.push(a),c.stop(),o.hasAuxiliary&&e.streamType==="sub"&&n.push(c)}for(let o of n)r&&(yield this._room.unsubscribe(o));this._remoteVideoConfigMap.delete(`${e.userId}_${e.streamType}`)})}muteRemoteAudio(e,r){return E(this,null,function*(){if(e==="*")if(r)yield this._stopRemoteAudio({userId:e});else{let n=[...this._room.remotePublishedUserMap.values()];for(let s of n)s.muteState.hasAudio&&(yield this._startRemoteAudio({userId:s.userId}))}else r?yield this._stopRemoteAudio({userId:e}):yield this._startRemoteAudio({userId:e});this._remoteAudioMuteMap.set(e,r)})}setRemoteAudioVolume(e,r){if(e==="*"){let n=[...this._room.remotePublishedUserMap.values()];for(let s of n)this._updateAudioPlayOption({playOption:{volume:r},track:s.remoteAudioTrack})}else if(e){let n=this._room.remotePublishedUserMap.get(e);n&&this._updateAudioPlayOption({playOption:{volume:r},track:n.remoteAudioTrack})}}enableAudioVolumeEvaluation(e=2e3,r=!1){this._room.enableAudioVolumeEvaluation(e,r)}startMixTranscode(e){let r=B({},e);return r.mixUsers=e.mixUsers.map(n=>{let s=B({},n);return b(n.streamType)||(s.streamType=Bs(n.streamType)),s}),this._room.startMixTranscode(r)}stopMixTranscode(){return this._room.stopMixTranscode()}startPublishCDNStream(e){let r=B({},e);return b(e.streamType)||(r.streamType=Bs(e.streamType)),this._room.startPublishCDNStream(r)}stopPublishCDNStream(){return this._room.stopPublishCDNStream()}on(e,r,n){return super.on(e,r,n),this._eventListened.add(e),this}off(e,r,n){return e==="*"?(this._eventListened.clear(),this.removeAllListeners()):super.off(e,r,n),this}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:r="",streamType:n="main"}=e;if(r===""){if(n==="main"&&this._localVideoTrack)return this._localVideoTrack.mediaTrack;if(n==="sub"&&this._localScreenTrack)return this._localScreenTrack.mediaTrack}else{let s=this._room.remotePublishedUserMap.get(r);if(s)return n==="main"?s.remoteVideoTrack.mediaTrack:s.remoteAuxiliaryTrack.mediaTrack}return null}getAudioTrack(e){if(e){let r=this._room.remotePublishedUserMap.get(e);if(r)return r.remoteAudioTrack.mediaTrack}else if(this._localAudioTrack)return this._localAudioTrack.mediaTrack;return null}setCurrentSpeaker(e){var r;(r=this._localAudioTrack)==null||r.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(n=>n.remoteAudioTrack.setAudioOutput(e))}_startRemoteAudio(e){return E(this,null,function*(){let{userId:r,option:n}=e;if(this._remoteAudioConfigMap.has(r)){this._log.warn(`remote audio has already started. userId:${r}`);return}let s=this._room.remotePublishedUserMap.get(r);if(!s)return;let o={};n&&(b(n.volume)||(o.volume=n.volume));let a=s.remoteAudioTrack;yield this._room.subscribe(a),yield this._updateAudioPlayOption({playOption:o,track:a}),this._remoteAudioConfigMap.set(r,e)})}_stopRemoteAudio(e,r=!0){return E(this,null,function*(){let n=this._room.remotePublishedUserMap.get(e.userId);n&&(n.remoteAudioTrack.stop(),n.muteState.hasAudio&&r&&(yield this._room.unsubscribe(n.remoteAudioTrack))),this._remoteAudioConfigMap.delete(`${e.userId}`)})}_updateVideoPlayOption(o){return E(this,arguments,function*({view:e,playOption:r,track:n,prevConfig:s}){if(b(e)&&s&&s.view&&!Qr(r)){let a;Ve(s.view)?a=s.view:a=hs(s.view),a&&(yield n.play(a,r))}if(!b(e)){let a;Ve(e)?a=e:a=hs(e),a?yield n.play(a,r):n.stop()}})}_updateAudioPlayOption(s){return E(this,arguments,function*({playOption:e={},track:r,prevConfig:n}){r.isPlayCalled||(yield r.play(null,e)),b(e.muted)||r.setPlayerMute(e.muted),b(e.volume)||r.setAudioVolume(e.volume/100)})}_checkTrackToPublish(){var r,n,s;let e=[];if(((r=this._localAudioConfig)==null?void 0:r.publish)&&this._localAudioTrack&&e.push(this._localAudioTrack),((n=this._localVideoConfig)==null?void 0:n.publish)&&this._localVideoTrack&&e.push(this._localVideoTrack),(s=this._localScreenConfig)!=null&&s.publish&&(this._localScreenTrack&&e.push(this._localScreenTrack),this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack)),e.length!==0)return this._room.publish(...e).catch(()=>{})}_handleReceiveMode(){this._room.autoReceiveAudio&&ot(this,this).add(X.REMOTE_AUDIO_AVAILABLE,r=>E(this,[r],function*({userId:e}){if(this._remoteAudioMuteMap.get("*")||this._remoteAudioMuteMap.get(e))return;let n=this._room.remotePublishedUserMap.get(e);n&&(yield this._room.subscribe(n.remoteAudioTrack).catch(()=>{}),yield this._updateAudioPlayOption({track:n.remoteAudioTrack}).catch(()=>{}),this._remoteAudioConfigMap.set(e,{userId:e}))})),this._room.autoReceiveVideo&&ot(this,this).add(X.REMOTE_VIDEO_AVAILABLE,({userId:e,streamType:r})=>{let n=this._room.remotePublishedUserMap.get(e);n&&(r==="main"?this._room.subscribe(n.remoteVideoTrack).catch(()=>{}):r==="sub"&&this._room.subscribe(n.remoteAuxiliaryTrack).catch(()=>{}))})}_exitRoom(){return E(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),[...this._remoteAudioConfigMap.keys()].forEach(e=>{this._stopRemoteAudio({userId:e}).catch()}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let r=e.includes("main")?"main":"sub",n=e.split(`_${r}`)[0];n&&this._stopRemoteVideo({userId:n,streamType:r}).catch()}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._room.remotePublishedUserMap.forEach(e=>{Be(e.remoteAudioTrack),Be(e.remoteVideoTrack),Be(e.remoteAuxiliaryTrack)}),Be(this)})}_stopScreenShare(){return E(this,null,function*(){var e,r,n;if(!!this._localScreenTrack){if(this._room.isJoined){let s=[this._localScreenTrack];this._localScreenAudioTrack&&s.push(this._localScreenAudioTrack),yield(e=this._room)==null?void 0:e.unpublish(...s).catch(()=>{})}this._localScreenTrack.stop(),this._localScreenTrack.close(),(r=this._localScreenAudioTrack)==null||r.stop(),(n=this._localScreenAudioTrack)==null||n.close(),Be(this._localScreenTrack),this._localScreenTrack=null,this._localScreenAudioTrack=null,this._localScreenConfig=null}})}sendSEIMessage(e,r){this._room.sendSEI(e,r||{seiPayloadType:243})}static setLogLevel(e,r){M.setLogLevel(e),b(r)||(r?M.enableUploadLog():M.disableUploadLog())}static isSupported(){return sa()}static getCameraList(){return ht()}static getMicrophoneList(){return at()}static getSpeakerList(){return dr()}static setCurrentSpeaker(e){return E(this,null,function*(){(yield dr()).forEach(n=>{n.deviceId===e&&(hc.forEach(s=>{s.setCurrentSpeaker(e),s.emit(X.DEVICE_CHANGED,{type:"speaker",action:"active",device:n})}),ze=n)})})}},ae=_n;p(ae,"_loggerManager",M),p(ae,"EVENT",X),p(ae,"ERROR_CODE",Q),p(ae,"TYPE",hn),p(ae,"frameWorkType",30),F([He(Oe.TRTC.enterRoom),xi("room",([i],[t])=>i.roomId===t.roomId&&i.userId===t.userId&&i.sdkAppId===t.sdkAppId),ce(i=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),i.call(this,t).catch(e=>{throw Be(this),e})}),Ne()],ae.prototype,"enterRoom",1),F([Ne()],ae.prototype,"exitRoom",1),F([He(Oe.TRTC.switchRole),Er("room",(i,t)=>t),Ne()],ae.prototype,"switchRole",1),F([Ne()],ae.prototype,"destroy",1),F([He(Oe.TRTC.startLocalAudio),xi("audio",([i],[t])=>{var e,r;return((e=i==null?void 0:i.option)==null?void 0:e.microphoneId)===((r=t==null?void 0:t.option)==null?void 0:r.microphoneId)}),Ne()],ae.prototype,"startLocalAudio",1),F([He(Oe.TRTC.updateLocalAudio),Er("audio"),Ne()],ae.prototype,"updateLocalAudio",1),F([Ui("audio"),Ne()],ae.prototype,"stopLocalAudio",1),F([He(Oe.TRTC.startLocalVideo),xi("video",([i],[t])=>{var e,r;return((e=i==null?void 0:i.option)==null?void 0:e.cameraId)===((r=t==null?void 0:t.option)==null?void 0:r.cameraId)}),Ne()],ae.prototype,"startLocalVideo",1),F([He(Oe.TRTC.updateLocalVideo),Er("video"),Ne()],ae.prototype,"updateLocalVideo",1),F([Ui("video"),Ne()],ae.prototype,"stopLocalVideo",1),F([He(Oe.TRTC.startScreenShare),xi("screen",()=>!0),Ne()],ae.prototype,"startScreenShare",1),F([He(Oe.TRTC.updateScreenShare),Er("screen"),Ne()],ae.prototype,"updateScreenShare",1),F([Ne()],ae.prototype,"stopScreenShare",1),F([He(Oe.TRTC.startRemoteVideo),xi(i=>`v${i.userId}${i.streamType}`,()=>!0),Ne()],ae.prototype,"startRemoteVideo",1),F([He(Oe.TRTC.updateRemoteVideo),Er(i=>`v${i.userId}${i.streamType}`),Ne()],ae.prototype,"updateRemoteVideo",1),F([He(Oe.TRTC.stopRemoteVideo),ce(i=>function(t){return E(this,null,function*(){if(t.userId==="*"){let e=[];return this._room.remotePublishedUserMap.forEach(r=>{this._remoteVideoConfigMap.has(`${r.userId}_${"main"}`)&&e.push(this.stopRemoteVideo({streamType:"main",userId:r.userId}).catch(()=>{})),this._remoteVideoConfigMap.has(`${r.userId}_${"sub"}`)&&e.push(this.stopRemoteVideo({streamType:"sub",userId:r.userId}).catch(()=>{}))}),Promise.all(e)}return i.call(this,t)})}),Ne()],ae.prototype,"stopRemoteVideo",1),F([Ui(i=>`v${i.userId}${i.streamType}`)],ae.prototype,"_stopRemoteVideo",1),F([He(...Oe.TRTC.muteRemoteAudio),Ne()],ae.prototype,"muteRemoteAudio",1),F([pc(...Oe.TRTC.setRemoteAudioVolume),ml(200,i=>i),Ne()],ae.prototype,"setRemoteAudioVolume",1),F([pc(...Oe.TRTC.enableAudioVolumeEvaluation)],ae.prototype,"enableAudioVolumeEvaluation",1),F([He(Oe.TRTC.startMixTranscode)],ae.prototype,"startMixTranscode",1),F([xi(i=>`a${i.userId}`,()=>!0)],ae.prototype,"_startRemoteAudio",1),F([ce(i=>function(t){return E(this,null,function*(){return t.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(e=>this._stopRemoteAudio(te(B({},t),{userId:e.userId})).catch(()=>{}))):i.call(this,t)})}),Ui(i=>`a${i.userId}`)],ae.prototype,"_stopRemoteAudio",1),F([Ui("room")],ae.prototype,"_exitRoom",1),F([Ui("screen")],ae.prototype,"_stopScreenShare",1),F([He(Oe.TRTC.sendSEIMessage),ll({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...i)=>i[0].byteLength})],ae.prototype,"sendSEIMessage",1);var fn=ae;var ix=_(f());var Cb=_(f(),1);var mc=class{constructor(){this._set=new Set;C.on(S.LEAVE_SUCCESS,this.delete,this)}add({room:t,roomId:e}){if(t.scene==="rtc")return;let r=this.getKey(t.userId,e||t.roomId,t.sdkAppId,t.useStringRoomId);this._set.add(r)}delete({room:t,roomId:e}){if(t.scene==="rtc")return;let r=this.getKey(t.userId,t.roomId||e,t.sdkAppId,t.useStringRoomId);this._set.delete(r)}getKey(t,e,r,n){return`${r}_${e}_${t}_${n}`}isJoined({userId:t,roomId:e,sdkAppId:r,room:n}){return n.scene==="rtc"?!1:this._set.has(this.getKey(t,e,r,n.useStringRoomId))}};function b_(){return E(this,null,function*(){let i,t;try{let l=yield at();i=l&&l.length}catch(l){}try{let l=yield ht();t=l&&l.length}catch(l){}let e={microphone:i,camera:t},{isH264EncodeSupported:r,isVp8EncodeSupported:n,isH264DecodeSupported:s,isVp8DecodeSupported:o}=this.checkSystemResult.detail,a=Bt.basis(),c={webRTC:a.isWebRTCSupported,getUserMedia:a.isGetUserMediaSupported,webSocket:a.isWebSocketsSupported,screenShare:a.isScreenShareSupported,webAudio:a.isWebAudioSupported,h264Encode:r,h264Decode:s,vp8Encode:n,vp8Decode:o},d={browser:a.browser,os:a.os,trtc:c,devices:e},u={isWebCodecSupported:a.isWebCodecSupported,isMediaSessionSupported:a.isMediaSessionSupported,isWebTransportSupported:a.isWebTransportSupported};Ee.uploadEvent({log:`trtcstats-${JSON.stringify(d)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(d)}`),Ee.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(u)}`,userId:this.userId})})}function El(){return ce(i=>{let t=new mc;return function(e,r,n){return E(this,null,function*(){let s=String(e.roomId||e.strRoomId);if(this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.userSig=e.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=r,e.privateMapKey=e.privateMapKey||"",this.isJoined)throw new L({code:v.INVALID_OPERATION,message:$({key:w.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:s,sdkAppId:this.sdkAppId,room:this}))throw new L({code:v.INVALID_OPERATION,message:$({key:w.REPEAT_JOIN,data:this.userId})});t.add({room:this,roomId:s}),this._log.info(`Join() => joining room: ${s} useStringRoomId: ${this.useStringRoomId} scene: ${this.scene} role: ${this.role}`),this.role=e.role===21?"audience":"anchor",C.emit(S.JOIN_START,{room:this,roomId:s}),this.checkSystemResult=yield Bt.checkSystemRequirementsInternal(),this.checkDestroy();let o=Ke.getEnv();o||(o=ei.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(vo.OLD_CLOUD_LADDER)?o=ei.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(vo.WEBRTC)&&(o=ei.WEBRTC))),Ee.setConfig({env:o,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:s}),b_.call(this);let{isH264EncodeSupported:a,isVp8EncodeSupported:c}=this.checkSystemResult.detail;if(!Bt.isWebRTCSupported()||!a&&!c)throw new L({code:v.NOT_SUPPORTED,message:$({key:w.NOT_SUPPORTED_WEBRTC})});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Ke.getEnv()&&(yield this.schedule(s,n,We));let d=yield i.call(this,e,r,n);return this.roomId=s,this._joinedTimestamp=Ke.performanceNow(),C.emit(S.JOIN_SUCCESS,{room:this}),Ee.uploadEvent({log:`stat-conv-${Number(Rt)}-${location.hostname}`,userId:this.userId}),d}catch(d){throw t.delete({room:this,roomId:s}),C.emit(S.JOIN_FAILED,{room:this,error:d}),d}})}})}var Pb=_(f(),1);var Tl=()=>ce(i=>function(...t){return E(this,null,function*(){C.emit(S.LEAVE_START,{room:this}),yield i.call(this),C.emit(S.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});var Yb=_(f()),gl=_(nt());var kb=_(f()),ge={SETUP_SUCCESS:"1",SETUP_FAILED:"5",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",RECONNECT_FAILED:"4"},qe={DISCONNECTED:"DISCONNECTED",CONNECTING:"CONNECTING",CONNECTED:"CONNECTED"},Dt={CLIENT_BANNED:9,CHANNEL_SETUP_RESULT:19,CHANNEL_RECONNECT_RESULT:514,JOIN_ROOM_RESULT:20,PEER_JOIN:4134,PEER_LEAVE:4135,STREAM_ADDED:16,STREAM_REMOVED:18,UPLINK_NETWORK_STATS:22,UPDATE_REMOTE_MUTE_STAT:23,PUBLISH_RESULT:4098,PUBLISH_STATE_CHANGE_RESULT:4112,UNPUBLISH_RESULT:4100,SUBSCRIBE_RESULT:4102,UNSUBSCRIBE_RESULT:4104,SUBSCRIBE_CHANGE_RESULT:4106,MUTE_RESULT:4108,UPDATE_OFFER_RESULT:4128,START_PUBLISH_TENCENT_CDN_RES:1286,STOP_PUBLISH_TENCENT_CDN_RES:1288,START_PUBLISH_GIVEN_CDN_RES:777,STOP_PUBLISH_GIVEN_CDN_RES:779,START_MIX_TRANSCODE_RES:781,STOP_MIX_TRANSCODE_RES:783,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772,REBUILD_PEER_CONNECTION_RES:4150,SPC_PUBLISH_RESULT:4146,SPC_SUBSCRIBE_RESULT:4156},Sl=[Dt.UPDATE_REMOTE_MUTE_STAT,Dt.UPLINK_NETWORK_STATS,Dt.USER_LIST_RES,Dt.MUTE_RESULT],Z={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",USER_LIST_RES:"user-list-res",SWITCH_ROLE_RES:"switch_role_res",MUTE_RESULT:"mute-result",UPDATE_CONSTRAINT_CONFIG_RES:"update-contraint-config-res",REBUILD_PEER_CONNECTION_RES:"rebuild-pc-res",SPC_PUBLISH_RESULT:"spc-publish-result",SPC_SUBSCRIBE_RESULT:"spc-subscribe-result"},ne={PUBLISH_CHANGE:"publish_change",JOIN_ROOM:"join",LEAVE_ROOM:"leave",ON_QUALITY_REPORT:"quality_report",UPDATE_MUTE_STAT:"mute_uplink",PUBLISH:"publish",PUBLISH_STATE_CHANGE:"publish_state_change",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",RECEIVE_DATA_USER_LIST:"receive_data_userlist",UNSUBSCRIBE:"unsubscribe",SUBSCRIBE_CHANGE:"subscribe_change",START_PUBLISH_TENCENT_CDN:"start_publishing",STOP_PUBLISH_TENCENT_CDN:"stop_publishing",START_PUBLISH_GIVEN_CDN:"start_push_user_cdn",STOP_PUBLISH_GIVEN_CDN:"stop_push_user_cdn",START_MIX_TRANSCODE:"start_mcu_mix",STOP_MIX_TRANSCODE:"stop_mcu_mix",GET_USER_LIST:"get_user_list",SWITCH_ROLE:"change_role",UPDATE_CONSTRAINT_CONFIG:"update_constraint_config",REBUILD_PEER_CONNECTION:"rebuild_pc",READY_TO_RECEIVE_DATA:"ready_to_receive",SPC_JOIN_ROOM:"join/v2",SPC_PUBLISH:"publish/v2",SPC_SUBSCRIBE:"subscribe/v3"};var En=class{constructor(t){p(this,"_room");p(this,"_sdkAppId");p(this,"_userId");p(this,"_userSig");p(this,"_url");p(this,"_backupUrl");p(this,"_urlWithParam");p(this,"_backupUrlWithParam");p(this,"_socketInUse");p(this,"_socket");p(this,"_backupSocket");p(this,"_backupTimer",-1);p(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0});p(this,"_currentState",qe.DISCONNECTED);p(this,"_reconnectionCount",0);p(this,"_reconnectionTimer",-1);p(this,"_seq",0);p(this,"_log");p(this,"_emitter");p(this,"_lastMessageTime",-1);p(this,"_prevTime",-1);this._room=t.room,this._sdkAppId=t.sdkAppId,this._userId=t.userId,this._userSig=t.userSig,this._url=t.url,this._backupUrl=t.backupUrl;let e=`?sdkAppId=${encodeURIComponent(this._sdkAppId)}&userId=${encodeURIComponent(this._userId)}&userSig=${encodeURIComponent(this._userSig)}`;this._urlWithParam=`${this._url}${e}`,this._backupUrlWithParam=`${this._backupUrl}${e}`,this._seq=0,this._log=M.createLogger({id:"ws",userId:this._userId,sdkAppId:this._sdkAppId}),this._emitter=new gl.default}get isConnected(){return this._currentState===qe.CONNECTED}get isConnecting(){return this._currentState===qe.CONNECTING}get isOnline(){return this._currentState===qe.CONNECTED&&Date.now()-this._lastMessageTime<12*1e3}connect(){return new Promise((t,e)=>{this._prevTime<0&&(this._prevTime=q()),this._log.info(`connect to ${this._url}`),this.emitConnectionStateChanged(qe.CONNECTING),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),this.once(ge.CONNECTED,t),this.once(ge.RECONNECT_FAILED,e)})}tryConnectBackup(){this._backupSocket||(this.unbindAndCloseSocket(m.MAIN),this._log.debug(`try to connect to url: ${this._backupUrlWithParam}`),this._backupSocket=new WebSocket(this._backupUrlWithParam),this.bindSocket(this._backupSocket))}bindSocket(t){t.onopen=this.onopen.bind(this),t.onclose=this.onclose.bind(this),t.onerror=this.onerror.bind(this),t.onmessage=this.onmessage.bind(this)}unbindSocket(t){this.clearBackupTimer(),t.onopen=()=>{},t.onclose=()=>{},t.onerror=()=>{},t.onmessage=()=>{}}unbindAndCloseSocket(t){if(t===m.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(e){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(e){}this._backupSocket=null}}clearBackupTimer(){this._backupTimer!==-1&&(clearTimeout(this._backupTimer),this._backupTimer=-1)}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}onopen(t){if(this.isConnected)return;this.isReconnecting&&!this._signalInfo.tinyId&&this.stopReconnection(),this.clearBackupTimer(),t.target===this._socket?(this.unbindAndCloseSocket(m.BACKUP),this._socketInUse=this._socket):(this.unbindAndCloseSocket(m.MAIN),this._socketInUse=this._backupSocket),this.emitConnectionStateChanged(qe.CONNECTED),this._emitter.emit(ge.CONNECTED)}onclose(t){let{url:e}=t.target,r=t.target===this._socketInUse;this._log.info(`websocket[${e} InUse: ${r}] is closed with code: ${t.code}`),t.target===this._socketInUse&&(this.emitConnectionStateChanged(qe.DISCONNECTED),(!t.wasClean||t.code!==1e3)&&(this._log.warn(`onclose code:${t.code} reason:${t.reason}`),this._log.warn("close current websocket and schedule a reconnect timeout"),this._socketInUse.onclose=()=>{},this._socketInUse.close(4011),this._socket=null,this._backupSocket=null,this._socketInUse=null,this.reconnect(m.MAIN)))}onerror(t){let{url:e}=t.target;this._log.error(`websocket[${e}] error observed`),this.isConnected?t.target===this._socketInUse&&(this.unbindAndCloseSocket(m.MAIN),this.unbindAndCloseSocket(m.BACKUP),this._socketInUse=null,this.reconnect(m.MAIN)):(this.isReconnecting||C.emit(S.API_SUCCESS_RATE,{room:this._room,apiName:"WebsocketConnect",error:new Error("ws onerror")}),t.target==this._socket?(this.unbindAndCloseSocket(m.MAIN),this.reconnect(m.BACKUP)):(this.unbindAndCloseSocket(m.BACKUP),this.reconnect(m.MAIN)))}onmessage(t){if(!this.isConnected)return;this._lastMessageTime=Date.now();let e=JSON.parse(t.data),{cmd:r,data:n}=e,s=Object.values(Dt),a=Object.keys(Dt)[s.indexOf(r)],c=Z[a];switch(Sl.includes(r)||(this._log.debug(`received msg: ${t.data}`),this._log.info(`Received event: [ ${c||`unknown cmd: ${r}`} ]`)),r){case Dt.CHANNEL_SETUP_RESULT:{if(e.code===0)this._signalInfo.clientIp=n.clientIp,this._signalInfo.signalIp=n.signalInnerIp,this._signalInfo.tinyId=e.tinyId,n.svrTime&&Kd(n.svrTime),this._log.info("ChannelSetup Success"),C.emit(S.API_SUCCESS_RATE,{room:this._room,apiName:"WebsocketConnect",cost:q()-this._prevTime}),this._prevTime=-1,this._emitter.emit(ge.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let d=new L({code:v.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:e.code,message:$({key:w.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:e.code,errorMsg:e.message}})});this._log.error(`${e.code}, ${e.message}`),this.close(),C.emit(S.API_SUCCESS_RATE,{room:this._room,apiName:"WebsocketConnect",error:d}),this._emitter.emit(ge.SETUP_FAILED,d)}break}case Dt.JOIN_ROOM_RESULT:{e.code===0&&(this._signalInfo.relayIp=n.relayOuterIp,this._signalInfo.relayInnerIp=n.relayInnerIp,this._signalInfo.relayPort=n.relayPort,this._log.info(`signalIp:${this._signalInfo.signalIp} clientIp:${this._signalInfo.clientIp} relayIp: ${this._signalInfo.relayIp}`)),this._emitter.emit(c,{data:e});break}case Dt.CHANNEL_RECONNECT_RESULT:{e.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),C.emit(S.API_SUCCESS_RATE,{room:this._room,apiName:"WebsocketReconnect",cost:q()-this._prevTime}),this._prevTime=-1,this._room.syncUserList(),this._room.checkConnectionsToReconnect()):(this._log.warn(`reconnect failed, ${e.code} ${e.message}`),this._room.reJoin());break}default:this._emitter.emit(c,{data:e});break}}reconnect(t=m.MAIN){if(this.isReconnecting)return;if(this._reconnectionCount>=jn){this._log.warn(`SDK has tried reconnect signal channel for ${jn} times, but all failed. please check your network`);let n=new L({code:v.SIGNAL_CHANNEL_RECONNECTION_FAILED,message:$({key:w.SIGNAL_CHANNEL_RECONNECTION_FAILED})});C.emit(S.API_SUCCESS_RATE,{room:this._room,apiName:"WebsocketReconnect",error:n}),this._emitter.emit(ge.RECONNECT_FAILED,n);return}this._reconnectionCount++,this._log.warn(`reconnect ${t} [${this._reconnectionCount}/${jn}]`);let e=this.getReconnectionUrl(t);this.emitConnectionStateChanged(qe.CONNECTING),this._prevTime<0&&(this._prevTime=q()),t===m.MAIN?(this._socket=new WebSocket(e),this.bindSocket(this._socket)):(this._backupSocket=new WebSocket(e),this.bindSocket(this._backupSocket));let r=rt(this._reconnectionCount);this._reconnectionTimer=setTimeout(()=>{this._log.warn(`reconnect ${t} timeout(${r/1e3}s), try again`),this.clearReconnectionTimer(),this.unbindAndCloseSocket(m.MAIN),this.unbindAndCloseSocket(m.BACKUP),this.reconnect(t===m.MAIN?m.BACKUP:m.MAIN)},r)}get isReconnecting(){return this._reconnectionTimer!==-1}getReconnectionUrl(t){let e=t===m.MAIN?this._urlWithParam:this._backupUrlWithParam;if(this._signalInfo.tinyId&&e.indexOf("&rc=1")===-1){let{roomId:r,useStringRoomId:n}=this._room;e+=`&rc=1&relayInnerIp=${this._signalInfo.relayInnerIp}&relayOuterIp=${this._signalInfo.relayIp}&relayPort=${this._signalInfo.relayPort}&roomId=${r}&useStringRoomId=${n}`}return e}send(t,e={}){if(this.isConnected){let r={cmd:t,data:e,userId:this._userId,tinyId:this._signalInfo.tinyId,seq:++this._seq};return this._socketInUse.send(JSON.stringify(r)),r.seq}}sendWaitForResponse({command:t,data:e,timeout:r=5e3,responseCommand:n,commandDesc:s,enableLog:o=!0}){return new Promise((a,c)=>{let d=setTimeout(()=>{this.off(n,u);let h=new L({code:v.API_CALL_TIMEOUT,message:$({key:w.API_CALL_TIMEOUT,data:{commandDesc:s,command:t}})});o&&this._log.warn(h),c(h)},r),u=h=>{h.data.seq===l&&(clearTimeout(d),this.off(n,u),a(h))};this.on(n,u);let l=this.send(t,e)})}sendWaitForResponseWithRetry(t){let{commandDesc:e,command:r,retries:n=0,retryTimeout:s=0}=t;return vt({retryFunction:this.sendWaitForResponse,onRetrying:o=>{this._log.warn(`${e||r} timeout observed, retrying [${o}/${n}]`)},settings:{retries:n,timeout:s},context:this})(t)}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={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0},this._socketInUse=null,this.unbindAndCloseSocket(m.MAIN),this.unbindAndCloseSocket(m.BACKUP),this.emitConnectionStateChanged(qe.DISCONNECTED)}on(t,e,r){this._emitter.on(t,e,r)}removeListener(t,e,r){this._emitter.removeListener(t,e,r)}once(t,e,r){this._emitter.once(t,e,r)}off(t,e,r){this._emitter.off(t,e,r)}emitConnectionStateChanged(t){t!==this._currentState&&(this._log.info(`${this._currentState} -> ${t}`),this._emitter.emit(ge.CONNECTION_STATE_CHANGED,{prevState:this._currentState,state:t}),this._currentState=t)}};var XD=_(f());var gD=_(f()),Il=_(nt());var rD=_(f());var qb=_(f(),1),Tn=class{constructor(t,e=!1){this.dataView=t;this.isSEI&&(e?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let t=this.seiPayloadStartIndex,e=this.dataView.byteLength-2,r=[],n=0;for(let o=t;o<=e;o++){let a=this.dataView.getInt8(o);switch(a){case 0:case 1:case 2:case 3:n===2&&(r.push(3),n=0),a==0?n++:n=0,r.push(a);break;default:n=0,r.push(a);break}}r.push(this.dataView.getInt8(this.dataView.byteLength-1));let s=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,t),...r]).buffer);this.dataView=s}removePreventionByte(){let t=this.seiPayloadStartIndex,e=this.dataView.byteLength-1,r=[],n=0;for(let o=t;o<=e;o++)switch(this.dataView.getInt8(o)){case 0:n++,r.push(this.dataView.getInt8(o));break;case 3:n!==2&&r.push(this.dataView.getInt8(o)),n=0;break;default:r.push(this.dataView.getInt8(o)),n=0;break}let s=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,t),...r]).buffer);this.dataView=s}get isSEI(){return this.dataView.getUint8(4)===6}get seiPayloadStartIndex(){let t=6;for(let e=6;e<this.dataView.buffer.byteLength&&(t++,this.dataView.getUint8(e)===255);e++);return t}get seiPayloadType(){return this.isSEI?this.dataView.getUint8(5):null}get seiPayload(){if(!this.isSEI)return null;let t=0,e=6;for(let s=6;s<this.dataView.buffer.byteLength;s++){let o=this.dataView.getUint8(s);if(e++,o===255)t+=255;else{t+=o;break}}let r=new ArrayBuffer(t),n=new DataView(r);for(let s=0;s<r.byteLength;s++,e++)n.setInt8(s,this.dataView.getInt8(e));return n}};var _c=class{constructor(t,e,r){this._connection=t;this._log=e;this._isUplink=r;p(this,"_seiMessageList",[]);p(this,"_seiPayloadType",243);p(this,"_mainVideoSenderOrReceiver",null);p(this,"_mainVideoAbortController",null);p(this,"_abortMap",new Map);p(this,"onSEIMessage")}get isRunning(){return!!this._mainVideoAbortController}start(t){this._mainVideoSenderOrReceiver=t;let e=t.createEncodedStreams(),r=e.readable,n=e.writable,s=new TransformStream({transform:this._isUplink?this.encodeVideoFrame.bind(this):this.decodeVideoFrame.bind(this)});this._mainVideoAbortController=new AbortController,r.pipeThrough(s).pipeTo(n,this._mainVideoAbortController).catch(()=>{})}restart(t){this.stop(),this.start(t)}stop(){var t;(t=this._mainVideoAbortController)==null||t.abort(),this._mainVideoAbortController=null}destroy(){this.stop(),this._abortMap.forEach(t=>t.abort()),this._abortMap.clear(),this._log=null,this.onSEIMessage=null,this._mainVideoSenderOrReceiver=null,this._connection=null}handleEncodedStreams(){try{let t=this._connection.getPeerConnection();this.clearUnusedSenderOrReceiver(t),this._isUplink?t.getSenders().forEach((e,r)=>{if(r===1){if(e===this._mainVideoSenderOrReceiver)return;this.isRunning?this.restart(e):this.start(e)}else{if(this._abortMap.has(e))return;this.pipeSenderOrReceiver(e)}}):t.getReceivers().forEach((e,r)=>{var n;this._abortMap.has(e)||e===this._mainVideoSenderOrReceiver||(r===1&&((n=e.track)==null?void 0:n.kind)===m.VIDEO?this.isRunning?this.restart(e):this.start(e):this.pipeSenderOrReceiver(e))})}catch(t){this._log.warn(t)}}pipeSenderOrReceiver(t){let{readable:e,writable:r}=t.createEncodedStreams(),n=new AbortController;this._abortMap.set(t,n),e.pipeTo(r,n).catch(()=>{})}clearUnusedSenderOrReceiver(t){this._abortMap.forEach((e,r)=>{(this._isUplink?t.getSenders():t.getReceivers()).find(s=>s===r)||(e.abort(),this._abortMap.delete(r))})}push(t,e){e&&e.seiPayloadType&&(this._seiPayloadType=e.seiPayloadType),this._seiMessageList.push(t)}hasSEI(t){let e=new DataView(t);return e.getInt32(0)===1&&e.getInt8(4)===6}isEmptyFrame(t){return t.type==="empty"||t.data.byteLength===0}getNaluCount(t){let e=0,r=0,n=new DataView(t);for(let s=0;s<t.byteLength;s++)switch(n.getUint8(s)){case 0:e++;break;case 1:(e===2||e===3)&&r++,e=0;break;default:e=0;break}return r}encodeVideoFrame(t,e){try{if(this._connection.isH264&&this._seiMessageList.length>0&&!this.isEmptyFrame(t)){let n=9-this.getNaluCount(t.data);if(n<=0)return;let s=this._seiMessageList.splice(0,n).reverse().map(this.encodeSEINalu.bind(this)),o=s.reduce((l,h)=>l+h.dataView.byteLength,0),a=new ArrayBuffer(o+t.data.byteLength),c=new DataView(a),d=new DataView(t.data),u=0;for(let l=0;l<s.length;l++)for(let h=0;h<s[l].dataView.byteLength;h++)c.setInt8(u++,s[l].dataView.getInt8(h));for(let l=0;l<t.data.byteLength;l++)c.setInt8(u++,d.getInt8(l));t.data=a,this._log.debug(`${s.length} sei sent`)}}catch(r){this._log.warn(r)}e.enqueue(t)}decodeVideoFrame(t,e){try{if(this._connection.isH264&&!this.isEmptyFrame(t)&&this.hasSEI(t.data)){let r=[],n=new DataView(t.data),s=0,o=-1,a=-1;for(let c=0;c<t.data.byteLength;c++){let d=n.getUint8(c);if(d===0)s++;else if(d===1){if(s===2||s===3){let u=c-s;if(o===-1?o=u:a===-1&&(a=u,r.push(new Tn(new DataView(n.buffer.slice(o,a)))),o=u,a=-1),!(n.getUint8(c+1)===6)){t.data=new DataView(n.buffer.slice(u)).buffer;break}}s=0}else s=0}this._log.debug(`${r.length} sei received`),ue(this.onSEIMessage)&&r.reverse().forEach(c=>{this.onSEIMessage({seiPayloadType:c.seiPayloadType,data:c.seiPayload.buffer})})}}catch(r){this._log.warn(r)}e.enqueue(t)}encodeSEINalu(t){let e=t.byteLength,r=parseInt(e/255),n=e%255,s=[];s.push(0,0,0,1,6,this._seiPayloadType);for(let a=0;a<r;a++)s.push(255);s.push(n);let o=new DataView(t);return s.push(...new Uint8Array(o.buffer)),s.push(128),new Tn(new DataView(new Uint8Array(s).buffer),!0)}},Fs=_c;var fc=0,Ec=!1,Gs=new Set,D_=i=>fc>2&&!Ec&&Gs.size===0&&i,Tc=!1,Qe=class{constructor(t){p(this,"userId");p(this,"tinyId");p(this,"_sdpSemantics");p(this,"_isUplink");p(this,"_room");p(this,"_log");p(this,"_signalChannel");p(this,"_isErrorObserved",!1);p(this,"_waitForPeerConnectionConnectedPromise");p(this,"_waitForPeerConnectionConnectedPromiseReject",null);p(this,"_peerConnection",null);p(this,"_emitter",new Il.default);p(this,"_currentState","DISCONNECTED");p(this,"_isReconnecting",!1);p(this,"_reconnectionCount",0);p(this,"_reconnectionTimer",-1);p(this,"_isFirstConnection",!0);p(this,"_prevTime",-1);p(this,"_enableSEI");p(this,"_sei");p(this,"_localAddress");p(this,"_remoteAddress");this.userId=t.userId,this.tinyId=t.tinyId,this._room=t.room,this._sdpSemantics=t.room.sdpSemantics,this._isUplink=t.isUplink,this._log=M.createLogger({id:"n",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=t.signalChannel,this._enableSEI=t.enableSEI,this._enableSEI&&ui&&(this._sei=new Fs(this,this._log,this._isUplink))}beforeConnect(){this._prevTime<0&&(this._prevTime=q())}afterConnect(t){return E(this,null,function*(){try{yield t,this._isFirstConnection?(this._isFirstConnection=!1,C.emit(S.API_SUCCESS_RATE,{room:this._room,apiName:"PeerConnectionConnect",cost:Math.min(q()-this._prevTime,30*1e3)})):this._isReconnecting&&C.emit(S.API_SUCCESS_RATE,{room:this._room,apiName:"PeerConnectionReconnect",cost:q()-this._prevTime}),this._prevTime=-1}catch(e){throw this._isFirstConnection?(this._isFirstConnection=!1,C.emit(S.API_SUCCESS_RATE,{room:this._room,apiName:"PeerConnectionConnect",error:e})):this._isReconnecting&&this._reconnectionCount>=3&&C.emit(S.API_SUCCESS_RATE,{room:this._room,apiName:"PeerConnectionReconnect",error:e}),e}})}initialize(){let t={encodedInsertableStreams:this._enableSEI&&ui,iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"};this._peerConnection=new RTCPeerConnection(t),this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this)}close(t){this._log.info("close connection"),this._emitter.emit("closed",t),this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this._sei&&(this._sei.destroy(),this._sei=null),Gs.delete(this)}closePeerConnection(t=!1){this._peerConnection&&(this._log.info("close pc"),this._peerConnection.onconnectionstatechange=null,this._peerConnection.close(),this._peerConnection=null,t&&this.emitConnectionStateChangedEvent("DISCONNECTED")),this._waitForPeerConnectionConnectedPromiseReject&&this._waitForPeerConnectionConnectedPromiseReject(new L({code:v.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return St;let t=null;if(this._isUplink){if(!nr()||this._peerConnection.getSenders().length===0)return St;t=this._peerConnection.getSenders()[0].transport}else{if(!vi()||this._peerConnection.getReceivers().length===0)return St;t=this._peerConnection.getReceivers()[0].transport}return t?t.state:St}onConnectionStateChange(t){let e=this._peerConnection.iceConnectionState,r=this.getDTLSTransportState();if(this._log.info(`connectionState: ${t.target.connectionState}, ICE: ${e}, DTLS: ${r}`),t.target.connectionState===fe.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),t.target.connectionState===fe.FAILED||t.target.connectionState===fe.CLOSED){let n=`connection ${t.target.connectionState}. ICE Transport state: ${e}, DTLS Transport state: ${r}`,s=new L({message:n,code:v.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",s)}(t.target.connectionState===fe.CONNECTED||t.target.connectionState===fe.COMPLETED)&&(this.logSelectedCandidate(),Ee.logSuccessEvent({userId:this._room.userId,eventType:Lt.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(t){return t===this._currentState?!1:(t==="CONNECTED"?(fc=0,Ec=!1,Tc=!0,Gs.add(this)):Gs.delete(this),C.emit(S.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:t,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:t}),this._currentState=t,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}logSelectedCandidate(){return E(this,null,function*(){if(!this._peerConnection)return;let t=yield this._peerConnection.getStats();for(let[,e]of t)if(ci(e)){let r=t.get(e.localCandidateId),n=t.get(e.remoteCandidateId);r&&(this._log.info(`local candidate: ${r.candidateType} ${r.protocol}:${r.ip||r.address}:${r.port} ${r.networkType||""} ${r.candidateType==="relay"?`relayProtocol:${r.relayProtocol}`:""}`),this._localAddress=`${r.ip||r.address}:${r.port}`),n&&(this._log.info(`remote candidate: ${n.candidateType} ${n.protocol}:${n.ip||n.address}:${n.port}`),this._remoteAddress=`${n.protocol}:${n.ip||n.address}`);break}})}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise?this._waitForPeerConnectionConnectedPromise:(this._waitForPeerConnectionConnectedPromise=new Promise((t,e)=>{if(this._currentState==="CONNECTED")return t();this._waitForPeerConnectionConnectedPromiseReject=e;let r=a=>{a.state==="CONNECTED"&&(clearTimeout(o),s(),t())},n=({room:a})=>{a===this._room&&(clearTimeout(o),s(),e(new L({code:v.API_CALL_ABORTED,message:$({key:w.CONNECTION_ABORTED,data:"leave room"})})))},s=()=>{C.off(S.LEAVE_SUCCESS,n,this),this._emitter.off("connection-state-changed",r,this)},o=setTimeout(()=>{s();let a=new L({code:v.API_CALL_TIMEOUT,message:"connection timeout"});fc+=1,D_(this._signalChannel.isConnected)&&(this._log.warn("firewall restrition"),Ec=!0,this._emitter.emit("firewall-restriction")),e(a)},Jn);C.on(S.LEAVE_SUCCESS,n,this),this._emitter.on("connection-state-changed",r,this)}),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally(()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null}),this._waitForPeerConnectionConnectedPromise)}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(ge.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=ti()){this._log.warn(`SDK has tried reconnect for ${this._reconnectionCount} times, but all failed, please check your network`),this.stopReconnection();let t=new L({code:this._isUplink?v.UPLINK_RECONNECTION_FAILED:v.DOWNLINK_RECONNECTION_FAILED,message:$({key:this._isUplink?w.UPLINK_RECONNECTION_FAILED:w.DOWNLINK_RECONNECTION_FAILED})});return this.emitConnectionStateChangedEvent("DISCONNECTED"),this._emitter.emit("error",t),-1}return this._signalChannel.isConnected?(this._reconnectionCount+=1,this._log.warn(`reconnect() trying [${this._reconnectionCount}]`),1):(this._log.warn("reconnect() signal channel is not connected, suspend reconnection until signal is connected"),this._signalChannel.once(ge.CONNECTED,this.reconnect,this),-1)}on(t,e,r){this._emitter.on(t,e,r)}off(t,e,r){this._emitter.off(t,e,r)}getIsReconnecting(){return this._isReconnecting}get isH264(){var t,e;return!!((e=(t=this._peerConnection)==null?void 0:t.remoteDescription)!=null&&e.sdp.includes("H264"))}};var PD=_(f()),Rc=_(Ic());var Re=function(i){return Rc.default.parse(i)},ct=function(i){return Rc.default.write(i)},Dl=function(i){let t=Re(i);return t.media.forEach(e=>{e.type===m.AUDIO&&e.fmtp.forEach(r=>{r.config+=";sprop-stereo=1;stereo=1"})}),ct(t)};function Ol(i){let t=Re(i);return t.media.forEach(e=>{var r,n;if(e.type===m.VIDEO){let s=new Set;e.rtp.forEach(({payload:a,codec:c})=>c==="H264"&&s.add(a)),e.fmtp.forEach(({payload:a,config:c})=>{let d=c.match(/apt=(\d+)/);d&&d[1]&&s.has(Number(d[1]))&&s.add(a)});let o=({payload:a})=>!s.has(a);e.rtp=e.rtp.filter(o),e.rtcpFb=(r=e.rtcpFb)==null?void 0:r.filter(o),e.fmtp=e.fmtp.filter(o),e.payloads=(n=e.payloads)==null?void 0:n.split(" ").filter(a=>!s.has(Number(a))).join(" ")}}),ct(t)}var LD=_(f());function Ws(i){return Object.keys(i).filter(t=>i[t])}var Cc=class extends Qe{constructor(e){super(te(B({},e),{isUplink:!1}));p(this,"_flag",0);p(this,"role","anchor");p(this,"remoteAudioTrack");p(this,"remoteVideoTrack");p(this,"remoteAuxiliaryTrack");p(this,"ssrc",{audio:0,video:0,auxiliary:0});p(this,"_isSDPExchanging",!1);this.flag=e.flag,this.remoteAudioTrack=e.remoteAudioTrack||new ur(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new Mi(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new lr(this._room,this)}get subscribeState(){let e={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(this.remoteVideoTrack.mediaType&8?e.smallVideo=!0:e.video=!0),this.remoteAudioTrack.isSubscribed&&(e.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(e.auxiliary=!0),e}get muteState(){return oi(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var r,n,s;e!==this._flag&&(this._flag=e,(r=this.remoteAudioTrack)==null||r.onFlagChanged(),(n=this.remoteVideoTrack)==null||n.onFlagChanged(),(s=this.remoteAuxiliaryTrack)==null||s.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===m.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var s,o;let r=this._currentState,n=super.emitConnectionStateChangedEvent(e);return n&&r!==e&&((s=this.remoteVideoTrack)==null||s.emit("connection-state-changed",{prevState:r,state:e}),(o=this.remoteAuxiliaryTrack)==null||o.emit("connection-state-changed",{prevState:r,state:e})),n}onTrack(e){let r=e.streams[0],{track:n}=e,s=r.id===Wn?m.MAIN:m.AUXILIARY;this._log.debug(`ontrack ${s} ${n.kind}`);let o=m.AUDIO;n.kind===m.VIDEO&&(o=s===m.MAIN?m.VIDEO:m.AUXILIARY);let a=this.remoteAudioTrack;o===m.VIDEO?a=this.remoteVideoTrack:o===m.AUXILIARY&&(a=this.remoteAuxiliaryTrack),a.setMediaStream(r),a.setMediaStreamTrack(n)}addRRTRLine(e){let r=e.split(`\r
88
+ `,r.onclick=this.onQuestionClick.bind(this);let n=document.createElement("div");n.className=Ha,n.innerText=`${Nt()?"\u8BE6\u60C5 >":"Detail >"}`,n.onclick=this.onCollapseClick.bind(this);let s=t.content.firstChild,o=s.querySelector(`.${Js}`);return o.appendChild(n),o.appendChild(r),o.appendChild(e),s}addDiaLog(){Wa()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${Or}`).onclick=t=>t.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",O.info("show autoplay dialog"),_e.uploadEvent({log:D_}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){O.warn("confirm clicked, try resume stream"),C.emit(S.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let t=this._dialogNode.querySelector(`.${Vu}`);t.style.visibility=`${this._showDetail?"hidden":"visible"}`,t.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||_e.uploadEvent({log:O_}),this._isCollapseClicked=!0}onQuestionClick(){window.open(Hu,"_blank"),this._isQuestionClicked||_e.uploadEvent({log:P_}),this._isQuestionClicked=!0}},Fu=Fa;var Pr={};Jr(Pr,{create:()=>ct,remove:()=>He});var kS=_(f(),1),kn=new WeakMap;function ct(i,t){kn.has(i)||kn.set(i,[]);let e=kn.get(i),n={add:(s,o)=>("addEventListener"in t?(e.push(t.removeEventListener.bind(t,s,o)),t.addEventListener(s,o)):(e.push(t.off.bind(t,s,o)),t.on(s,o)),n)};return n}function He(i){let t=kn.get(i);t&&(t.forEach(e=>e()),kn.delete(i))}var Kt=class extends he{constructor(e,r){super(e.id,`${r}-player`);this.kind=r;p(this,"id");p(this,"element",null);p(this,"container",null);p(this,"mediaStream",new MediaStream);p(this,"track");p(this,"url");p(this,"attr");p(this,"muted");p(this,"_log");p(this,"_pausedRetryCount");p(this,"_isElementPlayingFired",!1);p(this,"_interval");this.id=e.id,this._log=e.log,this.track=e.track,this.container=e.container,this.muted=e.muted,this._pausedRetryCount=Sa,this._state="STOPPED",this.bindTrackEvents()}get isPlaying(){return this._state==="PLAYING"}get isStopped(){return this._state==="STOPPED"}setAttr(e){this.attr=e}setTrack(e){if(e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(Pt.MEDIA_TRACK_CHANGED,e),e!==null&&(this.bindTrackEvents(),this.element))){let r=new MediaStream;r.addTrack(e),this.element.srcObject=r}}setUrl(e){this.track&&(this.unbindTrackEvents(),this.element&&(this.element.srcObject=null),this.track=null),e!==this.url&&(this.url=e,e!==null&&this.element&&(this.element.crossOrigin="anonymous",this.element.src=e))}setContainer(e){this.container=e,this.track&&this.element&&this.container&&this.container.appendChild(this.element)}play(){return E(this,null,function*(){if(this.element&&this.element.parentElement!==this.container&&this.container&&this.container.append(this.element),!this.isPlaying)try{this.bindAutoPlayEvent(),yield this.element.play()}catch(e){let r=B({key:V.PLAY_FAILED,data:{media:this.kind,error:e}});if(this.track&&!this.track.muted&&this._log.warn(e),r.includes("NotAllowedError"))throw new M({code:v.PLAY_NOT_ALLOWED,message:r})}})}stop(){this.unbindEvents(),this._isElementPlayingFired=!1,this.element&&(this.container&&this.container.removeChild(this.element),this.element.srcObject=null,this.element=null),this.handleStopped(m.ENDED),this._interval>0&&me.clearTask(this._interval)}pause(){var e;this.isPlaying&&((e=this.element)==null||e.pause())}resume(){return this.isPlaying?Promise.resolve():Ni?this.replay():this.play().catch(()=>{})}setMuted(e){this.element&&(this.element.muted=e),this.muted=e}setRect(e,r){this.element&&(this.element.style.width=`${e}px`,this.element.style.height=`${r}px`)}replay(){return this.stop(),this.play().catch(()=>{})}bindElementEvents(){if(this.element){let e=this.handleElementEvent.bind(this);ct(this.element,this.element).add(m.PLAYING,e).add(m.ENDED,e).add(m.PAUSE,e).add(m.ERROR,e).add(m.LOADEDDATA,e)}}bindTrackEvents(){if(this.track){let e=this.handleTrackEvent.bind(this);Pr==null||Pr.create(this.track,this.track).add(m.ENDED,e).add(m.MUTE,e).add(m.UNMUTE,e),this.track.readyState===m.ENDED&&this.handleTrackEvent({type:m.ENDED}),this.track.muted&&this.handleTrackEvent({type:m.MUTE})}}bindAutoPlayEvent(){C.on(S.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(){this.track&&He(this.track)}unbindEvents(){this.element&&He(this.element),this.unbindTrackEvents(),C.off(S.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){var n;switch(e.type){case m.PLAYING:this._isElementPlayingFired=!0,this._log.info(`${this.kind} player is playing`),this.handlePlaying(m.PLAYING),this._interval&&(me.clearTask(this._interval),this._interval=-1);break;case m.ENDED:this._log.info(`${this.kind} player is ended`),this.handleStopped(m.ENDED);break;case m.PAUSE:this._log.info(`${this.kind} player is paused`),this.handlePaused(m.PAUSE);let s=this.container&&document.getElementById(this.container.id);s||this._log.warn(`${this.kind} player has been remove, element ID: ${(n=this.container)==null?void 0:n.id}`);let o=mr();this._pausedRetryCount>0&&(this.kind===m.VIDEO&&!Wa()||this.kind===m.AUDIO&&(de(o)&&o<=70||!s))&&(this._log.info(`${this.kind} player auto resume when paused`),this.resume(),this._pausedRetryCount--),nt&&(this._interval=me.run(yr,()=>{this.element&&this._state==="PAUSED"&&this.resume()},{delay:3e3}));break;case m.ERROR:if(this.element&&this.element.error){let{code:a,message:c}=this.element.error;this._log.error(`${this.kind} player error observed. code: ${a} message: ${c} userAgent: ${navigator.userAgent}`),_e.uploadEvent({log:`stat-${this.kind}-${yt.PLAYER_ERROR}-${a}-${navigator.userAgent}`,error:this.element.error})}break;case m.LOADEDDATA:this.kind===m.VIDEO&&this.emit(Pt.LOADED_DATA);break}}handleTrackEvent(e){switch(e.type){case m.ENDED:this._log.info(`${this.kind} track is ended`),this.handleStopped(m.ENDED);break;case m.MUTE:this._log.info(`${this.kind} track is unable to provide media output`),this.handlePaused(m.MUTE);break;case m.UNMUTE:this._log.info(`${this.kind} track is able to provide media output`),this._isElementPlayingFired&&this.handlePlaying(m.UNMUTE);break}}handlePlaying(e){this.emit(Pt.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this.emit(Pt.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this.emit(Pt.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};H([Ke([],"PLAYING")],Kt.prototype,"handlePlaying",1),H([Ke("PLAYING","PAUSED",{ignoreError:!0})],Kt.prototype,"handlePaused",1),H([Ke([],"STOPPED")],Kt.prototype,"handleStopped",1);var Gi=class extends Kt{constructor(e){super(e,m.VIDEO);p(this,"mirror");p(this,"objectFit");b(e.mirror)||(this.mirror=e.mirror),b(e.objectFit)||(this.objectFit=e.objectFit)}initializeElement(){var n;let e=document.createElement(m.VIDEO);if(this.track){let s=new MediaStream;s.addTrack(this.track),e.srcObject=s}e.muted=!0;let r=`width: 100%; height: 100%; object-fit: ${this.objectFit};background-color: black;`;this.mirror&&(r+="transform: scaleX(-1);"),e.setAttribute("id",`video_${this.id}`),e.setAttribute("style",r),e.setAttribute("autoplay","autoplay"),e.setAttribute("playsinline","playsinline"),(n=this.container)==null||n.appendChild(e),this.element=e,this.bindElementEvents()}setAttr(e){let r=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},e);r.style=Object.assign({width:"100%",height:"100%"},r.style),super.setAttr(r)}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}play(){return this.element||this.initializeElement(),super.play()}getVideoFrame(){if(!this.element)return"";let e=document.createElement("canvas");return e.width=this.element.videoWidth,e.height=this.element.videoHeight,e.getContext("2d").drawImage(this.element,0,0),e.toDataURL("image/png")}getElement(){return this.element}};var Pg=_(f(),1);var Cg=_(f(),1);var lg=_(f(),1);var L_="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<firstChannel.length;++i){sum+=firstChannel[i]*firstChannel[i]}rms=Math.sqrt(sum/firstChannel.length);this.volume=Math.max(rms,this.volume*0.95);this.tick-=firstChannel.length;if(this.tick<0){this.tick+=(this.intervalTime/1000)*sampleRate;this.port.postMessage({volume:this.volume})}}return true}}registerProcessor('volume-meter',VolumeMeter);",Wu=!1,Ka=class{constructor(t){p(this,"context_");p(this,"blob_");this.context_=t.context,this.blob_=new Blob([L_],{type:"application/javascript"}),this.addModuleToContext()}addModuleToContext(){return E(this,null,function*(){try{yield this.context_.audioWorklet.addModule(URL.createObjectURL(this.blob_)),O.info("worklet addModule success"),C.emit(S.WORKLET_LOADED_SUCCESS),Wu=!0}catch(t){O.info(`worklet addModule catch error. ${t.message}`),C.emit(S.WORKLET_LOADED_FAILED)}})}get initWorkletSuccess(){return Wu}},Ku=Ka;var _g=_(f(),1);typeof window!="undefined"&&(window.AudioContext=window.AudioContext||window.webkitAudioContext||window.mozAudioContext);var Mr=()=>{let i=new window.AudioContext,t=()=>{i.state==="suspended"?(i.resume(),document.addEventListener("click",t)):i.state==="interrupted"?i.resume():document.removeEventListener("click",t)};return document.addEventListener("click",t),i.onstatechange=()=>{O.info(`audioSource context state: ${i.state}`),t()},i};var Et,Xs,zs=0,ja=class{constructor(t){p(this,"_volume");p(this,"_log");p(this,"_track");p(this,"_stream");p(this,"_audioCtx");p(this,"_destination");p(this,"_streamSource");p(this,"_scriptProcessorNode");p(this,"_audioWorkletNode");p(this,"_interval");let{track:e,log:r}=t;this._volume=0,this._log=r,this._track=e,Et||(Et=Mr()),this._audioCtx=Et,this._destination=this._audioCtx.destination;let n=new MediaStream;n.addTrack(this._track),this._streamSource=this._audioCtx.createMediaStreamSource(n),this._audioWorkletNode=null,this._scriptProcessorNode=null,this._interval=200,C.on(S.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this),Aa?(C.on(S.WORKLET_LOADED_SUCCESS,this.initAudioWorklet,this),C.on(S.WORKLET_LOADED_FAILED,this.initScriptProcessor,this),this.preload()):this.initScriptProcessor(),zs+=1}preload(){Xs?Xs.initWorkletSuccess&&this.initAudioWorklet():Xs=new Ku({context:Et})}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(this._audioCtx,"volume-meter"),this._audioWorkletNode.port.onmessage=t=>{this._volume=t.data.volume||0},this._streamSource.connect(this._audioWorkletNode).connect(this._destination),this.handleAudioLevelInterval({interval:this._interval})}catch(t){_e.logFailedEvent({userId:this._log.userId,eventType:yt.LOAD_WORKLET,error:t}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=this._audioCtx.createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=t=>{let e=t.inputBuffer.getChannelData(0),r=0;for(let n=0;n<e.length;++n)r+=e[n]*e[n];this._volume=Math.sqrt(r/e.length)||0},this._streamSource.connect(this._scriptProcessorNode),this._scriptProcessorNode.connect(this._destination)}catch(t){this._log.error(`volumeMeter init script processor error: ${t}`)}}destroy(){this._streamSource&&this._streamSource.disconnect(),this._scriptProcessorNode&&(this._scriptProcessorNode.onaudioprocess=null,this._scriptProcessorNode.disconnect()),this._audioWorkletNode&&(this._audioWorkletNode.port.postMessage({name:"stop"}),this._audioWorkletNode.port.onmessage=null,this._audioWorkletNode.disconnect()),this._audioWorkletNode=null,this._scriptProcessorNode=null,this._audioCtx=null,C.off(S.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this),C.off(S.WORKLET_LOADED_SUCCESS,this.initAudioWorklet,this),C.off(S.WORKLET_LOADED_FAILED,this.initScriptProcessor,this),zs>0&&(zs-=1),zs===0&&(Et==null||Et.close(),Et=null,Xs=null)}resume(){Et==null||Et.resume()}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}handleAudioLevelInterval(t){var r;let{interval:e}=t;this._interval=e,(r=this._audioWorkletNode)==null||r.port.postMessage({name:"setIntervalTime",intervalTime:e})}},ju=ja;var Wi=class extends Kt{constructor(e){super(e,m.AUDIO);p(this,"_volumeMeter");p(this,"gainedTrack");p(this,"_outputDeviceId");p(this,"_volume",1);p(this,"_loop",!1);e.gainedTrack&&(this.gainedTrack=e.gainedTrack),this._outputDeviceId=e.outputDeviceId,this.track&&this.initVolumeMeter(this.track)}setTrack(e){this.track!==e&&(this._volumeMeter&&(this._volumeMeter.destroy(),this._volumeMeter=null),e!==null&&this.initVolumeMeter(e)),super.setTrack(e)}initVolumeMeter(e){this._volumeMeter=new ju({track:this.gainedTrack||e,log:this._log})}initializeElement(){if((vi==="15.2"||vi==="15.3"||vi==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}let r=document.createElement(m.AUDIO);if(this.gainedTrack||this.track){let n=new MediaStream;n.addTrack(this.gainedTrack||this.track),r.srcObject=n}r.muted=this.muted,r.setAttribute("id",`audio_${this.id}`),r.setAttribute("autoplay","autoplay"),r.setAttribute("playsinline","playsinline"),this.element=r,this.bindElementEvents()}play(){return E(this,null,function*(){this.element||this.initializeElement(),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),!this._volumeMeter&&this.track&&this.initVolumeMeter(this.track),this.setVolume(this._volume),yield Ci(Wi.prototype,this,"play").call(this)})}stop(){this._volumeMeter&&(this._volumeMeter.destroy(),this._volumeMeter=null),super.stop()}resume(){return E(this,null,function*(){yield Ci(Wi.prototype,this,"resume").call(this),this._volumeMeter&&this._volumeMeter.resume()})}setSinkId(e){return E(this,null,function*(){this._outputDeviceId!==e&&(this.element&&(yield this.element.setSinkId(e)),this._outputDeviceId=e)})}setVolume(e){!this.element||(this.element.volume=e,this._volume=e)}setLoop(e){!this.element||(this.element.loop=e,this._loop=e)}getAudioLevel(){var e;return((e=this._volumeMeter)==null?void 0:e.getCalculatedVolume())||0}getInternalAudioLevel(){var e;return(e=this._volumeMeter)==null?void 0:e.getInternalAudioLevel()}};var Ki=class extends he{constructor({userId:e,sdkAppId:r,mediaType:n,room:s}){var o;super();p(this,"id",Na());p(this,"userId");p(this,"isRemote");p(this,"mediaType");p(this,"room");p(this,"user");p(this,"_log");p(this,"isPlayCalled");p(this,"mediaTrack",null);p(this,"mediaStream");p(this,"container",null);p(this,"subVideoPlayerMap");p(this,"playerMuted",!1);p(this,"abortCtrl");p(this,"audioOutputDeviceId");p(this,"audioVolume");p(this,"objectFit","cover");p(this,"mirror",!1);p(this,"gain");p(this,"isScreen",!1);b(e)||(this.userId=e),this.mediaType=n,this._log=O.createLogger({id:`${this.kind[0]}t`,userId:(o=s||this.room)==null?void 0:o.userId,remoteUserId:this instanceof Fe?void 0:this.userId,sdkAppId:r,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof Fe}),this.initPlayer()}get log(){return this._log||O}get kind(){return this.mediaType===1?m.AUDIO:m.VIDEO}get muted(){return!!(this.mediaTrack&&!this.mediaTrack.enabled)}get strMediaType(){return this.mediaType===4?m.VIDEO:this.mediaType===2?m.SCREEN:m.AUDIO}uninstallEvents(){}play(e,r){return E(this,null,function*(){let n=Oe(e)?e[0]:e;if(this.isPlayCalled){r&&!b(r.muted)&&this.setPlayerMute(r.muted),r&&!b(r.objectFit)&&(this.objectFit=r.objectFit),this.isScreen?this.mirror=!1:r&&!b(r.mirror)&&(this.mirror=r.mirror),this.kind===m.VIDEO&&(this.player.setObjectFit(this.objectFit),this.player.setMirror(this.mirror),this.container!==n&&n&&(this.container=n,this.player.setContainer(n)),Oe(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),r)));return}if((!this.isRemote||this.kind===m.VIDEO)&&this.setPlayerMute(!0),r&&!b(r.muted)&&this.setPlayerMute(r.muted),r&&!b(r.objectFit)&&(this.objectFit=r.objectFit),this.isRemote||(this.mirror=!0),this.isScreen?this.mirror=!1:r&&!b(r.mirror)&&(this.mirror=r.mirror),this.kind===m.VIDEO&&(this.player.setObjectFit(this.objectFit),this.player.setMirror(this.mirror)),this.isPlayCalled=!0,n&&(this.container=n,this.player.setContainer(n)),C.emit(S.PLAY_TRACK_START,{track:this}),!!this.mediaTrack){this._log.info(`play with options: ${JSON.stringify(r)}`);try{yield this.player.play(),Oe(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),r))}catch(s){throw this.handleAutoPlayFailed(),this.emit("error",s),s}}})}playSubContainer(e,r){return E(this,null,function*(){if(!this.mediaTrack||this.kind===m.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((s,o)=>{var a;e.find(c=>o===c)||(s.stop(),s.setContainer(null),(a=this.subVideoPlayerMap)==null||a.delete(o))});for(let[s,o]of e.entries()){let a=this.subVideoPlayerMap.get(o);a?r&&(b(r.mirror)||a.setMirror(r.mirror),b(r.objectFit)||a.setObjectFit(r.objectFit)):this.subVideoPlayerMap.set(o,new Gi({id:this.userId||this.id,track:this.mediaTrack,container:o,muted:this.playerMuted,objectFit:this.objectFit,mirror:this.mirror,log:this.log.createChild({id:`vp-sub${s+1}`})}))}let n=[...this.subVideoPlayerMap.values()];for(let s of n)yield s.play()})}initPlayer(){var e;this.log.info(`create ${this.kind}Player`),this.kind===m.AUDIO?this.player=new Wi({id:this.userId||this.id,track:this.mediaTrack,gainedTrack:(e=this.gain)==null?void 0:e.audioTrack,container:this.container||null,muted:this.playerMuted,outputDeviceId:this.audioOutputDeviceId,log:this.log}):(this.player=new Gi({id:this.userId||this.id,track:this.mediaTrack,container:this.container||null,muted:this.playerMuted,objectFit:this.objectFit,mirror:this.mirror,log:this.log}),this.player.on(Pt.LOADED_DATA,()=>{C.emit(S.VIDEO_LOADED_DATA,{track:this})}),this.player.on(Pt.MEDIA_TRACK_CHANGED,r=>{var n;(n=this.subVideoPlayerMap)==null||n.forEach(s=>s.setTrack(r))})),this.player.on(Pt.PLAYER_STATE_CHANGED,r=>{C.emit(S.PLAYER_STATE_CHANGED,w({track:this},r)),this.emit("player-state-changed",r)})}setAudioOutput(e){return E(this,null,function*(){var r;this.audioOutputDeviceId=e,yield(r=this.player)==null?void 0:r.setSinkId(e)})}setAudioVolume(e){var r;this.audioVolume=e,this.log.info(`setAudioVolume to ${e}`),(r=this.player)==null||r.setVolume(e)}getAudioLevel(){var e;return((e=this.player)==null?void 0:e.getAudioLevel())||0}getInternalAudioLevel(){var e;return((e=this.player)==null?void 0:e.getInternalAudioLevel())||0}stop(){!this.isPlayCalled||(this.isPlayCalled=!1,this.player&&(this.log.info(`stop ${this.kind} player`),this.player.stop(),this.player.setContainer(null)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(e=>{e.stop(),e.setContainer(null)}),this.container=null)}resume(){return E(this,null,function*(){var e;!this.isPlayCalled||(yield(e=this.player)==null?void 0:e.resume())})}close(){var e;this.log.info("close"),this.isPlayCalled&&this.stop(),!this.isRemote&&((e=this.mediaTrack)==null||e.stop(),this.mediaTrack=null,this.uninstallEvents())}setMute(e){return this.mediaTrack?(this.mediaTrack.enabled=!e,this.emit(e?"mute":"unmute",this),C.emit(e?S.TRACK_MUTED:S.TRACK_UNMUTED,{track:this}),!0):!1}setPlayerMute(e){this.playerMuted=e,this.player.setMuted(e)}setMediaStream(e){e!==this.mediaStream&&(this.mediaStream=e)}setMediaStreamTrack(e){this.mediaStream||(this.mediaStream=new MediaStream),this.mediaTrack&&this.mediaStream.removeTrack(this.mediaTrack);let r=this.mediaTrack;this.mediaTrack=e,this.mediaTrack&&(this.mediaTrack.enabled=!this.muted,this.mediaStream.addTrack(this.mediaTrack),this.isRemote||this.player.setTrack(this.mediaTrack)),this.updatePlayingState(!!e),this.emit("media-track-changed",this.mediaTrack,r)}setMediaType(e){this.mediaType=e}updatePlayingState(e){if(!(!this.isPlayCalled||e&&!this.player.isStopped||!e&&this.player.isStopped)&&this.isPlayCalled&&this.player.isStopped===e){if(this.log.info(`playing state updated, ${e?"play":"stop"} ${this.kind}`),e&&this.player.isStopped){if(this instanceof Ye&&(!this.isSubscribed||!this.hasFlag))return;this.player.play().catch(()=>this.handleAutoPlayFailed())}!e&&!this.player.isStopped&&this.player.stop()}}handleAutoPlayFailed(){if(this.room&&this.room.enableAutoPlayDialog)new Fu;else{let e=()=>{this.resume().then(()=>{document.removeEventListener("click",e,!0),document.removeEventListener("touchstart",e,!0)})};document.addEventListener("click",e,!0),document.addEventListener("touchstart",e,!0)}}};H([Ke([],he.INIT)],Ki.prototype,"close",1);var LI=_(f(),1);var pI=_(f(),1);var k_=Object.prototype.hasOwnProperty,{toString:uI}=Object.prototype;function x_(i){if(i==null)return!0;if(typeof i=="boolean")return!1;if(typeof i=="number")return i===0;if(typeof i=="string"||typeof i=="function"||Array.isArray(i))return i.length===0;if(i instanceof Error)return i.message==="";if(Ht(i))switch(Object.prototype.toString.call(i)){case"[object File]":case"[object Map]":case"[object Set]":return i.size===0;case"[object Object]":{for(let t in i)if(k_.call(i,t))return!1;return!0}}return!1}var jt=x_;var EI=_(f(),1),Yu=_(rt(),1);var Ju=i=>t=>t.deviceId===i;var xn=class{constructor(t,e="Input"){p(this,"kind");p(this,"type");p(this,"devices",[]);this.kind=t,this.type=e}update(t,e){let r=t.filter(n=>n.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);e&&(r.forEach(n=>{if(n.deviceId&&!this.devices.find(Ju(n.deviceId))){let s=`${this.kind}${this.type}Added`;O.warn(`${s}: ${JSON.stringify(n)}`),e.emit(s,n)}}),this.devices.forEach(n=>{if(n.deviceId&&!r.find(Ju(n.deviceId))){let s=`${this.kind}${this.type}Removed`;O.warn(`${s}: ${JSON.stringify(n)}`),e.emit(s,n)}})),this.devices=r}hasDevice(t){return!!this.devices.find(e=>e.deviceId===t)}},Ya=class extends Yu.EventEmitter{constructor(){super();p(this,"audioInputs",new xn(m.AUDIO));p(this,"videoInputs",new xn(m.VIDEO));p(this,"audioOutputs",new xn(m.AUDIO,"Output"));this.init(),navigator.mediaDevices&&navigator.mediaDevices.addEventListener("devicechange",this.update.bind(this))}init(){qs().then(e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)})}update(){return E(this,null,function*(){let e=yield qs();return this.audioInputs.update(e,this),this.videoInputs.update(e,this),this.audioOutputs.update(e,this),this})}},Te=mn||Tr?null:new Ya;function qs(){return E(this,null,function*(){return Oa()||!Fs()?[]:(yield navigator.mediaDevices.enumerateDevices()).map((t,e)=>{let r={kind:t.kind,deviceId:t.deviceId,groupId:t.groupId,label:t.label||`${t.kind}_${e}`};return t.deviceId.length>0&&Xa.add(`${t.deviceId}_${t.kind}`),t.getCapabilities&&(r.getCapabilities=()=>t.getCapabilities()),r})})}function Xe(){return Te.update().then(i=>i.audioInputs.devices)}function dt(){return Te.update().then(i=>i.videoInputs.devices)}function Lr(){return E(this,null,function*(){return Te.update().then(i=>i.audioOutputs.devices)})}var Xa=new Set;function Xu(i){if(i instanceof CanvasCaptureMediaStreamTrack||!(i instanceof MediaStreamTrack))return!1;let t=i.label.toLocaleLowerCase();if(t.includes("camera")||t.includes("webcam"))return!0;let r=`${((i==null?void 0:i.getSettings())||{}).deviceId}_${m.VIDEO_INPUT}`;return!!Xa.has(r)}function zu(i){if(i instanceof CanvasCaptureMediaStreamTrack||!(i instanceof MediaStreamTrack))return!1;let t=i.label.toLocaleLowerCase();if(t.includes("mic")||t.includes("\u9EA6\u514B\u98CE"))return!0;let r=`${((i==null?void 0:i.getSettings())||{}).deviceId}_${m.AUDIO_INPUT}`;return!!Xa.has(r)}function za(i,t){return E(this,null,function*(){let r=(yield Xe()).find(n=>n.deviceId===Ui);return(r==null?void 0:r.groupId)===i&&r.label===t})}function qu(s){return E(this,arguments,function*({newDeviceId:i,oldDeviceId:t,oldGroupId:e,oldLabel:r,kind:n}){return i!==t?!1:n===m.AUDIO&&i===Ui?yield za(e,r):!0})}var U_=function(i){return E(this,null,function*(){let t=w_(i);O.info(`getUserMedia with constraints: ${JSON.stringify(t)}`);let e=[],r=[];t.audio&&(e=yield Xe(),O.info(`microphones: ${$i(e,["label","deviceId"])}`)),t.video&&(r=yield dt(),O.info(`cameras: ${$i(r,["label","deviceId"])}`));try{let n=yield navigator.mediaDevices.getUserMedia(t);return ka&&n.getTracks().forEach(s=>{O.info(`${s.kind} capabilities: ${$i(s.getCapabilities(),Vs)}`)}),n}catch(n){if(n.name==="NotFoundError"){if(r&&r.length===0)throw new M({code:v.DEVICE_NOT_FOUND,message:B({key:V.CAMERA_NOT_FOUND})});if(e&&e.length===0)throw new M({code:v.DEVICE_NOT_FOUND,message:B({key:V.MICROPHONE_NOT_FOUND})})}throw new M({code:v.INITIALIZE_FAILED,name:n.name,message:n.message,constraint:n.constraint})}})},V_=Dt({retryFunction:U_,settings:{retries:3,timeout:500},onError:(i,t,e,r)=>{i.name==="NotReadableError"?(r[0].video&&(r[0].maxResolution=!1,r[0].frameRate&&(r[0].frameRate=r[0].frameRate>10?10:5)),t()):e(i),r[0].microphoneId&&Qu(r[0].microphoneId,!1),r[0].cameraId&&Qu(r[0].cameraId,!0)},onRetrying:i=>{O.warn(`getUserMedia NotReadableError observed, retrying [${i}/3]`)}});function Qu(i,t){return E(this,null,function*(){let r=(t?yield dt():yield Xe()).find(n=>n.deviceId===i);r&&ce(r.getCapabilities)&&O.warn($i(r.getCapabilities(),Vs))})}function w_(i){return{audio:B_(i),video:$_(i)}}function B_(i){if(!i.audio)return!1;let t={};return jt(i.microphoneId)||(t.deviceId=i.useExact?{exact:i.microphoneId}:i.microphoneId),de(i.channelCount)&&i.channelCount>1&&(t.channelCount=i.channelCount),Ne(i.echoCancellation)&&!i.echoCancellation&&(t.echoCancellation=!1),Ne(i.noiseSuppression)&&!i.noiseSuppression&&(t.noiseSuppression=!1),Ne(i.autoGainControl)&&!i.autoGainControl&&(t.autoGainControl=!1),jt(t)?!0:t}function $_(i){if(!i.video)return!1;let{maxResolution:t=!0}=i,e={};return i.cameraId?e.deviceId=i.useExact?{exact:i.cameraId}:i.cameraId:i.facingMode&&(e.facingMode=i.facingMode),i.width&&(e.width={ideal:i.width},t&&(e.width.max=i.width)),i.height&&(e.height={ideal:i.height},t&&(e.height.max=i.height)),ue&&Ct&&i.width&&i.height&&i.width*i.height<352*288&&(e.width=i.width,e.height=i.height),i.frameRate&&(e.frameRate=i.frameRate),jt(e)?!0:e}var Zu=V_;var UI=_(f(),1);function Qs(i){return ae((t,e)=>function(...r){return E(this,null,function*(){return yield i.apply(this,r),t.apply(this,r)})})}function Zs(i){return ae((t,e)=>function(...r){return E(this,null,function*(){return i.call(this,t.apply(this,r))})})}function ae(i){return function(t,e,r){return r.value=i(r.value,e),r}}var Fe=class extends Ki{constructor(e){super({mediaType:e});p(this,"isRemote",!1);p(this,"deviceId");p(this,"groupId","");p(this,"label","");p(this,"_isRecapturing",!1);p(this,"_lastRecaptureTime",0);p(this,"_onMuteTimeoutId",-1);this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this)}installTrackEvent(e){e.addEventListener(m.MUTE,this.onTrackMuted),e.addEventListener(m.UNMUTE,this.onTrackUnmuted),e.addEventListener(m.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===m.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){e.removeEventListener(m.MUTE,this.onTrackMuted),e.removeEventListener(m.UNMUTE,this.onTrackUnmuted),e.removeEventListener(m.ENDED,this.onTrackEnded)}setStateToCapture(){}capture(e){return E(this,null,function*(){try{C.emit(S.LOCAL_TRACK_CAPTURE_START,{track:this});let r;e.customSource?(r=new MediaStream,r.addTrack(e.customSource)):r=yield Zu(e);let n=r.getTracks()[0];return this.setMediaStream(r),this.setMediaStreamTrack(n),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),C.emit(S.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this}),r}catch(r){throw C.emit(S.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:r}),this.log.error(`getUserMedia error observed ${r}`),r}})}setMediaStreamTrack(e){this.state===he.INIT&&this.setStateToCapture(),this.mediaTrack&&this.uninstallTrackEvent(this.mediaTrack),super.setMediaStreamTrack(e),e&&this.installTrackEvent(e)}setPublishStarting(e){this.room=e}setPublishStarted(){}setPublishStopped(e,r){}publish(e){this.room=e,this.userId=e.userId,this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),C.emit(S.LOCAL_TRACK_PUBLISHED,{track:this}),this.setPublishStarted()}unpublish(){this.room=void 0,this.mediaType===2&&(this.mediaType=4),C.emit(S.LOCAL_TRACK_UNPUBLISHED,{track:this}),this.setPublishStopped("api-call")}get isPublishing(){return this.state==="publish"}updateDeviceIdInUse(){return E(this,null,function*(){if(this.mediaTrack&&Ft){let{deviceId:e,groupId:r}=this.mediaTrack.getSettings(),{label:n}=this.mediaTrack;(yield qu({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=n,r&&(this.groupId=r),qs().then(o=>{let a=o.find(c=>c.deviceId===e);a&&this.emit("2",a)}))}})}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(e=!1){return!(!this.deviceId||!this.mediaTrack||this.kind===m.AUDIO&&!zu(this.mediaTrack)||this.kind===m.VIDEO&&!Xu(this.mediaTrack)||this._isRecapturing||e&&Ct&&ht)}onTrackMuted(){if(!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<Cr){setTimeout(()=>this.onTrackMuted(),Cr);return}this._onMuteTimeoutId=setTimeout(()=>E(this,null,function*(){var e;((e=this.mediaTrack)==null?void 0:e.muted)&&document.visibilityState==="visible"&&this.recapture(yield this.getRecoverCaptureDeviceId())}),5e3)}}onTrackUnmuted(){this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return E(this,null,function*(){if(!!this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<Cr){setTimeout(()=>this.onTrackEnded(),Cr);return}this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e){return E(this,null,function*(){var s;if(this._isRecapturing||!this.mediaTrack)return;let r;return this.log.warn("recapture trying"),(s=this.mediaTrack)==null||s.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now(),(this.kind==="audio"?yield Xe():yield dt()).find(o=>o.deviceId===e)&&(r=e),this.capture({deviceId:r,useExact:!0}).then(()=>{var o;return(o=this.room)==null?void 0:o.replaceTrack(this)}).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId})}).catch(o=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${o.message}`),this.emit("5",o)})})}getRecoverCaptureDeviceId(){return E(this,null,function*(){let{deviceId:e}=this;if(e){let r=(Un.get(e)||0)+1;if(Un.set(e,r),r>=3){let n=this.kind==="video"?(yield dt()).find(s=>!Un.has(s.deviceId)):(yield Xe()).find(s=>!Un.has(s.deviceId));n&&(this.log.warn(`${e} capture fail ${r} times, change new ${n.deviceId}`),e=n.deviceId)}}return e})}};H([Ke(he.INIT,"capture")],Fe.prototype,"setStateToCapture",1),H([Ke("capture","publish_starting",{success(){this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"})}})],Fe.prototype,"setPublishStarting",1),H([Ke("publish_starting","publish",{success(){this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"})}})],Fe.prototype,"setPublishStarted",1),H([ae(i=>function(t,e){let r=this.state.oldState||this.state;i.call(this,t,e),r!=="capture"&&this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:this.state.oldState==="publish_starting"?"starting":"started",reason:t,error:e})}),Ke(["publish","publish_starting"],"capture",{ignoreError:!0})],Fe.prototype,"setPublishStopped",1);var Un=new Map;C.on(S.SWITCH_DEVICE_SUCCESS,i=>{i.track.deviceId&&Un.delete(i.track.deviceId)});var mR=_(f(),1);var Jt=class extends Fe{constructor(){super(1);p(this,"mediaType",1);p(this,"volume",0);p(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40});p(this,"playerMuted",!0)}getAudioLevel(){return this.volume||super.getAudioLevel()}capture({deviceId:e,useExact:r=!1}={}){return super.capture({video:!1,audio:!0,microphoneId:e,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExact:r})}switchDevice(e){return E(this,null,function*(){if(!(!this.mediaStream||!this.mediaTrack)){if(this.deviceId===e)if(e===Ui){if(yield za(this.groupId,this.label))return}else return;try{this.log.info(`switchDevice audio to: ${e}`),this.mediaTrack&&this.mediaTrack.stop(),yield this.capture({deviceId:e,useExact:!0}),this.room&&(yield this.room.replaceTrack(this)),C.emit(S.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(r){throw this.log.error(`switch microphone failed ${r}`),this.deviceId&&this.recapture(this.deviceId),r}}})}listenDeviceChange(){Te&&!Te.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&Te.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return E(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current microphone is lost: ${JSON.stringify(e)}`);let r=yield Xe();r[0]?this.recapture(r[0].deviceId):Te.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){return E(this,null,function*(){this.log.warn(`microphone added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)})}close(){Te.off("audioInputAdded",this.handleMicrophoneAdded,this),Te.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}};var NR=_(f(),1);var St=class extends Fe{constructor(){super(4);p(this,"mediaType",4);p(this,"profile",{width:640,height:480,frameRate:15,bitrate:900});p(this,"states",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0});p(this,"small");p(this,"facingMode");p(this,"_canvas");p(this,"_canvasInterval");p(this,"canvasTrack")}capture({deviceId:e,facingMode:r,useExact:n=!1,customSource:s}={}){return super.capture({audio:!1,video:!0,facingMode:r||this.facingMode,cameraId:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExact:n,customSource:s})}genCanvasTrack(){if(this.canvasTrack||!this.mediaTrack)return;this.log.info("gen canvas track");let{width:e,height:r,frameRate:n}=this.mediaTrack.getSettings();this._canvas=document.createElement("canvas");let s=this._canvas.getContext("2d");e&&r&&(this._canvas.width=e,this._canvas.height=r),this._canvasInterval=me.run($t,()=>{if(!this._canvas)return;if(this.mediaTrack){let c=this.mediaTrack.getSettings();(c.width!==this._canvas.width||c.height!==this._canvas.height)&&(this._canvas.width=c.width,this._canvas.height=c.height)}let a=this.player.getElement();a&&(s==null||s.drawImage(a,0,0,this._canvas.width,this._canvas.height))},{fps:Math.max(15,n||0)});let o=this._canvas.captureStream();this.canvasTrack=o.getVideoTracks()[0]}destoryCanvasTrack(){this._canvasInterval&&(me.clearTask(this._canvasInterval),this._canvasInterval=void 0,this._canvas=void 0,this.canvasTrack=void 0)}setPublishStarting(e){super.setPublishStarting(e),this.isNeedToResetVideoProfile(this.profile)&&this.setProfile(this.profile)}setMediaStreamTrack(e){super.setMediaStreamTrack(e),this.isNeedToResetVideoProfile(this.profile)&&this.setProfile(this.profile)}setProfile(e){var n;if(!e)return;let r=e.bitrate&&e.bitrate!==this.profile.bitrate;return this.isNeedToResetVideoProfile(e)&&(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),e.width=1920,e.height=1080),super.setProfile(e),(n=this.mediaTrack)==null?void 0:n.applyConstraints({width:e.width,height:e.height,frameRate:e.frameRate}).then(()=>{if(r&&this.room&&this.room.setBandWidth)return this.room.setBandWidth({bandwidth:e.bitrate,type:m.VIDEO,videoType:m.BIG})})}isNeedToResetVideoProfile(e){return!!(this.room&&this.room.scheduleResult&&!((this.room.scheduleResult.trtcAutoConf||{})["2k4k"]===1)&&!this.isScreen&&e.height*e.width>=2560*1440)}switchDevice(e){return E(this,null,function*(){try{if(!this.mediaStream||this.deviceId===e||this.facingMode===e)return;(e===m.FACING_MODE_USER||e===m.FACING_MODE_ENVIRONMENT)&&(this.facingMode=e,e=void 0),this.mediaTrack&&this.mediaTrack.stop(),yield this.capture({deviceId:e,useExact:!0}),this.room&&(yield this.room.replaceTrack(this)),C.emit(S.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(r){throw this.log.error(`switch camera failed ${r}`),this.deviceId&&this.recapture(this.deviceId),r}})}listenDeviceChange(){Te&&!Te.listeners("audioInputRemoved").includes(this.handleCameraRemoved)&&Te.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return E(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current camera is lost: ${JSON.stringify(e)}`);let r=yield dt();r[0]?this.recapture(r[0].deviceId):Te.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return E(this,null,function*(){this.log.warn(`camera added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)})}close(){Te.off("videoInputAdded",this.handleCameraAdded,this),Te.off("videoInputRemoved",this.handleCameraRemoved,this),this.destoryCanvasTrack(),super.close()}};var $R=_(f(),1);var LR=_(f(),1);var F_=function(i){return E(this,null,function*(){let t=null,e=W_(i);O.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let r=yield navigator.mediaDevices.getDisplayMedia(e);if(i.systemAudio&&r.getAudioTracks().length===0&&(_r&&fr<74||ht||ue)&&O.warn("Your browser not support capture system audio"),i.frameRate&&r.getVideoTracks()[0]&&r.getVideoTracks()[0].applyConstraints({frameRate:{min:i.frameRate,ideal:i.frameRate}}).catch(n=>{O.warn(`screen applyConstraints failed: ${n}`)}),i.audio){let n=G_(i);O.info(`getUserMedia with constraints: ${JSON.stringify(n)}`),t=yield navigator.mediaDevices.getUserMedia(n),r.addTrack(t.getAudioTracks()[0])}return r})};function G_(i){let t={echoCancellation:i.echoCancellation,autoGainControl:i.autoGainControl,noiseSuppression:i.noiseSuppression,sampleRate:i.sampleRate,channelCount:i.channelCount};return b(i.microphoneId)||(t.deviceId=i.microphoneId),{audio:t,video:!1}}function W_(i){let t={systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:ht?{max:i.width}:{ideal:i.width,max:i.width},height:ht?{max:i.height}:{ideal:i.height,max:i.height},frameRate:i.frameRate,displaySurface:"monitor"};if(t.video=e,i.systemAudio){let{echoCancellation:r=!0,noiseSuppression:n=!1,autoGainControl:s=!1}=i;t.audio={echoCancellation:r,noiseSuppression:n,autoGainControl:s,sampleRate:48e3}}return t}var tl=F_;var Mt=class extends St{constructor(){super();p(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600});p(this,"objectFit","contain");p(this,"isScreen",!0);this._log.id=`s-${this._log.id}`}capture(){return E(this,arguments,function*({systemAudio:e=!1,autoGainControl:r,echoCancellation:n,noiseSuppression:s,audioTrack:o,videoTrack:a}={}){try{let c;return a||o?(c=new MediaStream,a&&c.addTrack(a),o&&c.addTrack(o)):c=yield tl({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:r,echoCancellation:n,noiseSuppression:s}),this.setMediaStream(c),this.setMediaStreamTrack(c.getVideoTracks()[0]),c}catch(c){throw this.log.error(`getDisplayMedia error observed ${c}`),c instanceof M?c:new M({code:v.INITIALIZE_FAILED,name:c.name,message:c.message})}})}switchDevice(e){return E(this,null,function*(){throw new Error("Method not implemented.")})}};var WR=_(f(),1);var ji=class extends Jt{constructor(){super(),this._log.id=`s-${this._log.id}`}setScreenAudioTrack(t,e){this.setMediaStream(e),this.setMediaStreamTrack(t)}};var nA=_(f(),1);var qR=_(f(),1);var Vn=class extends Fe{constructor(e){super(1);p(this,"musicId");p(this,"mediaType",1);p(this,"volume",0);p(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40});p(this,"playerMuted",!1);p(this,"_audioContext");p(this,"_destination");p(this,"_source",null);this.initAudioContext(),this._destination=this._audioContext.createMediaStreamDestination(),this._destination.channelCount=1,this.setPlayerMute(!1),this.player.initializeElement(),this.player.setUrl(e.url),Ne(e.loop)&&this.player.setLoop(e.loop),de(e.volume)&&this.player.setVolume(e.volume),e.id&&(this.musicId=e.id),this._source=this._audioContext.createMediaElementSource(this.player.getElement()),this._source.connect(this._destination),this.setMediaStream(this._destination.stream)}initAudioContext(){this._audioContext=Mr(),this._audioContext.state!=="running"&&this._log.warn(`local music ${this.musicId} context state: ${this._audioContext.state}`)}destroy(){var e,r;(e=this._source)==null||e.disconnect(),(r=this._destination)==null||r.disconnect(),this.player.stop(),this._audioContext.close().then(()=>{this._source=null,this._destination=null,this._audioContext=null})}getStream(){var e;return((e=this._destination)==null?void 0:e.stream)||null}setPosition(e){if(e<0&&e>this.duration()){O.warn("Time beyond song duration.");return}this.player&&this.player.getElement()&&(this.player.getElement().currentTime=e)}getPosition(){var e;if(this.player)return((e=this.player.getElement())==null?void 0:e.currentTime)||0}setVolume(e){if(e>1&&e<0){this.log.warn("volume is out of range");return}this.player.setVolume(e)}getVolume(){let e=this.player.getElement();return(e==null?void 0:e.volume)||0}setPlayBackRate(e){if(e>8&&e<0){this.log.warn("rate is out of range");return}let r=this.player.getElement();r&&(r.playbackRate=e)}getPlayBackRate(){let e=this.player.getElement();return(e==null?void 0:e.playbackRate)||0}duration(){let e=this.player.getElement();return(e==null?void 0:e.duration)||0}loop(e){let r=this.player.getElement();return r&&Ne(e)&&(r.loop=e),(r==null?void 0:r.loop)||!1}setOperation(e){e==="pause"&&this.player.pause(),e==="resume"&&this.player.resume(),e==="stop"&&this.player.stop()}listenDeviceChange(){}};var eo=class{constructor({room:t}){p(this,"audioContext",null);p(this,"_destination",null);p(this,"_localAudioTrack",null);p(this,"_localScreenAudioTrack",null);p(this,"_localMediaStreamAudioTrack",null);p(this,"_audioTrackStreamSource",null);p(this,"_screenAudioTrackStreamSource",null);p(this,"_mixedMusicSet",new Set);p(this,"hasMusic",!1);p(this,"mixedMusicMap",new Map);p(this,"cacheMusicMap",new Map);p(this,"_log");p(this,"_originTrack",null);this._log=O.createLogger({id:"am",userId:t.userId,sdkAppId:t.sdkAppId}),this.initAudioContext()}get hasScreenAudioTrack(){return this._localScreenAudioTrack!==null}get hasAudioTrack(){return this._localAudioTrack!==null}get isMixed(){return(this.hasMusic?1:0)+(this._localAudioTrack?1:0)+(this._localScreenAudioTrack?1:0)>=1}get mediaStreamTrack(){return this._destination.stream.getAudioTracks()[0]}addMusicSource(t){return E(this,null,function*(){this._log.info(`add music source, id: ${t.id} url: ${t.url}`),this.initAudioContext();let{id:e,url:r,loop:n,volume:s}=t;if(this.mixedMusicMap.has(e))return;let o;this.cacheMusicMap.has(e)?o=this.cacheMusicMap.get(e).localMusicTrack:o=new Vn(t);let{stream:a}=o._destination,c=document.createElement("audio");c.srcObject=a,o.play(),yield c.play(),this._log.info(`start mix audio ${e} success.`);let d=this.audioContext.createMediaStreamSource(a),u=this.audioContext.createGain();return d.connect(u),u.connect(this._destination),this._mixedMusicSet.add(e),this.mixedMusicMap.set(e,{localMusicTrack:o,streamSource:d,gainNode:u,audioPlayer:c}),this.cacheMusicMap.set(e,{localMusicTrack:o}),this.hasMusic=!0,o})}updateMusicSource(t){return E(this,null,function*(){let{id:e,volume:r,loop:n,operation:s}=t;if(this._log.info(`update music source, id: ${t.id} operation: ${s}`),this.mixedMusicMap.has(e)){let{localMusicTrack:o}=this.mixedMusicMap.get(e);b(r)||o.setVolume(r),b(n)||o.loop(n),b(s)||o.setOperation(s)}})}addAudioTrack(t){return E(this,null,function*(){var r;if(this._log.info(`start add audioTrack, userId: ${t.userId}`),this.initAudioContext(),!(t!=null&&t.mediaStream))return;if(this._localMediaStreamAudioTrack===t.mediaTrack){this._log.info("addAudioTrack duplicate.");return}let e=yield(r=t.mediaTrack)==null?void 0:r.getSettings();this._destination.channelCount=(e==null?void 0:e.channelCount)||1,this._localAudioTrack=t,this._localMediaStreamAudioTrack=t.mediaTrack,this._audioTrackStreamSource=this.audioContext.createMediaStreamSource(t.mediaStream),this._audioTrackStreamSource.connect(this._destination)})}removeAudioTrack(t){var e,r,n,s;this._localAudioTrack===t&&(this._log.info(`start remove audioTrack, userId: ${t.userId}`),(e=this._audioTrackStreamSource)==null||e.disconnect(),(r=this._localMediaStreamAudioTrack)==null||r.stop(),this._localMediaStreamAudioTrack=null,(n=this._localAudioTrack)==null||n.stop(),this._localAudioTrack=null),this._localScreenAudioTrack===t&&(this._log.info(`start remove screenTrack, userId: ${t.userId}`),(s=this._screenAudioTrackStreamSource)==null||s.disconnect(),this._localScreenAudioTrack.stop(),this._localScreenAudioTrack=null)}addScreenAudioTrack(t){this._log.info(`start add screenAudioTrack, userId: ${t.userId}`),this.initAudioContext(),!!(t!=null&&t.mediaStream)&&this._localScreenAudioTrack!==t&&(this._localScreenAudioTrack=t,this._screenAudioTrackStreamSource=this.audioContext.createMediaStreamSource(t.mediaStream),this._screenAudioTrackStreamSource.connect(this._destination))}removeAudioTrackSource(t){var e,r;this._log.info(`remove audio track source, type: ${t}`),t==="main"&&((e=this._audioTrackStreamSource)==null||e.disconnect(),this._audioTrackStreamSource=null,this._localAudioTrack=null),t==="screen"&&((r=this._screenAudioTrackStreamSource)==null||r.disconnect(),this._screenAudioTrackStreamSource=null,this._localScreenAudioTrack=null)}removeMusicSource({id:t}){if(this.mixedMusicMap.has(t)){this._log.info(`start remove music source, music id: ${t}`);let{localMusicTrack:e,streamSource:r,gainNode:n,audioPlayer:s}=this.mixedMusicMap.get(t);r.disconnect(),n.disconnect(),s.pause(),s.srcObject=null,e.stop(),this.mixedMusicMap.delete(t),this._mixedMusicSet.delete(t),this._mixedMusicSet.size===0&&(this.hasMusic=!1)}t==="*"&&this.destroyAllMusic()}destroyAllMusic(){this._log.info("destroy all music source."),this._mixedMusicSet.forEach(t=>{this.removeMusicSource({id:t})})}destroyAllCache(){this._log.info("destroy all music cache."),this.cacheMusicMap.forEach(t=>{t.localMusicTrack.stop()})}initAudioContext(){this.audioContext||(this.audioContext=Mr(),this.audioContext.state!=="running"&&this._log.warn(`context state: ${this.audioContext.state}`),this._destination=this.audioContext.createMediaStreamDestination(),this._destination.channelCount=1)}initDenoiser(s){return E(this,arguments,function*({assetsPath:t,sdkAppId:e,userId:r,userSig:n}){})}enableDenoiser(t){return E(this,null,function*(){})}disableDenoiser(){return E(this,null,function*(){})}destroy(){this.removeAudioTrackSource("main"),this.removeAudioTrackSource("aux"),this.audioContext.close(),this.destroyAllMusic(),this.destroyAllCache()}};var CA=_(f(),1);var fA=_(f(),1);var qa=class extends Ki{constructor(e,r,n){super({userId:r.userId,sdkAppId:e.sdkAppId,mediaType:n,room:e});this.room=e;this.user=r;p(this,"userId");p(this,"tinyId");p(this,"isRemote",!0);this.tinyId=r.tinyId,this.userId=r.userId}play(e,r){return this.hasFlag?super.play(e,r):(this.isPlayCalled=!0,this.container=e,e&&this.player.setContainer(e),Promise.resolve())}setMute(e){return this.hasFlag&&super.setMute(e)}setMediaStreamTrack(e){super.setMediaStreamTrack(e),this.mediaTrack&&this.hasFlag&&this.isSubscribed&&this.player.setTrack(this.mediaTrack)}get isSubscribed(){return this.state===qa.STATE_SUBSCRIBE}get streamType(){return(this.mediaType&2)===0?"main":"auxiliary"}subscribe(e=!0){this.mediaTrack&&this.hasFlag&&this.player.setTrack(this.mediaTrack),e&&C.emit(S.REMOTE_TRACK_SUBSCRIBED,{track:this})}unsubscribe(e=!0){this.player.setTrack(null),e&&C.emit(S.REMOTE_TRACK_UNSUBSCRIBED,{track:this}),this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}onFlagChanged(){this.updatePlayingState(this.hasFlag),this.mediaTrack&&this.hasFlag&&this.player.setTrack(this.mediaTrack)}},Ye=qa;p(Ye,"STATE_SUBSCRIBE","subscribe"),H([Ke(he.INIT,Ye.STATE_SUBSCRIBE,{success(){this.updatePlayingState(!0)}})],Ye.prototype,"subscribe",1),H([Ke(Ye.STATE_SUBSCRIBE,he.INIT,{success(){this.updatePlayingState(!1)}})],Ye.prototype,"unsubscribe",1);var kr=class extends Ye{constructor(e,r){super(e,r,1);p(this,"volume",0);p(this,"mediaType",1);p(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0})}getAudioLevel(){return this.volume||super.getAudioLevel()}get hasFlag(){return this.user.muteState.hasAudio&&!this.user.muteState.audioMuted}isFlagChanged(e){let r=e.hasAudio&&!e.audioMuted;return this.hasFlag||(this.volume=0),this.hasFlag!==r}};var PA=_(f(),1);var Ji=class extends Ye{constructor(e,r,n=4){super(e,r,n);p(this,"mediaType",4);p(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0})}changeType(e){this.room.changeType(e,this.user)}get hasFlag(){return this.user.muteState.hasVideo&&!this.user.muteState.videoMuted}isFlagChanged(e){let r=e.hasVideo&&!e.videoMuted;return this.hasFlag!==r}},xr=class extends Ji{constructor(e,r){super(e,r,2);p(this,"mediaType",2);p(this,"objectFit","contain")}get hasFlag(){return this.user.muteState.hasAuxiliary}isFlagChanged(e){let r=e.hasAuxiliary;return this.hasFlag!==r}};var ZC=_(f(),1);var UC=_(f());var kA=_(f());function ye(...i){}var K_=i=>i();function Za(){this.dispose()}var j_=()=>typeof __FASTRX_DEVTOOLS__!="undefined",J_=1,Yt=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(t){let e=new Qa(t,this,this.streamId++);return gt.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},wn=class{constructor(){this.defers=new Set,this.disposed=!1}next(t){}complete(){this.dispose()}error(t){this.dispose()}get bindDispose(){return()=>this.dispose()}dispose(){this.disposed=!0,this.complete=ye,this.error=ye,this.next=ye,this.dispose=ye,this.subscribe=ye,this.doDefer()}subscribe(t){return t instanceof Yt?t.subscribe(this):t(this),this}get bindSubscribe(){return t=>this.subscribe(t)}doDefer(){this.defers.forEach(K_),this.defers.clear()}defer(t){this.defers.add(t)}removeDefer(t){this.defers.delete(t)}reset(){this.disposed=!1,delete this.complete,delete this.next,delete this.dispose,delete this.next,delete this.subscribe}resetNext(){delete this.next}resetComplete(){delete this.complete}resetError(){delete this.error}},Y=class extends wn{constructor(t){super(),this.sink=t,t.defer(this.bindDispose)}next(t){this.sink.next(t)}complete(){this.sink.complete()}error(t){this.sink.error(t)}};function il(i,...t){return t.reduce((e,r)=>r(e),i)}function Xt(i,t,e){if(j_()){let r=Object.defineProperties(Object.setPrototypeOf(i,Yt.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:t,writable:!0,configurable:!0},args:{value:e,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});gt.create(r);for(let n=0;n<e.length;n++){let s=e[n];typeof s=="function"&&s instanceof Yt&&gt.addSource(r,s)}return r}return i}function Z(i,t){return function(...e){return r=>{if(r instanceof Yt){let n=Xt(s=>{let o=new i(s,...e);o.sourceId=n.id,o.subscribe(r)},t,arguments);return n.source=r,gt.pipe(n),n}else return n=>r(new i(n,...e))}}}function fi(i,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:i,payload:t}})}var Qa=class extends Y{constructor(t,e,r){super(t),this.source=e,this.id=r,this.sourceId=t.sourceId,this.defer(()=>{gt.defer(this.source,this.id)})}next(t){gt.next(this.source,this.id,t),this.sink.next(t)}complete(){gt.complete(this.source,this.id),this.sink.complete()}error(t){gt.complete(this.source,this.id,t),this.sink.error(t)}},gt={addSource(i,t){fi("addSource",{id:i.id,name:i.toString(),source:{id:t.id,name:t.toString()}})},next(i,t,e){fi("next",{id:i.id,streamId:t,data:e&&e.toString()})},subscribe({id:i,end:t},e){fi("subscribe",{id:i,end:t,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(i,t,e){fi("complete",{id:i.id,streamId:t,err:e?e.toString():null})},defer(i,t){fi("defer",{id:i.id,streamId:t})},pipe(i){fi("pipe",{name:i.toString(),id:i.id,source:{id:i.source.id,name:i.source.toString()}})},update(i){fi("update",{id:i.id,name:i.toString()})},create(i){i.id||(i.id=J_++),fi("create",{name:i.toString(),id:i.id})}},to=class extends Error{constructor(t){super(`timeout after ${t}ms`),this.timeout=t}};var WA=_(f());var $A=_(f());var ec=class extends wn{constructor(t){super(),this.source=t,this.sinks=new Set}add(t){t.defer(()=>this.remove(t)),this.sinks.add(t).size===1&&(this.reset(),this.subscribe(this.source))}remove(t){this.sinks.delete(t),this.sinks.size===0&&this.dispose()}next(t){this.sinks.forEach(e=>e.next(t))}complete(){this.sinks.forEach(t=>t.complete()),this.sinks.clear()}error(t){this.sinks.forEach(e=>e.error(t)),this.sinks.clear()}};function io(){return i=>{let t=new ec(i);if(i instanceof Yt){let e=Xt(r=>{t.add(r)},"share",arguments);return t.sourceId=e.id,e.source=i,gt.pipe(e),e}return Xt(t.add.bind(t),"share",arguments)}}function Y_(...i){return Xt(t=>{let e=i.length,r=e,n=e,s=new Array(e),o=()=>{--n===0&&t.complete()},a=(c,d)=>{let u=new Y(t);u.next=l=>{--r===0?(u.next=h=>{s[d]=h,t.next(s)},u.next(l)):s[d]=l},u.complete=o,u.subscribe(c)};i.forEach(a)},"combineLatest",arguments)}var tc=class extends Y{constructor(t,...e){super(t);let r=new Y(this.sink);r.next=n=>this.buffer=n,r.complete=ye,r.subscribe(Y_(...e))}next(t){this.buffer&&this.sink.next([t,...this.buffer])}},UA=Z(tc,"withLatestFrom"),ic=class extends Y{constructor(t,e,r){super(t),this.bufferSize=e,this.startBufferEvery=r,this.buffer=[],this.count=0,this.startBufferEvery&&(this.buffers=[[]])}next(t){this.startBufferEvery?(this.count++===this.startBufferEvery&&(this.buffers.push([]),this.count=1),this.buffers.forEach(e=>{e.push(t)}),this.buffers[0].length===this.bufferSize&&this.sink.next(this.buffers.shift())):(this.buffer.push(t),this.buffer.length===this.bufferSize&&(this.sink.next(this.buffer),this.buffer=[]))}complete(){this.buffer.length?this.sink.next(this.buffer):this.buffers.length&&this.buffers.forEach(t=>this.sink.next(t)),super.complete()}},VA=Z(ic,"bufferCount"),rc=class extends Y{constructor(t,e){super(t),this.buffer=[];let r=new Y(t);r.next=n=>{t.next(this.buffer),this.buffer=[]},r.complete=ye,r.subscribe(e)}next(t){this.buffer.push(t)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},wA=Z(rc,"buffer");function nc(i){let t=arguments,e=io()(Xt(r=>{e.next=n=>r.next(n),e.complete=()=>r.complete(),e.error=n=>r.error(n),i&&r.subscribe(i)},"subject",t));return e.next=ye,e.complete=ye,e.error=ye,e}function rl(i){return Xt(t=>{let e=0,r=setInterval(()=>t.next(e++),i);return t.defer(()=>{clearInterval(r)}),"interval"},"interval",arguments)}var uC=_(f());var JA=_(f());var sc=class extends Y{constructor(t,e,r){super(t),this.f=e;let n=()=>{this.sink.next(this.acc),this.sink.complete()};typeof r=="undefined"?this.next=s=>{this.acc=s,this.complete=n,this.resetNext()}:(this.acc=r,this.complete=n)}next(t){this.acc=this.f(this.acc,t)}},X_=Z(sc,"reduce");var oc=class extends Y{constructor(t,e,r){super(t),this.filter=e,this.thisArg=r}next(t){this.filter.call(this.thisArg,t)&&this.sink.next(t)}},z_=Z(oc,"filter"),ac=class extends Y{next(t){}},QA=Z(ac,"ignoreElements"),cc=class extends Y{constructor(t,e){super(t),this.count=e}next(t){this.sink.next(t),--this.count===0&&this.complete()}},q_=Z(cc,"take"),dc=class extends Y{constructor(t,e){super(t);let r=new Y(t);r.next=()=>t.complete(),r.complete=Za,r.subscribe(e)}},ZA=Z(dc,"takeUntil"),uc=class extends Y{constructor(t,e){super(t),this.f=e}next(t){this.f(t)?this.sink.next(t):this.complete()}},Q_=Z(uc,"takeWhile");var lc=class extends Y{constructor(t,e){super(t),this.count=e}next(t){--this.count===0&&(this.next=super.next)}},eC=Z(lc,"skip"),pc=class extends Y{constructor(t,e){super(t),t.next=ye;let r=new Y(t);r.next=()=>{r.dispose(),t.resetNext()},r.complete=Za,r.subscribe(e)}},tC=Z(pc,"skipUntil"),hc=class extends Y{constructor(t,e){super(t),this.f=e}next(t){this.f(t)||(this.next=super.next,this.next(t))}},Z_=Z(hc,"skipWhile"),ef={leading:!0,trailing:!1},mc=class extends Y{constructor(t,e,r){super(t),this.durationSelector=e,this.trailing=r}cacheValue(t){this.last=t,this.disposed&&this.throttle(t)}send(t){this.sink.next(t),this.throttle(t)}throttle(t){this.reset(),this.subscribe(this.durationSelector(t))}next(){this.complete()}complete(){this.dispose(),this.trailing&&this.send(this.last)}},_c=class extends Y{constructor(t,e,r=ef){super(t),this.durationSelector=e,this.config=r,this._throttle=new mc(this.sink,this.durationSelector,this.config.trailing),this._throttle.dispose()}next(t){this._throttle.disposed&&this.config.leading?this._throttle.send(t):this._throttle.cacheValue(t)}complete(){this._throttle.throttle=ye,this._throttle.complete(),super.complete()}},iC=Z(_c,"throttle");var fc=class extends Y{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},Ec=class extends Y{constructor(t,e){super(t),this.durationSelector=e,this._debounce=new fc(this.sink),this._debounce.dispose()}next(t){this._debounce.dispose(),this._debounce.reset(),this._debounce.last=t,this._debounce.subscribe(this.durationSelector(t))}complete(){this._debounce.complete(),super.complete()}},rC=Z(Ec,"debounce");var Tc=class extends Y{constructor(t,e,r){super(t),this.count=e,this.defaultValue=r}next(t){this.count--===0&&(this.defaultValue=t,this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("not enough elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},nC=Z(Tc,"elementAt");var Sc=class extends Y{constructor(t,e){super(t),this.f=e,this.i=0}next(t){this.f(t)?(this.sink.next(this.i++),this.complete()):++this.i}},sC=Z(Sc,"findIndex"),gc=class extends Y{constructor(t,e,r){super(t),this.f=e,this.defaultValue=r,this.index=0}next(t){(!this.f||this.f(t,this.index++))&&(this.defaultValue=t,this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},oC=Z(gc,"first"),Ic=class extends Y{constructor(t,e,r){super(t),this.f=e,this.defaultValue=r,this.index=0}next(t){(!this.f||this.f(t,this.index++))&&(this.defaultValue=t)}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},aC=Z(Ic,"last"),Rc=class extends Y{constructor(t,e){super(t),this.predicate=e,this.index=0}next(t){this.predicate(t,this.index++)?this.result=!0:(this.result=!1,this.complete())}complete(){if(this.result===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.result);super.complete()}},cC=Z(Rc,"every");var bC=_(f());var Ac=class extends Y{constructor(t,e,r){super(t),this.f=e,typeof r=="undefined"?this.next=n=>{this.acc=n,this.resetNext(),this.sink.next(this.acc)}:this.acc=r}next(t){this.sink.next(this.acc=this.f(this.acc,t))}},hC=Z(Ac,"scan"),Cc=class extends Y{constructor(){super(...arguments),this.hasLast=!1}next(t){this.hasLast?this.sink.next([this.last,t]):this.hasLast=!0,this.last=t}},mC=Z(Cc,"pairwise"),yc=class extends Y{constructor(t,e,r){super(t),this.mapper=e,this.thisArg=r}next(t){super.next(this.mapper.call(this.thisArg,t))}},nl=Z(yc,"map");var Ur=class extends Y{constructor(t,e,r){super(t),this.data=e,this.context=r}next(t){let e=this.context.combineResults;e?this.sink.next(e(this.data,t)):this.sink.next(t)}tryComplete(){this.context.resetComplete(),this.dispose()}},Vr=class extends Y{constructor(t,e,r){super(t),this.makeSource=e,this.combineResults=r,this.index=0}subInner(t,e){let r=this.currentSink=new e(this.sink,t,this);this.complete=this.tryComplete,r.complete=r.tryComplete,r.subscribe(this.makeSource(t,this.index++))}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},ro=class extends Ur{},no=class extends Vr{next(t){this.subInner(t,ro),this.next=e=>{this.currentSink.dispose(),this.subInner(e,ro)}}},tf=Z(no,"switchMap");function co(i){return(t,e)=>i(()=>t,e)}var _C=co(Z(no,"switchMapTo")),vc=class extends Ur{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},so=class extends Vr{constructor(){super(...arguments),this.sources=[],this.next2=this.sources.push.bind(this.sources)}next(t){this.next2(t),this.subNext()}subNext(){this.next=this.next2,this.subInner(this.sources.shift(),vc),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},fC=Z(so,"concatMap"),EC=co(Z(so,"concatMapTo")),Nc=class extends Ur{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},oo=class extends Vr{constructor(){super(...arguments),this.inners=new Set}next(t){this.subInner(t,Nc),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(t=>t.resetComplete()):this.dispose()}},TC=Z(oo,"mergeMap"),SC=co(Z(oo,"mergeMapTo")),bc=class extends Ur{dispose(){this.context.resetNext(),super.dispose()}},ao=class extends Vr{next(t){this.next=ye,this.subInner(t,bc)}},gC=Z(ao,"exhaustMap"),IC=co(Z(ao,"exhaustMapTo")),Dc=class extends Y{constructor(t,e){super(t),this.f=e,this.groups=new Map}next(t){let e=this.f(t),r=this.groups.get(e);typeof r=="undefined"&&(r=nc(),r.key=e,this.groups.set(e,r),super.next(r)),r.next(t)}complete(){this.groups.forEach(t=>t.complete()),super.complete()}error(t){this.groups.forEach(e=>e.error(t)),super.error(t)}},RC=Z(Dc,"groupBy"),Oc=class extends Y{constructor(){super(...arguments),this.start=new Date}next(t){this.sink.next({value:t,interval:Number(new Date)-Number(this.start)}),this.start=new Date}},AC=Z(Oc,"timeInterval"),Pc=class extends Y{constructor(t,e){super(t),this.miniseconds=e,this.buffer=[],this.id=setInterval(()=>{this.sink.next(this.buffer.concat()),this.buffer.length=0},this.miniseconds)}next(t){this.buffer.push(t)}complete(){this.sink.next(this.buffer),super.complete()}dispose(){clearInterval(this.id),super.dispose()}},CC=Z(Pc,"bufferTime"),Mc=class extends Y{constructor(t,e){super(t),this.buffer=[],this.delayTime=e}dispose(){clearTimeout(this.timeoutId),super.dispose()}delay(t){this.timeoutId=setTimeout(()=>{let e=this.buffer.shift();if(e){let{time:r,data:n}=e;super.next(n),this.buffer.length&&this.delay(Number(this.buffer[0].time)-Number(r))}},t)}next(t){this.buffer.length||this.delay(this.delayTime),this.buffer.push({time:new Date,data:t})}complete(){this.timeoutId=setTimeout(()=>super.complete(),this.delayTime)}},yC=Z(Mc,"delay"),Lc=class extends Y{constructor(t,e){super(t),this.selector=e}error(t){this.dispose(),this.selector(t)(this.sink)}},vC=Z(Lc,"catchError");var kC=_(f());var kc=class extends Y{constructor(t,e){super(t),e instanceof Function?this.next=r=>{e(r),t.next(r)}:(e.next&&(this.next=r=>{e.next(r),t.next(r)}),e.complete&&(this.complete=()=>{e.complete(),t.complete()}),e.error&&(this.error=r=>{e.error(r),t.error(r)}))}},PC=Z(kc,"tap"),xc=class extends Y{constructor(t,e){super(t),this.timeout=e,this.id=setTimeout(()=>this.error(new to(this.timeout)),this.timeout)}next(t){super.next(t),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},MC=Z(xc,"timeout");var qC=il(rl(250),nl(()=>performance.now()),io());var cy=_(f(),1);var wr=new Map;C.on(S.JOIN_SUCCESS,({room:i})=>{be(i.userId,{eventId:32788,eventDesc:"join room"})});C.on(S.LEAVE_START,({room:i})=>{be(i.userId,{eventId:32789,eventDesc:"leave room"})});C.on(S.LOCAL_TRACK_PUBLISHED,({track:i})=>{i.room&&be(i.room.userId,{eventId:i.kind===m.AUDIO?32769:32768,eventDesc:`publish ${i.kind}`})});C.on(S.LOCAL_TRACK_UNPUBLISHED,({track:i})=>{i.room&&be(i.room.userId,{eventId:i.kind===m.AUDIO?32771:32770,eventDesc:`unpublish ${i.kind}`})});C.on(S.TRACK_MUTED,({track:i})=>{i.room&&(i.kind===m.AUDIO?be(i.room.userId,{eventId:i.isRemote?32785:32772,eventDesc:"mute audio",remoteUserId:i.isRemote?i.userId:void 0}):be(i.room.userId,{eventId:i.isRemote?32784:32773,eventDesc:"mute video",remoteUserId:i.isRemote?i.userId:void 0}))});C.on(S.TRACK_UNMUTED,({track:i})=>{i.room&&(i.kind===m.AUDIO?be(i.room.userId,{eventId:i.isRemote?32787:32774,eventDesc:"unmute audio",remoteUserId:i.isRemote?i.userId:void 0}):be(i.room.userId,{eventId:i.isRemote?32786:32775,eventDesc:"unmute video",remoteUserId:i.isRemote?i.userId:void 0}))});C.on(S.REMOTE_TRACK_SUBSCRIBED,({track:i})=>{i.mediaType===1&&be(i.room.userId,{eventId:32777,eventDesc:`${m.SUBSCRIBE} ${i.kind}`,remoteUserId:i.userId}),i.mediaType===4&&be(i.room.userId,{eventId:32776,eventDesc:`${m.SUBSCRIBE} ${i.kind}`,remoteUserId:i.userId}),i.mediaType===8&&be(i.room.userId,{eventId:32803,eventDesc:`${m.SUBSCRIBE} ${m.SMALL_VIDEO}`,remoteUserId:i.userId})});C.on(S.REMOTE_TRACK_UNSUBSCRIBED,({track:i})=>{i.mediaType===1&&be(i.room.userId,{eventId:32779,eventDesc:`${m.UNSUBSCRIBE} ${i.kind}`,remoteUserId:i.userId}),i.mediaType===4&&be(i.room.userId,{eventId:32778,eventDesc:`${m.UNSUBSCRIBE} ${i.kind}`,remoteUserId:i.userId}),i.mediaType===8&&be(i.room.userId,{eventId:32804,eventDesc:`${m.UNSUBSCRIBE} ${m.SMALL_VIDEO}`,remoteUserId:i.userId})});C.on(S.SWITCH_DEVICE_SUCCESS,({track:i})=>{i.room&&be(i.room.userId,{eventId:i.kind===m.VIDEO?32780:32781,eventDesc:`switch ${i.kind===m.VIDEO?"camera":"microphone"}`})});C.on(S.LOCAL_TRACK_REPLACED,({track:i})=>{i.room&&be(i.room.userId,{eventId:i.kind===m.VIDEO?32782:32783,eventDesc:`replace ${i.kind}`})});C.on(S.SIGNAL_CONNECTION_STATE_CHANGED,({room:i,prevState:t,state:e})=>{let r,n;switch(e){case"CONNECTED":t==="RECONNECTING"?(r=32795,n="signal reconnected"):(r=32791,n="signal connected");break;case"DISCONNECTED":t==="RECONNECTING"?(r=32796,n="signal reconnect fail"):(r=32790,n="signal disconnected");break;case"RECONNECTING":r=32794,n="signal reconnecting";break}r&&n&&be(i.userId,{eventId:r,eventDesc:n})});C.on(S.PEER_CONNECTION_STATE_CHANGED,({room:i,prevState:t,state:e,remoteUserId:r})=>{let n=!!r,s=n?"downlink":"uplink",o,a;switch(e){case"CONNECTED":t==="RECONNECTING"?(o=n?32801:32798,a=`${s} reconnected`):(o=n?32793:32792,a=`${s} connected`);break;case"DISCONNECTED":t==="RECONNECTING"&&(o=n?32802:32799,a=`${s} reconnect fail`);break;case"RECONNECTING":o=n?32800:32797,a=`${s} reconnecting`;break}o&&a&&be(i.userId,{eventId:o,eventDesc:a,remoteUserId:r})});function be(i,t){let e=ee(w({},t),{timestamp:en()});wr.has(i)?wr.get(i).push(e):wr.set(i,[e])}function sl(i){if(wr.has(i)){let t=wr.get(i).map(e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,str_event_json:e.eventDesc}));return wr.delete(i),t}return[]}var Sy=_(f(),1);var Ny=_(f(),1);var ol=_(rt(),1);var uo=class extends ol.EventEmitter{constructor(e,r,n="userId"){super();this.mySelfId=e;this._log=r;this.key=n;p(this,"userMap",new Map);p(this,"remotePublishedUserMap",new Map)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let r=e[this.key],{userId:n,tinyId:s,role:o}=e;if(this.userMap.has(r))return;let a={userId:n,tinyId:s,role:o===20?"anchor":"audience"};this.userMap.set(r,a),this.emit("1",a)}deleteUser(e,r){let n=this.userMap.get(e);if(!n)return;let s=`peer leave [${e}]`;b(r)||(s+=`:${ga[r]}`),this._log.info(s);let o=this.remotePublishedUserMap.get(e);if(o){let a=o.muteState;o.flag=0,this.emit("5",o.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:a,muteState:o.muteState,flag:0})}this.userMap.delete(e),this.emit("2",n.userId)}setUserList(e){this.userMap.forEach(r=>{e.findIndex(n=>n[this.key]===r[this.key])<0&&this.deleteUser(r[this.key],0)}),e.forEach(r=>{!this.userMap.has(r[this.key])&&r[this.key]!==this.mySelfId&&this.addUser(r)})}addRemotePublishedUser(e){this.remotePublishedUserMap.has(e[this.key])||this.remotePublishedUserMap.set(e[this.key],e)}deleteRemotePublishedUser(e){!this.remotePublishedUserMap.has(e)||this.remotePublishedUserMap.delete(e)}setRemotePublishedUserList(e){this.remotePublishedUserMap.forEach(r=>{let n=r[this.key];if(e.findIndex(s=>s[this.key]===r[this.key])<0){this._log.info(`remote [${n}] unpublish`);let s=r.muteState;r.flag=0,this.emit("5",r.userId),this.deleteRemotePublishedUser(n),this.emit("6",{prevMuteState:s,muteState:r.muteState,flag:0})}}),e.forEach(r=>{var u;let n=r[this.key];if(n===this.mySelfId)return;let{flag:s,userId:o,tinyId:a}=r,c=li(s,o),d=(u=this.remotePublishedUserMap.get(n))==null?void 0:u.muteState;if(d){let l=this.remotePublishedUserMap.get(n);l&&l.flag!==s&&(l.flag=s,this._log.info(`remote publish updated: ${JSON.stringify(l.muteState)}`),this.emit("6",{prevMuteState:d,muteState:c,flag:s}))}else this._log.info(`remote publish. state: ${JSON.stringify(c)}`),this.addUser({userId:o,tinyId:a,role:20}),this.emit("3",r),this.emit("6",{prevMuteState:li(0,o),muteState:c,flag:s})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};var pv=_(f(),1);function al({timesInSecond:i,maxSizeInSecond:t,getSize:e}){return ae((r,n)=>{let s=new Map;return C.on(S.ROOM_DESTROY,({room:o})=>s.delete(o)),function(...o){let a=s.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},s.set(this,a)),a.timestamp===0?a.timestamp=Date.now():Date.now()-a.timestamp>1e3&&(a.timestamp=Date.now(),a.callCountInSecond=0,a.totalSizeInSecond=0),e&&(a.totalSizeInSecond+=e(...o)),a.timestamp!==0&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=i||a.totalSizeInSecond>t))throw new M({code:v.INVALID_OPERATION,message:B({key:V.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=i,isSize:a.totalSizeInSecond>t,name:n,timesInSecond:i,maxSizeInSecond:t}})});a.callCountInSecond++,r.call(this,...o)}})}var fv=_(f(),1);var cl=!0,dl=function(){var i;cl&&(cl=!1,O.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${Mi}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("******************************************************************************")),O.info("TRTC Web SDK Version:",$e),O.info("UA:",navigator.userAgent),O.info(`URL: ${location.href}${((i=self.frameElement)==null?void 0:i.tagName)==="IFRAME"?" in iframe":""}`))};var Yv=_(f());var Av=_(f());var Bn={SCENE_LIVE:"live",SCENE_RTC:"rtc",ROLE_ANCHOR:"anchor",ROLE_AUDIENCE:"audience",STREAM_TYPE_MAIN:"main",STREAM_TYPE_SUB:"sub",AUDIO_PROFILE_STANDARD:"standard",AUDIO_PROFILE_STANDARD_STEREO:"standard-stereo",AUDIO_PROFILE_HIGH:"high",AUDIO_PROFILE_HIGH_STEREO:"high-stereo",QOS_PREFERENCE_SMOOTH:"smooth",QOS_PREFERENCE_CLEAR:"clear"};var xv=_(f());var yv=_(f()),q={INVALID_PARAMETER:5e3,INVALID_OPERATION:5100,ENV_NOT_SUPPORTED:5200,DEVICE_ERROR:5300,SERVER_ERROR:5400,OPERATION_FAILED:5500,OPERATION_ABORT:5998,UNKNOWN_ERROR:5999},Ti=(D=>(D[D.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",D[D.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",D[D.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",D[D.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",D[D.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",D[D.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",D[D.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",D[D.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",D[D.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",D[D.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",D[D.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",D[D.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",D[D.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",D[D.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",D[D.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",D[D.MIX_PARAMS_USER_Z_ORDER=5015]="MIX_PARAMS_USER_Z_ORDER",D[D.MIX_PARAMS_VIDEO_FRAMERATE=5016]="MIX_PARAMS_VIDEO_FRAMERATE",D[D.MIX_PARAMS_VIDEO_GOP=5017]="MIX_PARAMS_VIDEO_GOP",D[D.MIX_PARAMS_AUDIO_BITRATE=5018]="MIX_PARAMS_AUDIO_BITRATE",D[D.MIX_PARAMS_NOT_SELF=5019]="MIX_PARAMS_NOT_SELF",D[D.MIX_PARAMS_USER_STREAM=5020]="MIX_PARAMS_USER_STREAM",D[D.INVALID_OPERATION=5100]="INVALID_OPERATION",D[D.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",D[D.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",D[D.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",D[D.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",D[D.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",D[D.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",D[D.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",D[D.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",D[D.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",D[D.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",D[D.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",D[D.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",D[D.DEVICE_ERROR=5300]="DEVICE_ERROR",D[D.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",D[D.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",D[D.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",D[D.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",D[D.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",D[D.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",D[D.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",D[D.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",D[D.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",D[D.SERVER_ERROR=5400]="SERVER_ERROR",D[D.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",D[D.OPERATION_FAILED=5500]="OPERATION_FAILED",D[D.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",D[D.REJOIN_FAILED=5502]="REJOIN_FAILED",D[D.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",D[D.OPERATION_ABORT=5998]="OPERATION_ABORT",D[D.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",D))(Ti||{});var Ov=_(f());function ll({code:i,params:t,enableDocLink:e=!1}){let r="",n,s=Ti[i];try{n=ul[s]}catch(o){n=ul.UNKNOWN_ERROR}return ce(n)?r=n(t):oe(n)&&(r=n),e&&(r+=" doc:"),r}var ul={INVALID_PARAMETER({fnName:i}){return`the parameters of the '${i}' you called does not meet the requirements, please check the API documentation.`},INVALID_PARAMETER_REQUIRED({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' is a required param when calling ${e}(), received: ${r}.`},INVALID_PARAMETER_TYPE({key:i,rule:t,fnName:e,value:r}){let n=`${i||t.name}`,s="";return Array.isArray(t.type)?s=t.type.join("|"):s=t.type,`'${n}' must be type of ${s} when calling ${e}(), received type: ${Ee(r)}.`},INVALID_PARAMETER_EMPTY({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' cannot be '${r}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:i,rule:t,fnName:e,value:r}){let n=`${i||t.name}`,s=`${t.instanceOf.name||t.instanceOf}`;return`'${n}' must be instanceof ${s} when calling ${e}(), received type: ${Ee(r)}.`},INVALID_PARAMETER_RANGE({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' must be one of ${t.values.join("|")} when calling ${e}(), received: ${r}.`},INVALID_PARAMETER_LESS_THAN_ZERO({key:i,rule:t,fnName:e}){return`'${i||t.name}' cannot be less than 0 when calling ${e}().`},INVALID_PARAMETER_MIN({key:i,rule:t,value:e}){return`the min value of ${i||t.name} is ${t.min}, received: ${e}.`},INVALID_PARAMETER_MAX({key:i,rule:t,value:e}){return`the max value of ${i||t.name} is ${t.max}, received: ${e}.`},INVALID_ELEMENT_ID({key:i,fnName:t}){return`'${i}' is not found in the document object when calling ${t}().`},INVALID_ELEMENT_ID_TYPE({key:i,fnName:t,type:e}){return`the element corresponding to '${i}' must be instanceof HTMLElement when calling ${t}(), received: ${e}.`},INVALID_STREAM_ID({key:i}){return`'${i}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},INVALID_ROOM_ID_STRING({key:i}){return`'${i}' must be validate string when useStringRoomId is true.`},INVALID_ROOM_ID_INTEGER({key:i}){return`'${i}' must be an integer between [1, 4294967294] when useStringRoomId is false.`},INVALID_STREAM_TYPE:({fnName:i})=>`'streamType' is required when 'userId' is not '*', calling ${i}()`,MIX_PARAMS_USER_Z_ORDER({key:i}){return`'${i}' is required and must be between 1 and 15.`},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_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_OPERATION({fnName:i}){return`the API '${i}' you called does not meet the requirements, please check the API documentation.`},INVALID_OPERATION_NOT_JOINED({fnName:i}){return`cannot ${i} because you are not enter room yet.`},INVALID_OPERATION_REMOTE_USER_NOT_EXIST({fnName:i,value:t}){return`cannot ${i} because remote user(userId: ${t.userId}) does not publishing stream.`},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST({fnName:i,value:t}){return`cannot ${i} because remote user(userId: ${t.userId}) does not publishing ${t.streamType} video.`},INVALID_OPERATION_REPEAT_CALL({fnName:i}){return`you are already ${i}(), cannot repeated call '${i}'.`},ENV_NOT_SUPPORTED({fnName:i}){return`the current browser does not support the capability of the function '${i}' you are calling, please check the API documentation.`},NOT_SUPPORTED_HTTP:"http protocol does not support the ability to capture and publish streams, please use the https protocol.",NOT_SUPPORTED_WEBRTC:"the current browser does not support WebRTC capability, please check the SDK documentation.",NOT_SUPPORTED_H264_ENCODE:"this browser does not support H264 encode.",NOT_SUPPORTED_H264_DECODE:"this browser does not support H264 decode.",NOT_SUPPORTED_SCREEN_SHARE:"this browser does not support screen share, please check the browser version.",NOT_SUPPORTED_SMALL_VIDEO:"this browser does not support small video, please check the browser version.",NOT_SUPPORTED_SEI:"this browser does not support SEI, please check the browser version.",DEVICE_ERROR({fnName:i,error:t}){return`'${i}' got server exception${t?`, error: ${t.toString()}.`:"."}`},DEVICE_NOT_FOUND_ERROR({fnName:i,deviceType:t=Yi(i),error:e}){return`NotFoundError, no ${t} detected, please check your device and the configuration on '${i}'${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_ALLOWED_ERROR({fnName:i,deviceType:t=Yi(i),error:e}){return`NotAllowedError, you have disabled ${t} access, please allow the current application to use the ${t}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_READABLE_ERROR({fnName:i,deviceType:t=Yi(i),error:e}){return`NotReadableError, the ${t} maybe in use by another APP, please check if the device is pre-occupied by another APP.`},DEVICE_OVERCONSTRAINED_ERROR({fnName:i,deviceType:t=Yi(i),error:e}){return`OverconstrainedError, the device ID is incorrect, please check whether the device ID passed in is correct${e?`, error: ${e.toString()}.`:"."}`},DEVICE_INVALID_STATE_ERROR({fnName:i,deviceType:t=Yi(i),error:e}){return`InvalidStateError, after the user clicks and interacts with the page, turn on the ${t}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_SECURITY_ERROR({fnName:i,deviceType:t=Yi(i),error:e}){return`SecurityError, check whether the system security policy restricts the use of the ${t}, and it is recommended to turn on the ${t} after the user interacts with the page${e?`, error: ${e.toString()}.`:"."}`},DEVICE_ABORT_ERROR({fnName:i,deviceType:t=Yi(i),error:e}){return`AbortError, an unknown exception in the system makes the device unusable, recommended to change the device or browser and re-check whether the device is normal${e?` error: ${e.toString()}.`:"."}`},CAMERA_RECOVER_FAILED({error:i}){return`camera recover capture failed ${(i==null?void 0:i.name)||""}: ${(i==null?void 0:i.originMessage)||(i==null?void 0:i.message)}`},MICROPHONE_RECOVER_FAILED({error:i}){return`microphone recover capture failed ${(i==null?void 0:i.name)||""}: ${(i==null?void 0:i.originMessage)||(i==null?void 0:i.message)}`},OPERATION_FAILED({fnName:i,error:t}){return`'${i}' failed, reason: ${t==null?void 0:t.toString()}`},FIREWALL_RESTRICTION(){return"media connection failure due to firewall restrictions, please try to change your network."},EVENT_HANDLER_ERROR({eventName:i}){return`an error was caught on trtc.on('${i}', handler), please check your code on 'handler'.`},SERVER_ERROR({fnName:i,error:t}){return`'${i}' got server error: ${t==null?void 0:t.toString()}, please check the SDK documentation.`},ACCOUNT_NO_MONEY:({fnParams:i})=>`your TRTC account run out of credit, please recharge.${i.sdkAppId?` SDKAppId: ${i.sdkAppId}`:""}`,OPERATION_ABORT({fnName:i}){return`'${i}' abort`},UNKNOWN_ERROR({fnName:i,error:t}){return`'${i}' throw unknown exception${t?`, error: ${t.toString()}.`:"."}`}};function Yi(i){if(!i)return"camera";let t=i.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var Br=class extends Error{constructor({code:e,extraCode:r,message:n="",messageParams:s,fnName:o="",originError:a}){let c;n?c=n:c=ll({code:r||e,params:w({fnName:o,error:a},s)});super(c);p(this,"name","RtcError");p(this,"code");p(this,"extraCode");p(this,"functionName");p(this,"message");p(this,"originError");this.name=Ti[e],this.code=e,this.extraCode=r,this.functionName=o,this.originError=a,this.message=c}static convertFrom(e,r,n){let s=e;if(e instanceof M){let{stack:o}=e,a={code:q.UNKNOWN_ERROR,fnName:r,originError:e};switch(e.getCode()){case v.INVALID_PARAMETER:a.code=q.INVALID_PARAMETER;break;case v.INVALID_OPERATION:a.code=q.INVALID_OPERATION;break;case v.NOT_SUPPORTED:case v.NOT_SUPPORTED_H264:a.code=q.ENV_NOT_SUPPORTED,e.getCode()===v.NOT_SUPPORTED_H264&&(a.extraCode=e.message.includes(xe.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case v.DEVICE_NOT_FOUND:case v.DEVICE_AUTO_RECOVER_FAILED:a.code=q.DEVICE_ERROR;break;case v.JOIN_ROOM_FAILED:a.messageParams={fnParams:n};case v.SERVER_TIMEOUT:case v.SWITCH_ROLE_FAILED:a.code=q.SERVER_ERROR,a.extraCode=e.getExtraCode();break;case v.API_CALL_ABORTED:a.code=q.OPERATION_ABORT;break;case v.INITIALIZE_FAILED:a.code=5300,a.extraCode=rf(e.name);break;case v.UNKNOWN:break;default:a.code=q.OPERATION_FAILED}s=new Br(a),o&&(s.stack+=o.substr(o.indexOf(`
89
+ `)))}else s=new Br({code:q.UNKNOWN_ERROR,fnName:r,originError:e});return s}};function rf(i){let t;switch(i){case"NotFoundError":t=5301;break;case"NotAllowedError":t=5302;break;case"NotReadableError":t=5303;break;case"OverconstrainedError":t=5304;break;case"InvalidStateError":t=5305;break;case"SecurityError":t=5306;break;case"AbortError":t=5307;break;default:t=5300}return t}var j=Br;var pl={type:"object",properties:{cameraId:{type:"string"},useFrontCamera:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"},small:{properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack}}},hl={type:"object",properties:{systemAudio:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},profile:{type:["string","object"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack},audioTrack:{instanceOf:MediaStreamTrack}}},$r={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(i,t,e){if(oe(i)){let r=document.getElementById(i);if(!r)throw new j({code:q.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:t}});if(!(r instanceof HTMLElement))throw new j({code:q.INVALID_PARAMETER,extraCode:5010,fnName:e,messageParams:{key:t,type:Ee(r)}})}}},ml={name:"userId",required:!0,type:"string"},_l={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0,max:100},earMonitorVolume:{type:"number",min:0,max:100},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function fl(i,t,e,r){if(!/^[A-Za-z\d_-]*$/.test(i))throw new j({code:q.INVALID_PARAMETER,extraCode:5011,fnName:e,messageParams:{key:t}})}function El(i,t,e,r){if(oe(i)){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(i))throw new j({code:q.INVALID_PARAMETER,extraCode:5012,fnName:e,messageParams:{key:t}})}else if(!(/^[1-9]\d*$/.test(String(i))&&i<4294967295))throw new j({code:q.INVALID_PARAMETER,extraCode:5013,fnName:e,messageParams:{key:t}})}function po(i,t){if(!i)throw new j({code:q.INVALID_OPERATION,extraCode:5101,fnName:t})}function Tl(i,t,e){if(!i)throw new j({code:q.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:e}})}var Si={type:"number",notLessThanZero:!0},nf={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(i,t,e){if(this._room.isJoined)throw new j({code:q.INVALID_OPERATION,extraCode:5104,fnName:e})},properties:{sdkAppId:{required:!0,type:"number",allowEmpty:!1},userId:{required:!0,type:"string",allowEmpty:!1},userSig:{required:!0,type:"string",allowEmpty:!1},scene:{type:"string",values:["live","rtc"]},role:{type:"string",values:["audience","anchor"]},roomId:{required:!0,type:["string","number"],validate:El},proxy:{type:["object","string"],properties:{websocketProxy:{type:"string"},turnServer:{type:["object","array"],properties:{url:{required:!0,type:"string"},username:{type:"string"},credential:{type:"string"},credentialType:{type:"string",values:["password"]}}},loggerProxy:{type:"string"},webtransportProxy:{type:"string"}}},enableAutoPlayDialog:{type:"boolean"},streamId:{type:"string"},userDefineRecordId:{type:"string"}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:$r,publish:{type:"boolean"},option:pl}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:ee(w({},$r),{required:!1}),publish:{type:"boolean"},mute:{type:"boolean"},option:pl}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:_l}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:_l}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:$r,publish:{type:"boolean"},option:hl}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:$r,publish:{type:"boolean"},option:hl}},muteRemoteAudio:[ml,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[ml,{name:"volume",required:!0,type:"number",min:0,max:100}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:$r,userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(i,t,e){po(this._room.isJoined,e);let r=this._room.remotePublishedUserMap.get(i.userId);if(Tl(!!r,e,i),r&&(i.streamType==="main"&&!r.muteState.videoAvailable||i.streamType==="sub"&&!r.muteState.hasAuxiliary))throw new j({code:q.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:i}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:ee(w({},$r),{required:!1}),userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(i,t,e){po(this._room.isJoined,e);let r=this._room.remotePublishedUserMap.get(i.userId);if(Tl(!!r,e,i),r&&(i.streamType==="main"&&!r.muteState.videoAvailable||i.streamType==="sub"&&!r.muteState.hasAuxiliary))throw new j({code:q.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:i}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(i,t,e){if(i.userId!=="*"&&b(i.streamType))throw new j({code:q.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(i,t,e){po(this._room.isJoined,e)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],startMixTranscode:{name:"config",required:!0,type:"object",properties:{mode:{type:"string",values:["preset-layout","manual"]},streamId:{type:"string",validate:fl},videoWidth:Si,videoHeight:Si,videoBitrate:ee(w({},Si),{allowEmpty:!1}),videoFramerate:{type:"number",validate(i,t,e,r){if(i<=0||i>30)throw new j({code:q.INVALID_PARAMETER,extraCode:5016,fnName:e})}},videoGop:{type:"number",validate(i,t,e,r){if(i<1||i>8)throw new j({code:q.INVALID_PARAMETER,extraCode:5017,fnName:e})}},audioSampleRate:Si,audioBitrate:{type:"number",validate(i,t,e,r){if(i<32||i>192)throw new j({code:q.INVALID_PARAMETER,extraCode:5018,fnName:e})}},audioChannels:{type:"number",values:[1,2]},backgroundColor:{type:"number"},backgroundImage:{type:"string"},mixUsers:{required:!0,type:"array",arrayItem:{require:!0,type:"object",properties:{userId:{required:!0,type:"string"},roomId:{type:["string","number"],validate:El},pureAudio:{type:"boolean"},width:Si,height:Si,locationX:Si,locationY:Si,zOrder:{type:"number"},streamType:{values:["main","sub"]},renderMode:{type:"number",values:[0,1,2,4]}}}}},validate(i,t,e,r){let n=0,s=0,{mixUsers:o}=i,a=[];if(o.forEach((c,d)=>{if(a.push(c.userId),!c.pureAudio){if(!c.zOrder||c.zOrder<1||c>15)throw new j({code:q.INVALID_PARAMETER,extraCode:5015,fnName:e,messageParams:{key:`config.mixUsers[${d}].zOrder`}});c.width+c.locationX>n&&(n=c.width+c.locationX),c.height+c.locationY>s&&(s=c.height+c.locationY)}}),a.indexOf(this._room.userId)<0)throw new j({code:q.INVALID_PARAMETER,extraCode:5019,fnName:e});if(i.videoWidth<n||i.videoHeight<s)throw new j({code:q.INVALID_PARAMETER,extraCode:5020,fnName:e})}},startPublishCDNStream:{name:"options",required:!1,properties:{streamId:{type:"string",validate:fl},streamType:{values:["main","sub"]},appId:{type:"number",allowEmpty:!1},bizId:{type:"number",allowEmpty:!1},url:{type:"string",allowEmpty:!1}}},sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(i,t,e,r){if(!_i)throw new j({code:q.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new j({code:q.INVALID_OPERATION,messageParams:{key:V.SEI_DISABLED}});if(i.byteLength>1e3)throw new j({code:q.INVALID_PARAMETER,messageParams:{key:V.SEI_OVERSIZE,data:i.byteLength}});if(i.byteLength===0)throw new j({code:q.INVALID_PARAMETER,messageParams:{key:V.SEI_EMPTY}});if(po(this._room.isJoined,e),!this._room.isMainStreamPublished)throw new j({code:q.INVALID_PARAMETER,messageParams:{key:V.SEI_BEFORE_PUBLISH}})}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]}}}]},De={TRTC:nf};var aN=_(f());var Qv=_(f(),1);var Ue=class extends Error{};function sf(i,t){let e=[];return bt(e,i),bt(e,t),e}function of(i){this._resolve=Promise.resolve(i)}function af(i){this._reject=Promise.reject(i)}var Hr=class{constructor(t,e){this.instance=t;this.group=e;p(this,"started",!1);p(this,"ops",[]);p(this,"startSame",()=>!0);p(this,"mergeUpdate",sf);let r=Hr.instances.get(t);r?r.set(e,this):Hr.instances.set(t,new Map([[e,this]]))}static get(t,e){let r=Hr.instances.get(t);return r&&r.get(e)||new Hr(t,e)}action(t,e,r){let n=a=>{var c;return t===0?this.started=!0:t===3&&(this.started=!1),this.ops.shift(),(c=this.currentOp)==null||c.action(),a},s=a=>{var c,d;throw this.ops.shift(),t===0&&((c=this.currentOp)==null?void 0:c.type)===2&&this.ops.shift().reject(new Ue("start failed")),(d=this.currentOp)==null||d.action(),a},o={type:t,action:()=>e(...o.args).then(n,s),args:r,resolve:of,reject:af};try{switch(this.state){case 1:if(t===0)throw new Ue("already started");break;case 4:if(t===2)throw new Ue("not started");break;default:return this.cacheOp(o)}}catch(a){return Promise.reject(a)}return this.ops.push(o),o.promise=e(...o.args).then(n,s)}cacheOp(t){if(this.ops.length===1)switch(this.state){case 0:case 2:if(t.type===0)throw new Ue("already start");break;case 3:switch(t.type){case 2:throw new Ue("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new Ue("unknown state")}else switch(t.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let r=new Ue("keep stop");if(this.ops.slice(1).forEach(n=>n.reject(r)),this.ops=this.ops.slice(0,1),this.state===3)return this.currentOp.promise}break;case 2:switch(this.lastOpType){case 2:return this.lastOp.args=this.mergeUpdate(this.lastOp.args,t.args),this.lastOp.promise;case 3:throw new Ue("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new Ue("start not allowed after update");case 0:throw new Ue("duplicate start");case 3:if(this.startSame(this.currentOp.args,t.args))throw this.ops.pop().reject(new Ue("keep start")),new Ue("already start")}}t.promise=new Promise((r,n)=>{t._resolve?t._resolve.then(r):t.resolve=r,t._reject?t._reject.catch(n):t.reject=n});let{action:e}=t;return t.action=()=>e().then(t.resolve,t.reject),this.ops.push(t),t.promise}get lastOp(){return this.ops[this.ops.length-1]}get lastOpType(){return this.lastOp.type}get currentOp(){return this.ops[0]}get state(){return this.currentOp?this.currentOp.type:this.started?1:4}},zt=Hr;p(zt,"instances",new WeakMap);var Uc=(i,t)=>{if(t instanceof Ue){let{stack:e}=t;t=new j({code:q.OPERATION_ABORT,message:`${i} abort: ${t.message}`,fnName:i}),e&&(t.stack+=e.substr(e.indexOf(`
90
+ `)))}throw t};function gi(i,t){return ae((e,r)=>function(...n){let s=zt.get(this,typeof i=="string"?i:i.call(this,...n));return t&&(s.startSame=t.bind(this)),s.action(0,e.bind(this),n).catch(Uc.bind(null,r))})}function Xi(i,t){return ae((e,r)=>function(...n){let s=zt.get(this,typeof i=="string"?i:i.call(this,...n));return t&&(s.mergeUpdate=t.bind(this)),s.action(2,e.bind(this),n).catch(Uc.bind(null,r))})}function Ii(i){return ae((t,e)=>function(...r){return zt.get(this,typeof i=="string"?i:i.call(this,...r)).action(3,t.bind(this),r).catch(Uc.bind(null,e))})}var dN=_(f()),X={ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",KICKED_OUT:"kicked-out",REMOTE_USER_ENTER:"remote-user-enter",REMOTE_USER_EXIT:"remote-user-exit",REMOTE_AUDIO_AVAILABLE:"remote-audio-available",REMOTE_AUDIO_UNAVAILABLE:"remote-audio-unavailable",REMOTE_VIDEO_AVAILABLE:"remote-video-available",REMOTE_VIDEO_UNAVAILABLE:"remote-video-unavailable",AUDIO_VOLUME:"audio-volume",NETWORK_QUALITY:"network-quality",CONNECTION_STATE_CHANGED:"connection-state-changed",AUDIO_PLAY_STATE_CHANGED:"audio-play-state-changed",VIDEO_PLAY_STATE_CHANGED:"video-play-state-changed",SCREEN_SHARE_STOPPED:"screen-share-stopped",DEVICE_CHANGED:"device-changed",PUBLISH_STATE_CHANGED:"publish-state-changed",SEI_MESSAGE:"sei-message"};var hN=_(f());function ho(i){return i==="sub"?"auxiliary":i==="auxiliary"?"sub":"main"}function $n(i){return i===Bn.QOS_PREFERENCE_CLEAR?"detail":i===Bn.QOS_PREFERENCE_SMOOTH?"motion":""}var TN=_(f(),1);function gl(i){return{room:i,innerEmitter:C,constants:Ra,environment:Di,utils:ke,eventLogger:_e,log:i.getLogger(),clearStarted(t,e){let r=t.getAlias(),n=zt.instances.get(i);if(!!n)if(e){let s=n.get(r+e);if(!s)return;s.started=!1}else n.forEach((s,o)=>{o.startsWith(r)&&(s.started=!1)})}}}var CN=_(f(),1);var Il=(i,t)=>{let{emit:e}=i;return i.emit=(...r)=>{try{return e.apply(i,r)}catch(n){let s=B({key:V.CATCH_HANDLER_ERROR,data:{name:t,event:r[0]},addDocLink:!1});return O.warn(`${s}
91
+
92
+ ${n.stack}`),!1}},i};var bN=_(f(),1);var mo=new WeakMap;function Rl(i,t){return ae((e,r)=>function(...n){var a,c;let s=(a=mo.get(this))==null?void 0:a.get(t(...n));s&&s>0&&clearTimeout(s);let o=window.setTimeout(()=>{e.apply(this,n)},i);mo.has(this)?(c=mo.get(this))==null||c.set(t(...n),o):mo.set(this,new Map([[t(...n),o]]))})}var Al="5.0.3";var UN=_(f());function Ve(...i){return ae((t,e)=>function(...r){try{fo.call(this,i,r,e,this._name)}catch(n){return Promise.reject(n)}return t.apply(this,r)})}function Vc(...i){return ae((t,e)=>function(...r){try{fo.call(this,i,r,e,this._name)}catch(n){throw n}return t.apply(this,r)})}function fo(i,t,e,r){if(Oe(i))for(let n=0;n<i.length;n++)_o.call(this,{rule:i[n],value:t[n],key:i[n].name,fnName:e,className:r});else _o.call(this,{rule:i,value:t[0],key:i.name,fnName:e,className:r})}function _o({rule:i,value:t,key:e,fnName:r,className:n}){function s(c){return{code:q.INVALID_PARAMETER,extraCode:c,fnName:r,messageParams:{key:e,rule:i,value:t}}}if(b(t)){if(i.required)throw new j(s(5001));if(b(i.defaultValue))return;t=i.defaultValue}if(Array.isArray(i.type)){let c=!1;for(let d=0;d<i.type.length;d++)i.type[d]===null&&t===null&&(c=!0),ce(i.type[d])&&t instanceof i.type[d]&&(c=!0),oe(i.type[d])&&Ee(t)===i.type[d].toLowerCase()&&(c=!0);if(!c)throw new j({code:q.INVALID_PARAMETER,extraCode:5002,fnName:r,messageParams:{key:e,rule:{type:i.type.map(d=>vn(d)?$s(d):oe(d)?d:Ee(d))},value:t}})}else if(!b(i.type)&&Ee(t)!==i.type)throw new j(s(5002));if(i.allowEmpty===!1){let c=de(t)&&(t===0||Number.isNaN(t)),d=oe(t)&&t.trim()==="";if(c||d)throw new j(s(5003))}if(i.notLessThanZero&&de(t)&&t<0)throw new j(s(5006));if(!b(i.min)&&de(t)&&t<i.min)throw new j(s(5007));if(!b(i.max)&&de(t)&&t>i.max)throw new j(s(5008));if(oe(i.instanceOf)){if(!t||t._name!==i.instanceOf)throw new j(s(5004))}else if(ce(i.instanceOf)&&!(t instanceof i.instanceOf))throw new j(s(5004));if(Array.isArray(i.values)&&!i.values.includes(t))throw new j(s(5005));let{properties:o}=i;Ht(o)&&Bi(t)&&Object.keys(o).forEach(c=>{_o.call(this,{rule:o[c],value:t&&t[c],key:`${c}`,fnName:r,className:n})});let{arrayItem:a}=i;Ht(a)&&Oe(t)&&t.forEach((c,d)=>{_o.call(this,{rule:a,value:c,key:`${e}[${d}]`,fnName:r,className:n})}),ce(i.validate)&&i.validate.call(this,t,e,r,n,this)}var WN=_(f());function ve(){return ae((i,t)=>function(...e){let r=this._log||loggerManager;e.length>0?r.info(`${t}() ${JSON.stringify(e,(n,s)=>{if(s===e||n in e)return s;try{return s instanceof HTMLElement?`id: ${s.id} type:${Ee(s)}`:(JSON.stringify(s),s)}catch(o){return`type:${Ee(s)}`}})}`):r.info(`${t}()`);try{let n=i.apply(this,e),s=z();return yn(n)?n.then(o=>(r.info(`${t}() success`),C.emit(S.API_SUCCESS_RATE,{room:this._room,apiName:t,cost:z()-s}),o)).catch(o=>{throw o=j.convertFrom.call(this,o,t,e.length===1?e[0]:e),r.error(`${t}() failed ${o}`),C.emit(S.API_SUCCESS_RATE,{room:this._room,apiName:t,error:o}),o}):(C.emit(S.API_SUCCESS_RATE,{room:this._room,apiName:t,cost:z()-s}),n)}catch(n){throw n=j.convertFrom.call(this,n,t),r.error(`${t}() failed ${n}`),C.emit(S.API_SUCCESS_RATE,{room:this._room,apiName:t,error:n}),n}})}var YN=_(f());var Eo=i=>ae((t,e)=>function(r,n){return E(this,null,function*(){let s=this._plugins.get(r);if(!s){this._log.warn(`plugin ${r} is not found`);return}return fo.call(this,s.getValidateRule(i),[n],e,"TRTC"),t.call(this,s,n)})});var Cl=0,wc=new Set,ze=null;aa(Al);var Hn=class extends vl.EventEmitter{constructor(e,r){super();p(this,"_room");p(this,"_eventListened",new Set);p(this,"_localVideoTrack",null);p(this,"_localAudioTrack",null);p(this,"_localScreenTrack",null);p(this,"_localScreenAudioTrack",null);p(this,"_localVideoConfig",null);p(this,"_localScreenConfig",null);p(this,"_localAudioConfig",null);p(this,"_remoteVideoConfigMap",new Map);p(this,"_remoteAudioConfigMap",new Map);p(this,"_remoteAudioMuteMap",new Map);p(this,"_log",O.createLogger({id:`t${++Cl}`}));p(this,"_plugins",new Map);this._room=new e(w({logger:this._log,frameWorkType:Hn.frameWorkType},r)),r.plugins&&r.plugins.forEach(n=>{let s=new n(gl(this._room));this._plugins.set(s.getName(),s)}),this._room.on("audio-volume",n=>{!n.find(s=>s.userId==="")&&this._localAudioTrack&&n.push({userId:"",volume:Math.floor(this._localAudioTrack.getAudioLevel()*100)}),this.emit(X.AUDIO_VOLUME,{result:n.sort((s,o)=>o.volume-s.volume)})}),this.on(X.REMOTE_AUDIO_UNAVAILABLE,({userId:n})=>{this._stopRemoteAudio({userId:n},!1).catch(()=>{})}),this.on(X.REMOTE_VIDEO_UNAVAILABLE,({userId:n,streamType:s})=>{this._stopRemoteVideo({userId:n,streamType:s},!1).catch(()=>{})}),ct(Te,Te).add("audioInputAdded",n=>{this.emit(X.DEVICE_CHANGED,{type:"microphone",action:"add",device:n})}).add("audioInputRemoved",n=>{this.emit(X.DEVICE_CHANGED,{type:"microphone",action:"remove",device:n})}).add("videoInputAdded",n=>{this.emit(X.DEVICE_CHANGED,{type:"camera",action:"add",device:n})}).add("videoInputRemoved",n=>{this.emit(X.DEVICE_CHANGED,{type:"camera",action:"remove",device:n})}).add("audioOutputAdded",n=>E(this,null,function*(){if(this.emit(X.DEVICE_CHANGED,{type:"speaker",action:"add",device:n}),ze&&ze.deviceId===An){let s=(yield Lr()).find(o=>o.deviceId===An);s&&ze.groupId!==s.groupId&&(ze=s,this.emit(X.DEVICE_CHANGED,{type:"speaker",action:"active",device:s}))}})).add("audioOutputRemoved",n=>E(this,null,function*(){this.emit(X.DEVICE_CHANGED,{type:"speaker",action:"remove",device:n});let s=(yield Lr())[0];s&&ze&&(ze.deviceId===n.deviceId||ze.deviceId===An&&ze.groupId!==s.groupId)&&(ze=s,this.emit(X.DEVICE_CHANGED,{type:"speaker",action:"active",device:s}))})),Il(this,"trtc")}static create(e){}static _create(e,r){Cl+=1,dl();let n=new Hn(e,r||{});return wc.add(n),ze?n.emit(X.DEVICE_CHANGED,{type:"speaker",action:"active",device:ze}):Lr().then(s=>{s[0]&&(ze=s[0],n.emit(X.DEVICE_CHANGED,{type:"speaker",action:"active",device:s[0]}))}),n}enterRoom(e){return E(this,null,function*(){var c,d;let{scene:r="rtc",enableAutoPlayDialog:n=!0,autoReceiveAudio:s=!0,autoReceiveVideo:o=!0}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!oe(e.proxy)&&e.proxy.turnServer&&((d=(c=this._room).setTurnServer)==null||d.call(c,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=n,this._room.autoReceiveAudio=s,this._room.autoReceiveVideo=o;let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,role:e.role==="audience"?21:20,roomId:0,strRoomId:"",businessInfo:e.businessInfo||null,streamId:e.streamId||null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language};oe(e.roomId)?(a.strRoomId=e.roomId,this._room.useStringRoomId=!0):a.roomId=e.roomId,ct(this,this._room).add("peer-join",u=>{let{userId:l}=u;this.emit(X.REMOTE_USER_ENTER,{userId:l})}).add("peer-leave",u=>{this.emit(X.REMOTE_USER_EXIT,{userId:u})}).add("banned",u=>{this._exitRoom().then(()=>{this.emit(X.KICKED_OUT,{reason:u.reason})})}).add("error",u=>{this._exitRoom().then(()=>{this.emit(X.ERROR,j.convertFrom(u))})}).add("signal-connection-state-changed",u=>{this.emit(X.CONNECTION_STATE_CHANGED,u)}).add("network-quality",u=>{this.emit(X.NETWORK_QUALITY,u)}).add("remote-published",u=>{[u.remoteAudioTrack,u.remoteVideoTrack,u.remoteAuxiliaryTrack].forEach(h=>{ct(h,h).add("player-state-changed",I=>{let T=ee(w({},I),{userId:u.userId});h.kind===m.VIDEO&&(T.streamType=ho(h.streamType)),this.emit(h.kind===m.AUDIO?X.AUDIO_PLAY_STATE_CHANGED:X.VIDEO_PLAY_STATE_CHANGED,T)}).add("error",I=>{I.getCode()===v.PLAY_NOT_ALLOWED&&this.emit(X.AUTOPLAY_FAILED)})})}).add("remote-unpublished",u=>{[u.remoteAudioTrack,u.remoteVideoTrack,u.remoteAuxiliaryTrack].forEach(h=>{He(h)})}).add("remote-publish-state-changed",({prevMuteState:u,muteState:l})=>{let{userId:h}=l,I=this._room.remotePublishedUserMap.get(h),T=u.audioAvailable,N=u.videoAvailable,{audioAvailable:$,videoAvailable:x}=l;$||this._remoteAudioConfigMap.delete(h),x||this._remoteVideoConfigMap.delete(`${h}_${"main"}`),l.hasAuxiliary||this._remoteVideoConfigMap.delete(`${h}_${"sub"}`),T!==$&&this.emit($?X.REMOTE_AUDIO_AVAILABLE:X.REMOTE_AUDIO_UNAVAILABLE,{userId:h}),N!==x&&this.emit(x?X.REMOTE_VIDEO_AVAILABLE:X.REMOTE_VIDEO_UNAVAILABLE,{userId:h,streamType:"main"}),u.hasAuxiliary!==l.hasAuxiliary&&this.emit(l.hasAuxiliary?X.REMOTE_VIDEO_AVAILABLE:X.REMOTE_VIDEO_UNAVAILABLE,{userId:h,streamType:"sub"})}).add("firewall-restriction",()=>{this.emit(X.ERROR,new j({code:q.OPERATION_FAILED,extraCode:5501}))}).add("sei-message",u=>{this.emit(X.SEI_MESSAGE,u)}),this._handleReceiveMode(),yield this._room.join(a,r,Hn.frameWorkType),this._checkTrackToPublish()})}exitRoom(){return E(this,null,function*(){return yield this._exitRoom()})}switchRole(e){return E(this,null,function*(){yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){He(Te),this.removeAllListeners(),this._room.destroy(),wc.delete(this),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare()}startLocalAudio(){return E(this,arguments,function*(e={publish:!0}){if(this._localAudioTrack){this._log.warn("local audio is already started");return}let{publish:r=!0,option:n}=e,s=new Jt,o={},a={muted:!0};n&&(b(n.microphoneId)?b(n.audioTrack)||(o.customSource=n.audioTrack):o.deviceId=n.microphoneId,b(n.captureVolume),b(n.profile)||(oe(n.profile)?Ps[n.profile]&&s.setProfile(Ps[n.profile]):s.setProfile(n.profile)),de(n.earMonitorVolume)&&(a.muted=!(n.earMonitorVolume>0),a.volume=n.earMonitorVolume),b(n.echoCancellation)||(s.profile.echoCancellation=n.echoCancellation),b(n.noiseSuppression)||(s.profile.noiseSuppression=n.noiseSuppression),b(n.autoGainControl)||(s.profile.autoGainControl=n.autoGainControl)),s.on("5",c=>{this.emit(X.ERROR,new j({code:q.DEVICE_ERROR,extraCode:5309,messageParams:{error:c}}))}),s.on("2",c=>{this.emit(X.DEVICE_CHANGED,{type:"microphone",action:"active",device:c})}),s.on("4",c=>{let d;c.error&&(d=j.convertFrom(c.error)),this.emit(X.PUBLISH_STATE_CHANGED,ee(w({},c),{error:d}))}),yield s.capture(o),ct(s,s).add("player-state-changed",c=>{this.emit(X.AUDIO_PLAY_STATE_CHANGED,ee(w({},c),{userId:""}))}),yield this._updateAudioPlayOption({playOption:a,track:s}),r&&this._room.isJoined&&this._room.publish(s).catch(()=>{}),this._localAudioTrack=s,this._localAudioConfig=ee(w({},e),{publish:r})})}updateLocalAudio(e){return E(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:r,mute:n,option:s}=e,o={};s&&(s.microphoneId?yield this._localAudioTrack.switchDevice(s.microphoneId):b(s.audioTrack)||(this._localAudioTrack.setMediaStreamTrack(s.audioTrack),yield this._room.replaceTrack(this._localAudioTrack)),b(s.captureVolume),b(s.earMonitorVolume)||(o.muted=!(s.earMonitorVolume>0),o.volume=s.earMonitorVolume)),yield this._updateAudioPlayOption({playOption:o,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),this._room.isJoined&&!b(r)&&(r&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!r&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),b(n)||this._localAudioTrack.setMute(n),bt(this._localAudioConfig,e)})}stopLocalAudio(){return E(this,null,function*(){!this._localAudioTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),this._localAudioTrack.stop(),this._localAudioTrack.close(),He(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)})}startLocalVideo(){return E(this,arguments,function*(e={publish:!0,view:null}){if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:r,publish:n=!0,option:s}=e,o=new St,a={},c={};if(s&&(s.cameraId?a.deviceId=s.cameraId:b(s.useFrontCamera)?b(s.videoTrack)||(a.customSource=s.videoTrack):a.facingMode=s.useFrontCamera?m.FACING_MODE_USER:m.FACING_MODE_ENVIRONMENT,b(s.profile)||(oe(s.profile)?ki[s.profile]&&o.setProfile(ki[s.profile]):o.setProfile(s.profile)),b(s.fillMode)||(c.objectFit=s.fillMode),b(s.mirror)||(c.mirror=s.mirror),b(s.small)||(Ws()?oe(s.small)?o.small=ki[s.small]:o.small=s.small:this._log.warn("small stream is not supported"))),o.on("5",d=>{this.emit(X.ERROR,new j({code:q.DEVICE_ERROR,extraCode:5308,messageParams:{error:d}}))}),o.on("2",d=>{this.emit(X.DEVICE_CHANGED,{type:"camera",action:"active",device:d})}),o.on("4",d=>{let u;d.error&&(u=j.convertFrom(d.error)),this.emit(X.PUBLISH_STATE_CHANGED,ee(w({},d),{error:u}))}),yield o.capture(a),(s==null?void 0:s.qosPreference)&&o.mediaTrack){let d=$n(s.qosPreference);o.mediaTrack.contentHint=d}ct(o,o).add("player-state-changed",d=>{this.emit(X.VIDEO_PLAY_STATE_CHANGED,ee(w({},d),{userId:"",streamType:"main"}))}),yield this._updateVideoPlayOption({view:r,playOption:c,track:o}),n&&this._room.isJoined&&this._room.publish(o).catch(()=>{}),this._localVideoTrack=o,this._localVideoConfig=ee(w({},e),{view:r,publish:n})})}updateLocalVideo(e){return E(this,null,function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:r,publish:n,mute:s,option:o}=e,a={};if(o&&(o.cameraId?yield this._localVideoTrack.switchDevice(o.cameraId):b(o.useFrontCamera)?b(o.videoTrack)||(this._localVideoTrack.setMediaStreamTrack(o.videoTrack),yield this._room.replaceTrack(this._localVideoTrack)):yield this._localVideoTrack.switchDevice(o.useFrontCamera?m.FACING_MODE_USER:m.FACING_MODE_ENVIRONMENT),b(o.profile)||(oe(o.profile)?ki[o.profile]&&this._localVideoTrack.setProfile(ki[o.profile]):this._localVideoTrack.setProfile(o.profile)),b(o.fillMode)||(a.objectFit=o.fillMode),b(o.mirror)||(a.mirror=o.mirror),o.qosPreference&&this._localVideoTrack.mediaTrack)){let c=$n(o.qosPreference);this._localVideoTrack.mediaTrack.contentHint=c}yield this._updateVideoPlayOption({view:r,playOption:a,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),this._room.isJoined&&!b(n)&&(n&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._localVideoConfig.publish&&!n&&this._room.unpublish(this._localVideoTrack).catch(()=>{})),b(s)||this._localVideoTrack.setMute(s),bt(this._localVideoConfig,e)})}stopLocalVideo(){return E(this,null,function*(){!this._localVideoTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),He(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return E(this,arguments,function*(e={publish:!0,view:null}){if(this._localScreenTrack){this._log.warn("screen share is already started");return}let{view:r=null,publish:n=!0,option:s}=e,o=new Mt;o.on("4",l=>{let h;l.error&&(h=j.convertFrom(l.error)),this.emit(X.PUBLISH_STATE_CHANGED,ee(w({},l),{error:h}))});let a=null;o.setMediaType(2);let c={},d={};s&&(b(s.profile)||(oe(s.profile)?Ms[s.profile]&&o.setProfile(Ms[s.profile]):o.setProfile(s.profile)),s.systemAudio&&(c.systemAudio=!0,c.echoCancellation=s.echoCancellation,c.noiseSuppression=s.noiseSuppression,c.autoGainControl=s.autoGainControl),b(s.fillMode)||(d.objectFit=s.fillMode),s.videoTrack&&(c.videoTrack=s.videoTrack),s.audioTrack&&(c.audioTrack=s.audioTrack));let u=yield o.capture(c);if(s!=null&&s.qosPreference){let l=$n(s.qosPreference);o.mediaTrack.contentHint=l}if(o.mediaTrack.addEventListener(m.ENDED,()=>{this._stopScreenShare(),this.emit(X.SCREEN_SHARE_STOPPED)}),u.getAudioTracks()[0]&&(a=new ji,a.setScreenAudioTrack(u.getAudioTracks()[0],u)),ct(o,o).add("player-state-changed",l=>{this.emit(X.VIDEO_PLAY_STATE_CHANGED,ee(w({},l),{userId:"",streamType:"sub"}))}),yield this._updateVideoPlayOption({view:r,playOption:d,track:o}),n&&this._room.isJoined){let l=[o];a&&l.push(a),this._room.publish(...l).catch(()=>{})}this._localScreenTrack=o,this._localScreenAudioTrack=a,this._localScreenConfig=ee(w({},e),{view:r,publish:n})})}updateScreenShare(e){return E(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:r,publish:n,option:s}=e,o={};if(s&&(b(s.fillMode)||(o.objectFit=s.fillMode),s.qosPreference)){let a=$n(s.qosPreference);this._localScreenTrack.mediaTrack.contentHint=a}yield this._updateVideoPlayOption({view:r,playOption:o,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),this._room.isJoined&&!b(n)&&(n&&!this._localScreenConfig.publish&&this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenConfig.publish&&!n&&this._room.unpublish(this._localScreenTrack).catch(()=>{})),bt(this._localScreenConfig,e)})}stopScreenShare(){return E(this,null,function*(){return yield this._stopScreenShare()})}startPlugin(e,r){return E(this,null,function*(){return e.start(r)})}updatePlugin(e,r){return E(this,null,function*(){return e.update(r)})}stopPlugin(e,r){return E(this,null,function*(){return e.stop(r)})}startRemoteVideo(e){return E(this,null,function*(){let{view:r,userId:n,streamType:s,option:o}=e,a=`${n}_${s}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${n}, streamType:${s}`);return}let c=this._room.remotePublishedUserMap.get(n);if(!c)return;let d={},u=s==="main"?c.remoteVideoTrack:c.remoteAuxiliaryTrack;o&&(b(o.fillMode)||(d.objectFit=o.fillMode),b(o.mirror)||(d.mirror=o.mirror),s==="main"&&!b(o.small)&&this._room.changeType(o.small,u.user)),yield this._room.subscribe(u),yield this._updateVideoPlayOption({view:r,playOption:d,track:u}),this._remoteVideoConfigMap.set(a,e)})}updateRemoteVideo(e){return E(this,null,function*(){let{view:r,userId:n,streamType:s,option:o}=e,a=`${n}_${s}`;if(!this._remoteVideoConfigMap.has(a)||!this._room.remotePublishedUserMap.has(n))return;let c={};o&&(b(o.fillMode)||(c.objectFit=o.fillMode),b(o.mirror)||(c.mirror=o.mirror));let d=null,u=this._room.remotePublishedUserMap.get(n);s==="main"&&(u==null?void 0:u.muteState.hasVideo)&&(d=u.remoteVideoTrack),s==="sub"&&(u==null?void 0:u.muteState.hasAuxiliary)&&(d=u.remoteAuxiliaryTrack);let l=this._remoteVideoConfigMap.get(a);d&&(s==="main"&&o&&!b(o.small)&&this._room.changeType(o.small,d.user),yield this._updateVideoPlayOption({view:r,playOption:c,track:d,prevConfig:l})),bt(l,e)})}stopRemoteVideo(e){return E(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,r=!0){return E(this,null,function*(){let n=[],s=this._room.remotePublishedUserMap.get(e.userId);if(s){let{muteState:o,remoteVideoTrack:a,remoteAuxiliaryTrack:c}=s;e.streamType==="main"&&(a.stop(),o.hasVideo&&n.push(a)),e.streamType==="sub"&&(c.stop(),o.hasAuxiliary&&n.push(c))}for(let o of n)r&&(yield this._room.unsubscribe(o));this._remoteVideoConfigMap.delete(`${e.userId}_${e.streamType}`)})}muteRemoteAudio(e,r){return E(this,null,function*(){if(e==="*")if(r)yield this._stopRemoteAudio({userId:e});else{let n=[...this._room.remotePublishedUserMap.values()];for(let s of n)s.muteState.hasAudio&&(yield this._startRemoteAudio({userId:s.userId}))}else r?yield this._stopRemoteAudio({userId:e}):yield this._startRemoteAudio({userId:e});this._remoteAudioMuteMap.set(e,r)})}setRemoteAudioVolume(e,r){if(e==="*"){let n=[...this._room.remotePublishedUserMap.values()];for(let s of n)this._updateAudioPlayOption({playOption:{volume:r},track:s.remoteAudioTrack})}else if(e){let n=this._room.remotePublishedUserMap.get(e);n&&this._updateAudioPlayOption({playOption:{volume:r},track:n.remoteAudioTrack})}}enableAudioVolumeEvaluation(e=2e3,r=!1){this._room.enableAudioVolumeEvaluation(e,r)}startMixTranscode(e){let r=w({},e);return r.mixUsers=e.mixUsers.map(n=>{let s=w({},n);return b(n.streamType)||(s.streamType=ho(n.streamType)),s}),this._room.startMixTranscode(r)}stopMixTranscode(){return this._room.stopMixTranscode()}startPublishCDNStream(e){let r=w({},e);return b(e.streamType)||(r.streamType=ho(e.streamType)),this._room.startPublishCDNStream(r)}stopPublishCDNStream(){return this._room.stopPublishCDNStream()}on(e,r,n){return super.on(e,r,n),this._eventListened.add(e),this}off(e,r,n){return e==="*"?(this._eventListened.clear(),this.removeAllListeners()):super.off(e,r,n),this}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:r="",streamType:n="main"}=e;if(r===""){if(n==="main"&&this._localVideoTrack)return this._localVideoTrack.mediaTrack;if(n==="sub"&&this._localScreenTrack)return this._localScreenTrack.mediaTrack}else{let s=this._room.remotePublishedUserMap.get(r);if(s)return n==="main"?s.remoteVideoTrack.mediaTrack:s.remoteAuxiliaryTrack.mediaTrack}return null}getAudioTrack(e){if(e){let r=this._room.remotePublishedUserMap.get(e);if(r)return r.remoteAudioTrack.mediaTrack}else if(this._localAudioTrack)return this._localAudioTrack.mediaTrack;return null}setCurrentSpeaker(e){var r;(r=this._localAudioTrack)==null||r.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(n=>n.remoteAudioTrack.setAudioOutput(e))}_startRemoteAudio(e){return E(this,null,function*(){let{userId:r,option:n}=e;if(this._remoteAudioConfigMap.has(r)){this._log.warn(`remote audio has already started. userId:${r}`);return}let s=this._room.remotePublishedUserMap.get(r);if(!s)return;let o={};n&&(b(n.volume)||(o.volume=n.volume));let a=s.remoteAudioTrack;yield this._room.subscribe(a),yield this._updateAudioPlayOption({playOption:o,track:a}),this._remoteAudioConfigMap.set(r,e)})}_stopRemoteAudio(e,r=!0){return E(this,null,function*(){let n=this._room.remotePublishedUserMap.get(e.userId);n&&(n.remoteAudioTrack.stop(),n.muteState.hasAudio&&r&&(yield this._room.unsubscribe(n.remoteAudioTrack))),this._remoteAudioConfigMap.delete(`${e.userId}`)})}_updateVideoPlayOption(o){return E(this,arguments,function*({view:e,playOption:r,track:n,prevConfig:s}){if(b(e)&&s&&s.view&&!Nn(r)){let a;Oe(s.view)?a=s.view:a=Hs(s.view),a&&(yield n.play(a,r))}if(!b(e)){let a;Oe(e)?a=e:a=Hs(e),a?yield n.play(a,r):n.stop()}})}_updateAudioPlayOption(s){return E(this,arguments,function*({playOption:e={},track:r,prevConfig:n}){r.isPlayCalled||(yield r.play(null,e)),b(e.muted)||r.setPlayerMute(e.muted),b(e.volume)||r.setAudioVolume(e.volume/100)})}_checkTrackToPublish(){var r,n,s;let e=[];if(((r=this._localAudioConfig)==null?void 0:r.publish)&&this._localAudioTrack&&e.push(this._localAudioTrack),((n=this._localVideoConfig)==null?void 0:n.publish)&&this._localVideoTrack&&e.push(this._localVideoTrack),(s=this._localScreenConfig)!=null&&s.publish&&(this._localScreenTrack&&e.push(this._localScreenTrack),this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack)),e.length!==0)return this._room.publish(...e).catch(()=>{})}_handleReceiveMode(){this._room.autoReceiveAudio&&ct(this,this).add(X.REMOTE_AUDIO_AVAILABLE,r=>E(this,[r],function*({userId:e}){if(this._remoteAudioMuteMap.get("*")||this._remoteAudioMuteMap.get(e))return;let n=this._room.remotePublishedUserMap.get(e);n&&(yield this._room.subscribe(n.remoteAudioTrack).catch(()=>{}),yield this._updateAudioPlayOption({track:n.remoteAudioTrack}).catch(()=>{}),this._remoteAudioConfigMap.set(e,{userId:e}))})),this._room.autoReceiveVideo&&ct(this,this).add(X.REMOTE_VIDEO_AVAILABLE,({userId:e,streamType:r})=>{let n=this._room.remotePublishedUserMap.get(e);n&&(r==="main"?this._room.subscribe(n.remoteVideoTrack).catch(()=>{}):r==="sub"&&this._room.subscribe(n.remoteAuxiliaryTrack).catch(()=>{}))})}_exitRoom(){return E(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),[...this._remoteAudioConfigMap.keys()].forEach(e=>{this._stopRemoteAudio({userId:e}).catch()}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let r=e.includes("main")?"main":"sub",n=e.split(`_${r}`)[0];n&&this._stopRemoteVideo({userId:n,streamType:r}).catch()}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._room.remotePublishedUserMap.forEach(e=>{He(e.remoteAudioTrack),He(e.remoteVideoTrack),He(e.remoteAuxiliaryTrack)}),He(this)})}_stopScreenShare(){return E(this,null,function*(){var e,r,n;if(!!this._localScreenTrack){if(this._room.isJoined){let s=[this._localScreenTrack];this._localScreenAudioTrack&&s.push(this._localScreenAudioTrack),yield(e=this._room)==null?void 0:e.unpublish(...s).catch(()=>{})}this._localScreenTrack.stop(),this._localScreenTrack.close(),(r=this._localScreenAudioTrack)==null||r.stop(),(n=this._localScreenAudioTrack)==null||n.close(),He(this._localScreenTrack),this._localScreenTrack=null,this._localScreenAudioTrack=null,this._localScreenConfig=null}})}sendSEIMessage(e,r){this._room.sendSEI(e,r||{seiPayloadType:243})}static setLogLevel(e,r){O.setLogLevel(e),b(r)||(r?O.enableUploadLog():O.disableUploadLog())}static isSupported(){return Ma()}static getCameraList(){return dt()}static getMicrophoneList(){return Xe()}static getSpeakerList(){return Lr()}static setCurrentSpeaker(e){return E(this,null,function*(){(yield Lr()).forEach(n=>{n.deviceId===e&&(wc.forEach(s=>{s.setCurrentSpeaker(e),s.emit(X.DEVICE_CHANGED,{type:"speaker",action:"active",device:n})}),ze=n)})})}},re=Hn;p(re,"_loggerManager",O),p(re,"EVENT",X),p(re,"ERROR_CODE",q),p(re,"TYPE",Bn),p(re,"frameWorkType",30),H([Ve(De.TRTC.enterRoom),gi("room",([i],[t])=>i.roomId===t.roomId&&i.userId===t.userId&&i.sdkAppId===t.sdkAppId),ae(i=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),i.call(this,t).catch(e=>{throw He(this),e})}),ve()],re.prototype,"enterRoom",1),H([ve()],re.prototype,"exitRoom",1),H([Ve(De.TRTC.switchRole),Xi("room",(i,t)=>t),ve()],re.prototype,"switchRole",1),H([ve()],re.prototype,"destroy",1),H([Ve(De.TRTC.startLocalAudio),gi("audio",([i],[t])=>{var e,r;return((e=i==null?void 0:i.option)==null?void 0:e.microphoneId)===((r=t==null?void 0:t.option)==null?void 0:r.microphoneId)}),ve()],re.prototype,"startLocalAudio",1),H([Ve(De.TRTC.updateLocalAudio),Xi("audio"),ve()],re.prototype,"updateLocalAudio",1),H([Ii("audio"),ve()],re.prototype,"stopLocalAudio",1),H([Ve(De.TRTC.startLocalVideo),gi("video",([i],[t])=>{var e,r;return((e=i==null?void 0:i.option)==null?void 0:e.cameraId)===((r=t==null?void 0:t.option)==null?void 0:r.cameraId)}),ve()],re.prototype,"startLocalVideo",1),H([Ve(De.TRTC.updateLocalVideo),Xi("video"),ve()],re.prototype,"updateLocalVideo",1),H([Ii("video"),ve()],re.prototype,"stopLocalVideo",1),H([Ve(De.TRTC.startScreenShare),gi("screen",()=>!0),ve()],re.prototype,"startScreenShare",1),H([Ve(De.TRTC.updateScreenShare),Xi("screen"),ve()],re.prototype,"updateScreenShare",1),H([ve()],re.prototype,"stopScreenShare",1),H([Eo("start"),gi((i,t)=>i.getAlias()+i.getGroup(t))],re.prototype,"startPlugin",1),H([Eo("update"),Xi((i,t)=>i.getAlias()+i.getGroup(t))],re.prototype,"updatePlugin",1),H([Eo("stop"),Ii((i,t)=>i.getAlias()+i.getGroup(t))],re.prototype,"stopPlugin",1),H([Ve(De.TRTC.startRemoteVideo),gi(i=>`v${i.userId}${i.streamType}`,()=>!0),ve()],re.prototype,"startRemoteVideo",1),H([Ve(De.TRTC.updateRemoteVideo),Xi(i=>`v${i.userId}${i.streamType}`),ve()],re.prototype,"updateRemoteVideo",1),H([Ve(De.TRTC.stopRemoteVideo),ae(i=>function(t){return E(this,null,function*(){if(t.userId==="*"){let e=[];return this._room.remotePublishedUserMap.forEach(r=>{this._remoteVideoConfigMap.has(`${r.userId}_${"main"}`)&&e.push(this.stopRemoteVideo({streamType:"main",userId:r.userId}).catch(()=>{})),this._remoteVideoConfigMap.has(`${r.userId}_${"sub"}`)&&e.push(this.stopRemoteVideo({streamType:"sub",userId:r.userId}).catch(()=>{}))}),Promise.all(e)}return i.call(this,t)})}),ve()],re.prototype,"stopRemoteVideo",1),H([Ii(i=>`v${i.userId}${i.streamType}`)],re.prototype,"_stopRemoteVideo",1),H([Ve(...De.TRTC.muteRemoteAudio),ve()],re.prototype,"muteRemoteAudio",1),H([Vc(...De.TRTC.setRemoteAudioVolume),Rl(200,i=>i),ve()],re.prototype,"setRemoteAudioVolume",1),H([Vc(...De.TRTC.enableAudioVolumeEvaluation)],re.prototype,"enableAudioVolumeEvaluation",1),H([Ve(De.TRTC.startMixTranscode)],re.prototype,"startMixTranscode",1),H([gi(i=>`a${i.userId}`,()=>!0)],re.prototype,"_startRemoteAudio",1),H([ae(i=>function(t){return E(this,null,function*(){return t.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(e=>this._stopRemoteAudio(ee(w({},t),{userId:e.userId})).catch(()=>{}))):i.call(this,t)})}),Ii(i=>`a${i.userId}`)],re.prototype,"_stopRemoteAudio",1),H([Ii("room")],re.prototype,"_exitRoom",1),H([Ii("screen")],re.prototype,"_stopScreenShare",1),H([Ve(De.TRTC.sendSEIMessage),al({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...i)=>i[0].byteLength})],re.prototype,"sendSEIMessage",1),H([Ve(De.TRTC.create)],re,"_create",1);var Fn=re;var tU=_(f());var ED=_(f(),1);var Bc=class{constructor(){this._set=new Set;C.on(S.LEAVE_SUCCESS,this.delete,this)}add({room:t,roomId:e}){if(t.scene==="rtc")return;let r=this.getKey(t.userId,e||t.roomId,t.sdkAppId,t.useStringRoomId);this._set.add(r)}delete({room:t,roomId:e}){if(t.scene==="rtc")return;let r=this.getKey(t.userId,t.roomId||e,t.sdkAppId,t.useStringRoomId);this._set.delete(r)}getKey(t,e,r,n){return`${r}_${e}_${t}_${n}`}isJoined({userId:t,roomId:e,sdkAppId:r,room:n}){return n.scene==="rtc"?!1:this._set.has(this.getKey(t,e,r,n.useStringRoomId))}};function df(){return E(this,null,function*(){let i,t;try{let l=yield Xe();i=l&&l.length}catch(l){}try{let l=yield dt();t=l&&l.length}catch(l){}let e={microphone:i,camera:t},{isH264EncodeSupported:r,isVp8EncodeSupported:n,isH264DecodeSupported:s,isVp8DecodeSupported:o}=this.checkSystemResult.detail,a=Gt.basis(),c={webRTC:a.isWebRTCSupported,getUserMedia:a.isGetUserMediaSupported,webSocket:a.isWebSocketsSupported,screenShare:a.isScreenShareSupported,webAudio:a.isWebAudioSupported,h264Encode:r,h264Decode:s,vp8Encode:n,vp8Decode:o},d={browser:a.browser,os:a.os,trtc:c,devices:e},u={isWebCodecSupported:a.isWebCodecSupported,isMediaSessionSupported:a.isMediaSessionSupported,isWebTransportSupported:a.isWebTransportSupported};_e.uploadEvent({log:`trtcstats-${JSON.stringify(d)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(d)}`),_e.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(u)}`,userId:this.userId})})}function Nl(){return ae(i=>{let t=new Bc;return function(e,r,n){return E(this,null,function*(){let s=String(e.roomId||e.strRoomId);if(this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.userSig=e.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=r,e.privateMapKey=e.privateMapKey||"",this.isJoined)throw new M({code:v.INVALID_OPERATION,message:B({key:V.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:s,sdkAppId:this.sdkAppId,room:this}))throw new M({code:v.INVALID_OPERATION,message:B({key:V.REPEAT_JOIN,data:this.userId})});t.add({room:this,roomId:s}),this._log.info(`Join() => joining room: ${s} useStringRoomId: ${this.useStringRoomId} scene: ${this.scene} role: ${this.role}`),this.role=e.role===21?"audience":"anchor",C.emit(S.JOIN_START,{room:this,roomId:s,params:e}),this.checkSystemResult=yield Gt.checkSystemRequirementsInternal(),this.checkDestroy();let o=ke.getEnv();o||(o=wt.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(Ls.OLD_CLOUD_LADDER)?o=wt.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(Ls.WEBRTC)&&(o=wt.WEBRTC))),_e.setConfig({env:o,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:s}),df.call(this);let{isH264EncodeSupported:a,isVp8EncodeSupported:c}=this.checkSystemResult.detail;if(!Gt.isWebRTCSupported()||!a&&!c)throw new M({code:v.NOT_SUPPORTED,message:B({key:V.NOT_SUPPORTED_WEBRTC})});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!ke.getEnv()&&(yield this.schedule(s,n,$e));let d=yield i.call(this,e,r,n);return this.roomId=s,this._joinedTimestamp=ke.performanceNow(),C.emit(S.JOIN_SUCCESS,{room:this}),_e.uploadEvent({log:`stat-conv-${Number(mt)}-${location.hostname}`,userId:this.userId}),d}catch(d){throw t.delete({room:this,roomId:s}),C.emit(S.JOIN_FAILED,{room:this,error:d}),d}})}})}var CD=_(f(),1);var bl=()=>ae(i=>function(...t){return E(this,null,function*(){C.emit(S.LEAVE_START,{room:this}),yield i.call(this),C.emit(S.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});var HD=_(f()),Ol=_(rt());var ND=_(f()),Se={SETUP_SUCCESS:"1",SETUP_FAILED:"5",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",RECONNECT_FAILED:"4"},qe={DISCONNECTED:"DISCONNECTED",CONNECTING:"CONNECTING",CONNECTED:"CONNECTED"},Lt={CLIENT_BANNED:9,CHANNEL_SETUP_RESULT:19,CHANNEL_RECONNECT_RESULT:514,JOIN_ROOM_RESULT:20,PEER_JOIN:4134,PEER_LEAVE:4135,STREAM_ADDED:16,STREAM_REMOVED:18,UPLINK_NETWORK_STATS:22,UPDATE_REMOTE_MUTE_STAT:23,PUBLISH_RESULT:4098,PUBLISH_STATE_CHANGE_RESULT:4112,UNPUBLISH_RESULT:4100,SUBSCRIBE_RESULT:4102,UNSUBSCRIBE_RESULT:4104,SUBSCRIBE_CHANGE_RESULT:4106,MUTE_RESULT:4108,UPDATE_OFFER_RESULT:4128,START_PUBLISH_TENCENT_CDN_RES:1286,STOP_PUBLISH_TENCENT_CDN_RES:1288,START_PUBLISH_GIVEN_CDN_RES:777,STOP_PUBLISH_GIVEN_CDN_RES:779,START_MIX_TRANSCODE_RES:781,STOP_MIX_TRANSCODE_RES:783,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772,REBUILD_PEER_CONNECTION_RES:4150,SPC_PUBLISH_RESULT:4146,SPC_SUBSCRIBE_RESULT:4156},Dl=[Lt.UPDATE_REMOTE_MUTE_STAT,Lt.UPLINK_NETWORK_STATS,Lt.USER_LIST_RES,Lt.MUTE_RESULT],Q={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",USER_LIST_RES:"user-list-res",SWITCH_ROLE_RES:"switch_role_res",MUTE_RESULT:"mute-result",UPDATE_CONSTRAINT_CONFIG_RES:"update-contraint-config-res",REBUILD_PEER_CONNECTION_RES:"rebuild-pc-res",SPC_PUBLISH_RESULT:"spc-publish-result",SPC_SUBSCRIBE_RESULT:"spc-subscribe-result"},ne={PUBLISH_CHANGE:"publish_change",JOIN_ROOM:"join",LEAVE_ROOM:"leave",ON_QUALITY_REPORT:"quality_report",UPDATE_MUTE_STAT:"mute_uplink",PUBLISH:"publish",PUBLISH_STATE_CHANGE:"publish_state_change",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",RECEIVE_DATA_USER_LIST:"receive_data_userlist",UNSUBSCRIBE:"unsubscribe",SUBSCRIBE_CHANGE:"subscribe_change",START_PUBLISH_TENCENT_CDN:"start_publishing",STOP_PUBLISH_TENCENT_CDN:"stop_publishing",START_PUBLISH_GIVEN_CDN:"start_push_user_cdn",STOP_PUBLISH_GIVEN_CDN:"stop_push_user_cdn",START_MIX_TRANSCODE:"start_mcu_mix",STOP_MIX_TRANSCODE:"stop_mcu_mix",GET_USER_LIST:"get_user_list",SWITCH_ROLE:"change_role",UPDATE_CONSTRAINT_CONFIG:"update_constraint_config",REBUILD_PEER_CONNECTION:"rebuild_pc",READY_TO_RECEIVE_DATA:"ready_to_receive",SPC_JOIN_ROOM:"join/v2",SPC_PUBLISH:"publish/v2",SPC_SUBSCRIBE:"subscribe/v3"};var Gn=class{constructor(t){p(this,"_room");p(this,"_sdkAppId");p(this,"_userId");p(this,"_userSig");p(this,"_url");p(this,"_backupUrl");p(this,"_urlWithParam");p(this,"_backupUrlWithParam");p(this,"_socketInUse");p(this,"_socket");p(this,"_backupSocket");p(this,"_backupTimer",-1);p(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0});p(this,"_currentState",qe.DISCONNECTED);p(this,"_reconnectionCount",0);p(this,"_reconnectionTimer",-1);p(this,"_seq",0);p(this,"_log");p(this,"_emitter");p(this,"_lastMessageTime",-1);p(this,"_prevTime",-1);this._room=t.room,this._sdkAppId=t.sdkAppId,this._userId=t.userId,this._userSig=t.userSig,this._url=t.url,this._backupUrl=t.backupUrl;let e=`?sdkAppId=${encodeURIComponent(this._sdkAppId)}&userId=${encodeURIComponent(this._userId)}&userSig=${encodeURIComponent(this._userSig)}`;this._urlWithParam=`${this._url}${e}`,this._backupUrlWithParam=`${this._backupUrl}${e}`,this._seq=0,this._log=O.createLogger({id:"ws",userId:this._userId,sdkAppId:this._sdkAppId}),this._emitter=new Ol.default}get isConnected(){return this._currentState===qe.CONNECTED}get isConnecting(){return this._currentState===qe.CONNECTING}get isOnline(){return this._currentState===qe.CONNECTED&&Date.now()-this._lastMessageTime<12*1e3}connect(){return new Promise((t,e)=>{this._prevTime<0&&(this._prevTime=z()),this._log.info(`connect to ${this._url}`),this.emitConnectionStateChanged(qe.CONNECTING),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),this.once(Se.CONNECTED,t),this.once(Se.RECONNECT_FAILED,e)})}tryConnectBackup(){this._backupSocket||(this.unbindAndCloseSocket(m.MAIN),this._log.debug(`try to connect to url: ${this._backupUrlWithParam}`),this._backupSocket=new WebSocket(this._backupUrlWithParam),this.bindSocket(this._backupSocket))}bindSocket(t){t.onopen=this.onopen.bind(this),t.onclose=this.onclose.bind(this),t.onerror=this.onerror.bind(this),t.onmessage=this.onmessage.bind(this)}unbindSocket(t){this.clearBackupTimer(),t.onopen=()=>{},t.onclose=()=>{},t.onerror=()=>{},t.onmessage=()=>{}}unbindAndCloseSocket(t){if(t===m.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(e){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(e){}this._backupSocket=null}}clearBackupTimer(){this._backupTimer!==-1&&(clearTimeout(this._backupTimer),this._backupTimer=-1)}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}onopen(t){if(this.isConnected)return;this.isReconnecting&&!this._signalInfo.tinyId&&this.stopReconnection(),this.clearBackupTimer(),t.target===this._socket?(this.unbindAndCloseSocket(m.BACKUP),this._socketInUse=this._socket):(this.unbindAndCloseSocket(m.MAIN),this._socketInUse=this._backupSocket),this.emitConnectionStateChanged(qe.CONNECTED),this._emitter.emit(Se.CONNECTED)}onclose(t){let{url:e}=t.target,r=t.target===this._socketInUse;if(this._log.info(`websocket[${e} InUse: ${r}] is closed with code: ${t.code}`),r&&(this.emitConnectionStateChanged(qe.DISCONNECTED),!t.wasClean||t.code!==1e3)){this._log.warn(`onclose code:${t.code} reason:${t.reason}`),this._log.warn("close current websocket and schedule a reconnect timeout"),this._socketInUse.onclose=()=>{},this._socketInUse.close(4011);let n=this._socketInUse===this._socket;this._socket=null,this._backupSocket=null,this._socketInUse=null,this.reconnect(n?m.BACKUP:m.MAIN)}}onerror(t){let{url:e}=t.target;if(this._log.error(`websocket[${e}] error observed`),!this.isConnected)this.isReconnecting||C.emit(S.API_SUCCESS_RATE,{room:this._room,apiName:"WebsocketConnect",error:new Error("ws onerror")}),t.target==this._socket?(this.unbindAndCloseSocket(m.MAIN),this.reconnect(m.BACKUP)):(this.unbindAndCloseSocket(m.BACKUP),this.reconnect(m.MAIN));else if(t.target===this._socketInUse){this.unbindAndCloseSocket(m.MAIN),this.unbindAndCloseSocket(m.BACKUP);let r=this._socketInUse===this._socket;this._socketInUse=null,this.reconnect(r?m.BACKUP:m.MAIN)}}onmessage(t){if(!this.isConnected)return;this._lastMessageTime=Date.now();let e=JSON.parse(t.data),{cmd:r,data:n}=e,s=Object.values(Lt),a=Object.keys(Lt)[s.indexOf(r)],c=Q[a];switch(Dl.includes(r)||(this._log.debug(`received msg: ${t.data}`),this._log.info(`Received event: [ ${c||`unknown cmd: ${r}`} ]`)),r){case Lt.CHANNEL_SETUP_RESULT:{if(e.code===0)this._signalInfo.clientIp=n.clientIp,this._signalInfo.signalIp=n.signalInnerIp,this._signalInfo.tinyId=e.tinyId,n.svrTime&&iu(n.svrTime),this._log.info("ChannelSetup Success"),C.emit(S.API_SUCCESS_RATE,{room:this._room,apiName:"WebsocketConnect",cost:z()-this._prevTime}),this._prevTime=-1,this._emitter.emit(Se.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let d=new M({code:v.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:e.code,message:B({key:V.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:e.code,errorMsg:e.message}})});this._log.error(`${e.code}, ${e.message}`),this.close(),C.emit(S.API_SUCCESS_RATE,{room:this._room,apiName:"WebsocketConnect",error:d}),this._emitter.emit(Se.SETUP_FAILED,d)}break}case Lt.JOIN_ROOM_RESULT:{e.code===0&&(this._signalInfo.relayIp=n.relayOuterIp,this._signalInfo.relayInnerIp=n.relayInnerIp,this._signalInfo.relayPort=n.relayPort,this._log.info(`signalIp:${this._signalInfo.signalIp} clientIp:${this._signalInfo.clientIp} relayIp: ${this._signalInfo.relayIp}`)),this._emitter.emit(c,{data:e});break}case Lt.CHANNEL_RECONNECT_RESULT:{e.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),C.emit(S.API_SUCCESS_RATE,{room:this._room,apiName:"WebsocketReconnect",cost:z()-this._prevTime}),this._prevTime=-1,this._room.syncUserList(),this._room.checkConnectionsToReconnect()):(this._log.warn(`reconnect failed, ${e.code} ${e.message}`),this._room.reJoin());break}default:this._emitter.emit(c,{data:e});break}}reconnect(t=m.MAIN){if(this.isReconnecting)return;if(this._reconnectionCount>=In){this._log.warn(`SDK has tried reconnect signal channel for ${In} times, but all failed. please check your network`);let n=new M({code:v.SIGNAL_CHANNEL_RECONNECTION_FAILED,message:B({key:V.SIGNAL_CHANNEL_RECONNECTION_FAILED})});C.emit(S.API_SUCCESS_RATE,{room:this._room,apiName:"WebsocketReconnect",error:n}),this._emitter.emit(Se.RECONNECT_FAILED,n);return}this._reconnectionCount++,this._log.warn(`reconnect ${t} [${this._reconnectionCount}/${In}]`);let e=this.getReconnectionUrl(t);this.emitConnectionStateChanged(qe.CONNECTING),this._prevTime<0&&(this._prevTime=z()),t===m.MAIN?(this._socket=new WebSocket(e),this.bindSocket(this._socket)):(this._backupSocket=new WebSocket(e),this.bindSocket(this._backupSocket));let r=ot(this._reconnectionCount);this._reconnectionTimer=setTimeout(()=>{this._log.warn(`reconnect ${t} timeout(${r/1e3}s), try again`),this.clearReconnectionTimer(),this.unbindAndCloseSocket(m.MAIN),this.unbindAndCloseSocket(m.BACKUP),this.reconnect(t===m.MAIN?m.BACKUP:m.MAIN)},r)}get isReconnecting(){return this._reconnectionTimer!==-1}getReconnectionUrl(t){let e=t===m.MAIN?this._urlWithParam:this._backupUrlWithParam;if(this._signalInfo.tinyId&&e.indexOf("&rc=1")===-1){let{roomId:r,useStringRoomId:n}=this._room;e+=`&rc=1&relayInnerIp=${this._signalInfo.relayInnerIp}&relayOuterIp=${this._signalInfo.relayIp}&relayPort=${this._signalInfo.relayPort}&roomId=${r}&useStringRoomId=${n}`}return e}send(t,e={}){if(this.isConnected){let r={cmd:t,data:e,userId:this._userId,tinyId:this._signalInfo.tinyId,seq:++this._seq};return this._socketInUse.send(JSON.stringify(r)),r.seq}}sendWaitForResponse({command:t,data:e,timeout:r=5e3,responseCommand:n,commandDesc:s,enableLog:o=!0}){return new Promise((a,c)=>{let d=setTimeout(()=>{this.off(n,u);let h=new M({code:v.API_CALL_TIMEOUT,message:B({key:V.API_CALL_TIMEOUT,data:{commandDesc:s,command:t}})});o&&this._log.warn(h),c(h)},r),u=h=>{h.data.seq===l&&(clearTimeout(d),this.off(n,u),a(h))};this.on(n,u);let l=this.send(t,e)})}sendWaitForResponseWithRetry(t){let{commandDesc:e,command:r,retries:n=0,retryTimeout:s=0}=t;return Dt({retryFunction:this.sendWaitForResponse,onRetrying:o=>{this._log.warn(`${e||r} timeout observed, retrying [${o}/${n}]`)},settings:{retries:n,timeout:s},context:this})(t)}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={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0},this._socketInUse=null,this.unbindAndCloseSocket(m.MAIN),this.unbindAndCloseSocket(m.BACKUP),this.emitConnectionStateChanged(qe.DISCONNECTED)}on(t,e,r){this._emitter.on(t,e,r)}removeListener(t,e,r){this._emitter.removeListener(t,e,r)}once(t,e,r){this._emitter.once(t,e,r)}off(t,e,r){this._emitter.off(t,e,r)}emitConnectionStateChanged(t){t!==this._currentState&&(this._log.info(`${this._currentState} -> ${t}`),this._emitter.emit(Se.CONNECTION_STATE_CHANGED,{prevState:this._currentState,state:t}),this._currentState=t)}};var FO=_(f());var hO=_(f()),Pl=_(rt());var zD=_(f());var WD=_(f(),1),Wn=class{constructor(t,e=!1){this.dataView=t;this.isSEI&&(e?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let t=this.seiPayloadStartIndex,e=this.dataView.byteLength-2,r=[],n=0;for(let o=t;o<=e;o++){let a=this.dataView.getInt8(o);switch(a){case 0:case 1:case 2:case 3:n===2&&(r.push(3),n=0),a==0?n++:n=0,r.push(a);break;default:n=0,r.push(a);break}}r.push(this.dataView.getInt8(this.dataView.byteLength-1));let s=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,t),...r]).buffer);this.dataView=s}removePreventionByte(){let t=this.seiPayloadStartIndex,e=this.dataView.byteLength-1,r=[],n=0;for(let o=t;o<=e;o++)switch(this.dataView.getInt8(o)){case 0:n++,r.push(this.dataView.getInt8(o));break;case 3:n!==2&&r.push(this.dataView.getInt8(o)),n=0;break;default:r.push(this.dataView.getInt8(o)),n=0;break}let s=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,t),...r]).buffer);this.dataView=s}get isSEI(){return this.dataView.getUint8(4)===6}get seiPayloadStartIndex(){let t=6;for(let e=6;e<this.dataView.buffer.byteLength&&(t++,this.dataView.getUint8(e)===255);e++);return t}get seiPayloadType(){return this.isSEI?this.dataView.getUint8(5):null}get seiPayload(){if(!this.isSEI)return null;let t=0,e=6;for(let s=6;s<this.dataView.buffer.byteLength;s++){let o=this.dataView.getUint8(s);if(e++,o===255)t+=255;else{t+=o;break}}let r=new ArrayBuffer(t),n=new DataView(r);for(let s=0;s<r.byteLength;s++,e++)n.setInt8(s,this.dataView.getInt8(e));return n}};var $c=class{constructor(t,e,r){this._connection=t;this._log=e;this._isUplink=r;p(this,"_seiMessageList",[]);p(this,"_seiPayloadType",243);p(this,"_mainVideoSenderOrReceiver",null);p(this,"_mainVideoAbortController",null);p(this,"_abortMap",new Map);p(this,"onSEIMessage")}get isRunning(){return!!this._mainVideoAbortController}start(t){this._mainVideoSenderOrReceiver=t;let e=t.createEncodedStreams(),r=e.readable,n=e.writable,s=new TransformStream({transform:this._isUplink?this.encodeVideoFrame.bind(this):this.decodeVideoFrame.bind(this)});this._mainVideoAbortController=new AbortController,r.pipeThrough(s).pipeTo(n,this._mainVideoAbortController).catch(()=>{})}restart(t){this.stop(),this.start(t)}stop(){var t;(t=this._mainVideoAbortController)==null||t.abort(),this._mainVideoAbortController=null}destroy(){this.stop(),this._abortMap.forEach(t=>t.abort()),this._abortMap.clear(),this._log=null,this.onSEIMessage=null,this._mainVideoSenderOrReceiver=null,this._connection=null}handleEncodedStreams(){try{let t=this._connection.getPeerConnection();this.clearUnusedSenderOrReceiver(t),this._isUplink?t.getSenders().forEach((e,r)=>{if(r===1){if(e===this._mainVideoSenderOrReceiver)return;this.isRunning?this.restart(e):this.start(e)}else{if(this._abortMap.has(e))return;this.pipeSenderOrReceiver(e)}}):t.getReceivers().forEach((e,r)=>{var n;this._abortMap.has(e)||e===this._mainVideoSenderOrReceiver||(r===1&&((n=e.track)==null?void 0:n.kind)===m.VIDEO?this.isRunning?this.restart(e):this.start(e):this.pipeSenderOrReceiver(e))})}catch(t){this._log.warn(t)}}pipeSenderOrReceiver(t){let{readable:e,writable:r}=t.createEncodedStreams(),n=new AbortController;this._abortMap.set(t,n),e.pipeTo(r,n).catch(()=>{})}clearUnusedSenderOrReceiver(t){this._abortMap.forEach((e,r)=>{(this._isUplink?t.getSenders():t.getReceivers()).find(s=>s===r)||(e.abort(),this._abortMap.delete(r))})}push(t,e){e&&e.seiPayloadType&&(this._seiPayloadType=e.seiPayloadType),this._seiMessageList.push(t)}hasSEI(t){let e=new DataView(t);return e.getInt32(0)===1&&e.getInt8(4)===6}isEmptyFrame(t){return t.type==="empty"||t.data.byteLength===0}getNaluCount(t){let e=0,r=0,n=new DataView(t);for(let s=0;s<t.byteLength;s++)switch(n.getUint8(s)){case 0:e++;break;case 1:(e===2||e===3)&&r++,e=0;break;default:e=0;break}return r}encodeVideoFrame(t,e){try{if(this._connection.isH264&&this._seiMessageList.length>0&&!this.isEmptyFrame(t)){let n=9-this.getNaluCount(t.data);if(n<=0)return;let s=this._seiMessageList.splice(0,n).reverse().map(this.encodeSEINalu.bind(this)),o=s.reduce((l,h)=>l+h.dataView.byteLength,0),a=new ArrayBuffer(o+t.data.byteLength),c=new DataView(a),d=new DataView(t.data),u=0;for(let l=0;l<s.length;l++)for(let h=0;h<s[l].dataView.byteLength;h++)c.setInt8(u++,s[l].dataView.getInt8(h));for(let l=0;l<t.data.byteLength;l++)c.setInt8(u++,d.getInt8(l));t.data=a,this._log.debug(`${s.length} sei sent`)}}catch(r){this._log.warn(r)}e.enqueue(t)}decodeVideoFrame(t,e){try{if(this._connection.isH264&&!this.isEmptyFrame(t)&&this.hasSEI(t.data)){let r=[],n=new DataView(t.data),s=0,o=-1,a=-1;for(let c=0;c<t.data.byteLength;c++){let d=n.getUint8(c);if(d===0)s++;else if(d===1){if(s===2||s===3){let u=c-s;if(o===-1?o=u:a===-1&&(a=u,r.push(new Wn(new DataView(n.buffer.slice(o,a)))),o=u,a=-1),!(n.getUint8(c+1)===6)){t.data=new DataView(n.buffer.slice(u)).buffer;break}}s=0}else s=0}this._log.debug(`${r.length} sei received`),ce(this.onSEIMessage)&&r.reverse().forEach(c=>{this.onSEIMessage({seiPayloadType:c.seiPayloadType,data:c.seiPayload.buffer})})}}catch(r){this._log.warn(r)}e.enqueue(t)}encodeSEINalu(t){let e=t.byteLength,r=parseInt(e/255),n=e%255,s=[];s.push(0,0,0,1,6,this._seiPayloadType);for(let a=0;a<r;a++)s.push(255);s.push(n);let o=new DataView(t);return s.push(...new Uint8Array(o.buffer)),s.push(128),new Wn(new DataView(new Uint8Array(s).buffer),!0)}},To=$c;var Hc=0,Fc=!1,So=new Set,uf=i=>Hc>2&&!Fc&&So.size===0&&i,Gc=!1,Qe=class{constructor(t){p(this,"userId");p(this,"tinyId");p(this,"_sdpSemantics");p(this,"_isUplink");p(this,"_room");p(this,"_log");p(this,"_signalChannel");p(this,"_isErrorObserved",!1);p(this,"_waitForPeerConnectionConnectedPromise");p(this,"_waitForPeerConnectionConnectedPromiseReject",null);p(this,"_peerConnection",null);p(this,"_emitter",new Pl.default);p(this,"_currentState","DISCONNECTED");p(this,"_isReconnecting",!1);p(this,"_reconnectionCount",0);p(this,"_reconnectionTimer",-1);p(this,"_isFirstConnection",!0);p(this,"_prevTime",-1);p(this,"_enableSEI");p(this,"_sei");p(this,"_localAddress");p(this,"_remoteAddress");this.userId=t.userId,this.tinyId=t.tinyId,this._room=t.room,this._sdpSemantics=t.room.sdpSemantics,this._isUplink=t.isUplink,this._log=O.createLogger({id:"n",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=t.signalChannel,this._enableSEI=t.enableSEI,this._enableSEI&&_i&&(this._sei=new To(this,this._log,this._isUplink))}beforeConnect(){this._prevTime<0&&(this._prevTime=z())}afterConnect(t){return E(this,null,function*(){try{yield t,this._isFirstConnection?(this._isFirstConnection=!1,C.emit(S.API_SUCCESS_RATE,{room:this._room,apiName:"PeerConnectionConnect",cost:Math.min(z()-this._prevTime,30*1e3)})):this._isReconnecting&&C.emit(S.API_SUCCESS_RATE,{room:this._room,apiName:"PeerConnectionReconnect",cost:z()-this._prevTime}),this._prevTime=-1}catch(e){throw this._isFirstConnection?(this._isFirstConnection=!1,C.emit(S.API_SUCCESS_RATE,{room:this._room,apiName:"PeerConnectionConnect",error:e})):this._isReconnecting&&this._reconnectionCount>=3&&C.emit(S.API_SUCCESS_RATE,{room:this._room,apiName:"PeerConnectionReconnect",error:e}),e}})}initialize(){let t={encodedInsertableStreams:this._enableSEI&&_i,iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"};this._peerConnection=new RTCPeerConnection(t),this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this)}close(t){this._log.info("close connection"),this._emitter.emit("closed",t),this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this._sei&&(this._sei.destroy(),this._sei=null),So.delete(this)}closePeerConnection(t=!1){this._peerConnection&&(this._log.info("close pc"),this._peerConnection.onconnectionstatechange=null,this._peerConnection.close(),this._peerConnection=null,t&&this.emitConnectionStateChangedEvent("DISCONNECTED")),this._waitForPeerConnectionConnectedPromiseReject&&this._waitForPeerConnectionConnectedPromiseReject(new M({code:v.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return ft;let t=null;if(this._isUplink){if(!Dr()||this._peerConnection.getSenders().length===0)return ft;t=this._peerConnection.getSenders()[0].transport}else{if(!Hi()||this._peerConnection.getReceivers().length===0)return ft;t=this._peerConnection.getReceivers()[0].transport}return t?t.state:ft}onConnectionStateChange(t){let e=this._peerConnection.iceConnectionState,r=this.getDTLSTransportState();if(this._log.info(`connectionState: ${t.target.connectionState}, ICE: ${e}, DTLS: ${r}`),t.target.connectionState===pe.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),t.target.connectionState===pe.FAILED||t.target.connectionState===pe.CLOSED){let n=`connection ${t.target.connectionState}. ICE Transport state: ${e}, DTLS Transport state: ${r}`,s=new M({message:n,code:v.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",s)}(t.target.connectionState===pe.CONNECTED||t.target.connectionState===pe.COMPLETED)&&(this.logSelectedCandidate(),_e.logSuccessEvent({userId:this._room.userId,eventType:yt.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(t){return t===this._currentState?!1:(t==="CONNECTED"?(Hc=0,Fc=!1,Gc=!0,So.add(this)):So.delete(this),C.emit(S.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:t,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:t}),this._currentState=t,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}logSelectedCandidate(){return E(this,null,function*(){if(!this._peerConnection)return;let t=yield this._peerConnection.getStats();for(let[,e]of t)if(hi(e)){let r=t.get(e.localCandidateId),n=t.get(e.remoteCandidateId);r&&(this._log.info(`local candidate: ${r.candidateType} ${r.protocol}:${r.ip||r.address}:${r.port} ${r.networkType||""} ${r.candidateType==="relay"?`relayProtocol:${r.relayProtocol}`:""}`),this._localAddress=`${r.ip||r.address}:${r.port}`),n&&(this._log.info(`remote candidate: ${n.candidateType} ${n.protocol}:${n.ip||n.address}:${n.port}`),this._remoteAddress=`${n.protocol}:${n.ip||n.address}`);break}})}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise?this._waitForPeerConnectionConnectedPromise:(this._waitForPeerConnectionConnectedPromise=new Promise((t,e)=>{if(this._currentState==="CONNECTED")return t();this._waitForPeerConnectionConnectedPromiseReject=e;let r=a=>{a.state==="CONNECTED"&&(clearTimeout(o),s(),t())},n=({room:a})=>{a===this._room&&(clearTimeout(o),s(),e(new M({code:v.API_CALL_ABORTED,message:B({key:V.CONNECTION_ABORTED,data:"leave room"})})))},s=()=>{C.off(S.LEAVE_SUCCESS,n,this),this._emitter.off("connection-state-changed",r,this)},o=setTimeout(()=>{s();let a=new M({code:v.API_CALL_TIMEOUT,message:"connection timeout"});Hc+=1,uf(this._signalChannel.isConnected)&&(this._log.warn("firewall restrition"),Fc=!0,this._emitter.emit("firewall-restriction")),e(a)},Rn);C.on(S.LEAVE_SUCCESS,n,this),this._emitter.on("connection-state-changed",r,this)}),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally(()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null}),this._waitForPeerConnectionConnectedPromise)}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(Se.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=Bt()){this._log.warn(`SDK has tried reconnect for ${this._reconnectionCount} times, but all failed, please check your network`),this.stopReconnection();let t=new M({code:this._isUplink?v.UPLINK_RECONNECTION_FAILED:v.DOWNLINK_RECONNECTION_FAILED,message:B({key:this._isUplink?V.UPLINK_RECONNECTION_FAILED:V.DOWNLINK_RECONNECTION_FAILED})});return this.emitConnectionStateChangedEvent("DISCONNECTED"),this._emitter.emit("error",t),-1}return this._signalChannel.isConnected?(this._reconnectionCount+=1,this._log.warn(`reconnect() trying [${this._reconnectionCount}]`),1):(this._log.warn("reconnect() signal channel is not connected, suspend reconnection until signal is connected"),this._signalChannel.once(Se.CONNECTED,this.reconnect,this),-1)}on(t,e,r){this._emitter.on(t,e,r)}off(t,e,r){this._emitter.off(t,e,r)}getIsReconnecting(){return this._isReconnecting}get isH264(){var t,e;return!!((e=(t=this._peerConnection)==null?void 0:t.remoteDescription)!=null&&e.sdp.includes("H264"))}};var CO=_(f()),Jc=_(jc());var Ie=function(i){return Jc.default.parse(i)},ut=function(i){return Jc.default.write(i)},Bl=function(i){let t=Ie(i);return t.media.forEach(e=>{e.type===m.AUDIO&&e.fmtp.forEach(r=>{r.config+=";sprop-stereo=1;stereo=1"})}),ut(t)};function $l(i){let t=Ie(i);return t.media.forEach(e=>{var r,n;if(e.type===m.VIDEO){let s=new Set;e.rtp.forEach(({payload:a,codec:c})=>c==="H264"&&s.add(a)),e.fmtp.forEach(({payload:a,config:c})=>{let d=c.match(/apt=(\d+)/);d&&d[1]&&s.has(Number(d[1]))&&s.add(a)});let o=({payload:a})=>!s.has(a);e.rtp=e.rtp.filter(o),e.rtcpFb=(r=e.rtcpFb)==null?void 0:r.filter(o),e.fmtp=e.fmtp.filter(o),e.payloads=(n=e.payloads)==null?void 0:n.split(" ").filter(a=>!s.has(Number(a))).join(" ")}}),ut(t)}var vO=_(f());function go(i){return Object.keys(i).filter(t=>i[t])}var Xc=class extends Qe{constructor(e){super(ee(w({},e),{isUplink:!1}));p(this,"_flag",0);p(this,"role","anchor");p(this,"remoteAudioTrack");p(this,"remoteVideoTrack");p(this,"remoteAuxiliaryTrack");p(this,"ssrc",{audio:0,video:0,auxiliary:0});p(this,"_isSDPExchanging",!1);this.flag=e.flag,this.remoteAudioTrack=e.remoteAudioTrack||new kr(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new Ji(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new xr(this._room,this)}get subscribeState(){let e={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(this.remoteVideoTrack.mediaType&8?e.smallVideo=!0:e.video=!0),this.remoteAudioTrack.isSubscribed&&(e.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(e.auxiliary=!0),e}get muteState(){return li(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var r,n,s;e!==this._flag&&(this._flag=e,(r=this.remoteAudioTrack)==null||r.onFlagChanged(),(n=this.remoteVideoTrack)==null||n.onFlagChanged(),(s=this.remoteAuxiliaryTrack)==null||s.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===m.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var s,o;let r=this._currentState,n=super.emitConnectionStateChangedEvent(e);return n&&r!==e&&((s=this.remoteVideoTrack)==null||s.emit("connection-state-changed",{prevState:r,state:e}),(o=this.remoteAuxiliaryTrack)==null||o.emit("connection-state-changed",{prevState:r,state:e})),n}onTrack(e){let r=e.streams[0],{track:n}=e,s=r.id===Sn?m.MAIN:m.AUXILIARY;this._log.debug(`ontrack ${s} ${n.kind}`);let o=m.AUDIO;n.kind===m.VIDEO&&(o=s===m.MAIN?m.VIDEO:m.AUXILIARY);let a=this.remoteAudioTrack;o===m.VIDEO?a=this.remoteVideoTrack:o===m.AUXILIARY&&(a=this.remoteAuxiliaryTrack),a.setMediaStream(r),a.setMediaStreamTrack(n)}addRRTRLine(e){let r=e.split(`\r
94
93
  `),n=new Map;r.forEach((o,a)=>{/^a=rtcp-fb:/.test(o)&&r[a+1]&&!/^a=rtcp-fb:/.test(r[a+1])&&n.set(a+1,`${o.match(/^a=rtcp-fb:\d+/)[0]} rrtr`)});let s=[...n];for(let o=0;o<s.length;o++){let[a,c]=s[o];r.splice(a+o,0,c)}return r.join(`\r
95
- `)}addSPSDescription(e){let r=Re(e);return r.media.forEach(n=>{n.type===m.VIDEO&&n.fmtp.forEach(s=>{s.config+=";sps-pps-idr-in-keyframe=1"})}),ct(r)}removeSDESDescription(e){let r=["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"],n=Re(e);return n.media.forEach(s=>{!s.ext||(s.ext=s.ext.filter(o=>!r.includes(o.uri)))}),ct(n)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,r){return E(this,null,function*(){var n,s;try{if((((n=this._peerConnection)==null?void 0:n.connectionState)===fe.NEW||((s=this._peerConnection)==null?void 0:s.connectionState)===fe.CONNECTING)&&(yield this.waitForPeerConnectionConnected()),this.isSubscriptionStateNotChanged(e)){this._peerConnection||(this.initialize(),yield this.connect(e));return}if(this._peerConnection||this._isSDPExchanging){let o="subscribe_change";Object.values(e).find(a=>a===!0)||(o="unsubscribe"),yield this.sendSubscription(o,e)}else this.initialize(),yield this.connect(e)}catch(o){throw this._room.isJoined&&this.isStreamUnpublished(r)?(this._log.warn(`${o.message} ${JSON.stringify(this.muteState)}`),new L({code:v.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):o}})}unsubscribe(n){return E(this,arguments,function*({remoteTracks:e,streamType:r}){if(this._currentState==="CONNECTED"&&(r==="main"&&!this.isMainStreamSubscribed||r==="auxiliary"&&!this.isAuxStreamSubscribed)){this._log.info(`${r} stream already unsubscribed`);return}let s=B({},this.subscribeState);e.forEach(a=>{switch(a.mediaType){case 1:s.audio=!1;break;case 4:s.video=!1;break;case 8:s.smallVideo=!1;break;case 2:s.auxiliary=!1;break;default:break}});let o="subscribe_change";Object.values(s).find(a=>a===!0)||(o="unsubscribe"),this._log.info(`${o==="unsubscribe"?o:"subscribe"} ${r} [${Ws(s)}]`),yield this.sendSubscription(o,s),o==="unsubscribe"&&(this.remoteAudioTrack.setMediaStreamTrack(null),this.remoteVideoTrack.setMediaStreamTrack(null),this.remoteAuxiliaryTrack.setMediaStreamTrack(null),this.closePeerConnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"))})}sendSubscription(e,r=this.subscribeState){let n={srcTinyId:this.tinyId,srcUserId:this.userId},s=ne.UNSUBSCRIBE,o=Z.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(n={audio:r.audio,bigVideo:r.video,auxVideo:r.auxiliary,smallVideo:r.smallVideo,srcTinyId:this.tinyId},s=ne.SUBSCRIBE_CHANGE,o=Z.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:s,data:n,responseCommand:o,timeout:1e4}).then(({data:a})=>{if(a.code!==0){let c=new L({code:a.code,message:$({key:w.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(c),c}})}connect(){return E(this,arguments,function*(e=this.subscribeState){try{yield this.exchangeSDP(e),yield this.waitForPeerConnectionConnected()}catch(r){throw this.closePeerConnection(!0),r}})}exchangeSDP(e){return E(this,null,function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info("createOffer success, sending offer");let{type:r,sdp:n}=this._peerConnection.localDescription,s={type:r,sdp:n,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},o=yield this._signalChannel.sendWaitForResponse({command:ne.SUBSCRIBE,commandDesc:"exchange sdp",data:s,responseCommand:Z.SUBSCRIBE_RESULT,timeout:$d});if(!this._peerConnection){let a=new L({code:v.INVALID_OPERATION,message:$({key:w.CONNECTION_CLOSED})});throw this._log.warn(a),a}yield this.onSubscribeResult(o),this._isSDPExchanging=!1}catch(r){throw this._isSDPExchanging=!1,r}})}createOffer(){return E(this,null,function*(){let e={voiceActivityDetection:!1};di()&&this._sdpSemantics===gi?(this._peerConnection.addTransceiver(m.AUDIO,{direction:se.RECVONLY}),this._peerConnection.addTransceiver(m.VIDEO,{direction:se.RECVONLY}),this._peerConnection.addTransceiver(m.VIDEO,{direction:se.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let r=yield this._peerConnection.createOffer(e);if(r.sdp){let{isH264DecodeSupported:n}=yield fs();n||(this._log.warn("remove h264 desc from sdp"),r.sdp=Ol(r.sdp)),r.sdp=this.addRRTRLine(r.sdp),r.sdp=this.addSPSDescription(r.sdp),r.sdp=Dl(r.sdp),this._sdpSemantics===gi&&(r.sdp=this.removeSDESDescription(r.sdp))}yield this._peerConnection.setLocalDescription(r)})}onSubscribeResult(e){return E(this,null,function*(){let{code:r,message:n=""}=e&&e.data||{},{type:s,sdp:o}=e&&e.data&&e.data.data||{};if(r===qi)throw new L({code:v.NOT_SUPPORTED_H264,message:$({key:w.NOT_SUPPORTED_H264DECODE})});try{if(r!==0)throw new L({code:r,message:$({key:w.EXCHANGE_SDP_FAILED,data:{errMsg:n}})});this._log.debug(`accept remote answer: ${o}`),yield this._peerConnection.setRemoteDescription({type:s,sdp:o}),this._sei&&(this._sei.handleEncodedStreams(),this._sei.onSEIMessage=a=>{this._emitter.emit("sei-message",te(B({},a),{userId:this.userId}))}),this.updateSSRC(o)}catch(a){throw this._log.error(a),a}})}updateSSRC(e){try{Re(e).media.forEach(n=>{if(!!n.ssrcs)if(n.type===m.AUDIO){let s=n.ssrcs.find(o=>{var a;return(a=o.value)==null?void 0:a.includes(Wn)});s&&(this.ssrc.audio=Number(s.id))}else{let s=n.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(Wn)}),o=n.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(xd)});s&&(this.ssrc.video=Number(s.id)),o&&(this.ssrc.auxiliary=Number(o.id))}})}catch(r){}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return E(this,null,function*(){if(!(Ei(Cc.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch(r){let n=rt(this._reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${n/1e3}s`),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},n)}})}getIsReconnecting(){return this._isReconnecting}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}getCurrentState(){return this._currentState}setDelay({audioDelay:e,videoDelay:r}){this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=r}},gn=Cc;F([ce(i=>function(...t){return new Promise((e,r)=>{let n=s=>{this._emitter.off("closed",n),r(new L({code:v.API_CALL_ABORTED,message:$({key:w.CONNECTION_ABORTED,data:s})}))};this._emitter.on("closed",n),i.apply(this,t).then(e,r).finally(()=>{this._emitter.off("closed",n)})})})],gn.prototype,"subscribe",1),F([vs(Qe.prototype.afterConnect),ys(Qe.prototype.beforeConnect)],gn.prototype,"connect",1);var Ac=gn;var wO=_(f());var mO=_(f());var ZD=_(f());var B_="let width,height,offscreen,ctx;onmessage=function(e){const{action,data}=e.data;switch(action){case'render':offscreen=data.canvas;width=offscreen.width;height=offscreen.height;ctx=offscreen.getContext('2d');draw(data.readable,data.writable);break}};function draw(readable,writable){const transformer=new TransformStream({async transform(cameraFrame,controller){ctx.drawImage(cameraFrame,0,0,width,height);const frame=new VideoFrame(offscreen,{timestamp:cameraFrame.timestamp});cameraFrame.close();controller.enqueue(frame)}});readable.pipeThrough(transformer).pipeTo(writable)}",$_=new Blob([B_],{type:"application/javascript"}),yc=class{constructor(t){p(this,"width");p(this,"height");p(this,"canvas");p(this,"offscreen");p(this,"smallGenerator");p(this,"smallWritable");p(this,"bigProcessor");p(this,"bigReadable");p(this,"worker");let{videoTrack:e}=t;this.width=void 0,this.height=void 0,this.canvas=null,this.offscreen=null,this.smallGenerator=new MediaStreamTrackGenerator({kind:"video"}),this.smallWritable=this.smallGenerator.writable,this.bigProcessor=new MediaStreamTrackProcessor({track:e}),this.bigReadable=this.bigProcessor.readable,this.initWorker()}initWorker(){try{this.worker=new Worker(URL.createObjectURL($_)),M.info("init worker processor success")}catch(t){M.warn(`init worker processor failed. ${t.error}`)}}setCanvasRect(t,e){this.width=t,this.height=e,this.canvas=document.createElement("canvas"),this.canvas.width=t,this.canvas.height=e,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])}generateVideoTrack(){let t=new MediaStream([this.smallGenerator]);return t==null?void 0:t.getTracks()[0]}destroy(){this.worker.terminate()}},Ml=yc;var iO=_(f());var vc=class{constructor(t){p(this,"_player");p(this,"_canvas");p(this,"_canvasCtx");this._player=t,this._canvas=document.createElement("canvas"),this._canvasCtx=this._canvas.getContext("2d")}setCanvasRect(t,e){!this._canvas||(this._canvas.width=t,this._canvas.height=e)}drawVideoToCanvas(){let t=this._player.getElement();this._canvas&&this._canvasCtx&&t&&this._canvasCtx.drawImage(t,0,0,this._canvas.width,this._canvas.height)}generateVideoTrack(t){return this._canvas.captureStream(t).getVideoTracks()[0]}generateStreamFromTrack(t){let e=new MediaStream;return e.addTrack(t),e}destroy(){var t;(t=this._player)==null||t.stop(),this._canvas&&(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){let t=this._player.getElement();if(t)return t.readyState===t.HAVE_ENOUGH_DATA}return!1}},Nc=vc;var bc=class{constructor(t){p(this,"_player");p(this,"_processor");p(this,"_initOffscreenSuccess");p(this,"_localVideoTrack");p(this,"_interval");this._localVideoTrack=t,this._player=t.player,this._processor=null,this._initOffscreenSuccess=!1}initialize(){return E(this,null,function*(){if(na()&&(navigator==null?void 0:navigator.hardwareConcurrency)>=6)try{yield this.initOffscreen(),this._initOffscreenSuccess=!0,M.info("Initialize VideoGenerator successfully!")}catch(t){this.initCanvas()}else this.initCanvas()})}generateSmallVideoTrack(t){let e=this.getSmallVideoProfile(t),r;return this._initOffscreenSuccess?(this._processor.setCanvasRect(e.width,e.height),r=this._processor.generateVideoTrack(e.frameRate)):(this._processor.setCanvasRect(e.width,e.height),this._player.setRect(e.width,e.height),r=this._processor.generateVideoTrack(e.frameRate),this._interval=me.run(ii,this.render.bind(this),{fps:e.frameRate})),r}render(){this._processor instanceof Nc&&this._processor.drawVideoToCanvas()}destroy(){me.clearTask(this._interval),this._processor&&this._processor.destroy()}initOffscreen(){this._processor=new Ml({videoTrack:this._localVideoTrack.mediaTrack})}initCanvas(){this._player=new bi({track:this._localVideoTrack.mediaTrack,muted:!0,objectFit:"cover",mirror:!1,container:null,id:"video-player",log:this._localVideoTrack.log}),this._player.play().then(()=>{M.info("VideoGenerator: play local video success")}).catch(()=>{M.error("VideoGenerator: Failed to play local video")}),this._processor=new Nc(this._player)}getSmallVideoProfile(t){let e=this._localVideoTrack.mediaTrack,r=this._localVideoTrack.profile;if(wt){let c=e.getSettings();c&&c.width&&c.height&&(r.width=c.width,r.height=c.height)}let n,s=r.width*r.height,o=t.width*t.height;return M.info(`big res: ${r.width}*${r.height} small res: ${t.width}*${t.height} `),s>o?n=s/o:(M.warn(`Small stream resolution is larger than big stream, which is invalid. big: ${r.width} * ${r.height} small: ${t.width} * ${t.height}`),n=s/(160*120)),{width:r.width/Math.sqrt(n),height:r.height/Math.sqrt(n),frameRate:t.frameRate}}},Yt=bc;var Ll={voiceActivityDetection:!1},Dc=class extends Qe{constructor(e){super(te(B({},e),{isUplink:!0}));p(this,"localMainAudioTrack",null);p(this,"localMainVideoTrack",null);p(this,"localAuxAudioTrack",null);p(this,"localAuxVideoTrack",null);p(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0});p(this,"_isPublishingAux",!1);p(this,"_publishingLocalAudioTrack");p(this,"_publishingLocalVideoTrack");p(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});p(this,"_smallGenerator");p(this,"_audioManager");this._audioManager=e.audioManager,this._smallGenerator=null}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}get publishState(){var r,n,s,o;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(st()?(e.audio=!!((r=a[0])!=null&&r.track),e.bigVideo=!!((n=a[1])!=null&&n.track),e.smallVideo=!!((s=a[2])!=null&&s.track),e.auxVideo=!!((o=a[3])!=null&&o.track)):a.forEach(c=>{c.track&&(c.track.kind===m.AUDIO?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.localMainVideoTrack&&this.localMainVideoTrack.canvasTrack&&this.localMainVideoTrack.destoryCanvasTrack()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._smallGenerator&&(this._smallGenerator.destroy(),this._smallGenerator=null)}installEvents(){this._emitter.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this._emitter.on("connection-state-changed",this.handleConnectionStateChange,this)}uninstallEvents(){this._emitter.off("connection-state-changed",this.handleConnectionStateChange,this)}emitConnectionStateChangedEvent(e,r){var o,a,c;let n=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&n!==e&&(r?r.emit("connection-state-changed",{prevState:n,state:e}):((o=this.localMainVideoTrack)==null||o.emit("connection-state-changed",{prevState:n,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:n,state:e}),(c=this._publishingLocalVideoTrack)==null||c.emit("connection-state-changed",{prevState:n,state:e}))),s}publish(s){return E(this,arguments,function*({localAudioTrack:e,localVideoTrack:r,isAuxiliary:n}){var a;this._peerConnection||this.initialize(),e&&(this._publishingLocalAudioTrack=e),r&&(this._publishingLocalVideoTrack=r),this._isPublishingAux=n;let o;r&&!n&&r.small&&(this._smallGenerator=new Yt(r),yield this._smallGenerator.initialize(),o=this._smallGenerator.generateSmallVideoTrack(r.small)),this.sendMediaSettings(),di()?yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:r,smallTrack:o,isAuxiliary:n}):yield this.publishByAddTrack({localAudioTrack:e,localVideoTrack:r,smallTrack:o}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,n?(r&&(this.localAuxVideoTrack=r),e&&(this.localAuxAudioTrack=e)):(r&&(this.localMainVideoTrack=r),e&&(this.localMainAudioTrack=e)),(a=this._sei)==null||a.handleEncodedStreams(),this.installTrackMuteEvents(e,r),this.sendMutedFlag()})}publishByTransceiver(o){return E(this,arguments,function*({localAudioTrack:e,localVideoTrack:r,smallTrack:n,isAuxiliary:s}){this._log.info("publish by transceiver");let a=new MediaStream;r&&er&&as&&r.genCanvasTrack();let c=(r==null?void 0:r.canvasTrack)||(r==null?void 0:r.mediaTrack),d=this._audioManager.mediaStreamTrack;d&&a.addTrack(d),c&&a.addTrack(c);let u=this._peerConnection.getTransceivers();if(u.length===0)this._peerConnection.addTransceiver(d||m.AUDIO,{direction:se.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(s?m.VIDEO:c||m.VIDEO,{direction:se.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(n||m.VIDEO,{direction:se.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(s?c||m.VIDEO:m.VIDEO,{direction:se.SENDONLY,streams:[a]}),yield this.connect();else{let l=[];if(d&&(u[0].sender.track||l.push(0),yield u[0].sender.replaceTrack(d),yield this.setBandwidth({bandwidth:(e==null?void 0:e.profile.bitrate)||40,type:m.AUDIO})),c){let h=s?3:1;yield u[h].sender.replaceTrack(c),yield this.setBandwidth({bandwidth:r.profile.bitrate,type:m.VIDEO,videoType:s?m.AUXILIARY:m.BIG}),l.push(h),n&&(yield u[2].sender.replaceTrack(n),yield this.setBandwidth({bandwidth:r.small.bitrate,type:m.VIDEO,videoType:m.SMALL}),l.push(2))}yield this.setTransceiverDirection(se.SENDONLY,l),yield this.doPublishChange(),r==null||r.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),r==null||r.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"})}})}publishByAddTrack(s){return E(this,arguments,function*({localAudioTrack:e,localVideoTrack:r,smallTrack:n}){this._log.info("publish by addtrack");let o=r==null?void 0:r.mediaTrack,a=e!=null&&e.mediaTrack?this._audioManager.mediaStreamTrack:null;if(this._peerConnection&&this._peerConnection.connectionState!=="new"){a&&(yield this.addTrack(e)),o&&(yield this.addTrack(r));return}let c=new MediaStream;if(a&&c.addTrack(a),o&&c.addTrack(o),a&&this._peerConnection.addTrack(a,c),o&&(this._peerConnection.addTrack(o,c),n)){let d=new MediaStream;d.addTrack(n),this._peerConnection.addTrack(n,d)}yield this.connect()})}installTrackMuteEvents(...e){e.forEach(r=>{r&&(r==null||r.on("mute",this.sendMutedFlag,this),r==null||r.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(r=>{r&&(r==null||r.off("mute",this.sendMutedFlag,this),r==null||r.off("unmute",this.sendMutedFlag,this))})}unpublish(n){return E(this,arguments,function*({localAudioTrack:e,localVideoTrack:r}){if(!st()){if(e&&e.mediaTrack&&!r&&this.localMainVideoTrack){yield this.removeTrack(e),this.localMainAudioTrack=null;return}if(r&&r.mediaTrack&&!e&&this.localMainAudioTrack){yield this.removeTrack(r),this.localMainVideoTrack=null;return}yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,r),this.emitConnectionStateChangedEvent("DISCONNECTED",r);return}let s=r&&r===this.localAuxVideoTrack,o=e==null?void 0:e.mediaTrack,a=r==null?void 0:r.mediaTrack,c=this._peerConnection.getSenders(),d=[];o&&(this._audioManager.removeAudioTrack(e),this._audioManager.isMixed||(yield c[0].replaceTrack(null),d.push(0),this.localMainAudioTrack=null)),a&&(s?(yield c[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=te(B({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),d.push(3)):(yield c[1].replaceTrack(null),yield c[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=te(B({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),d.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.setTransceiverDirection(se.INACTIVE,d),yield this.doPublishChange(!1)):yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,r),r==null||r.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return E(this,null,function*(){let r={state:this.publishState,constraintConfig:this._mediaSettings},n=yield this._signalChannel.sendWaitForResponse({command:ne.PUBLISH_STATE_CHANGE,data:r,responseCommand:Z.PUBLISH_STATE_CHANGE_RESULT,enableLog:e});this.checkPublishResultCode(n.data.code,n.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:ne.UNPUBLISH,commandDesc:"unpublish",responseCommand:Z.UNPUBLISH_RESULT,enableLog:e}).catch(r=>{if(r.getCode()===v.API_CALL_TIMEOUT)return Promise.resolve();throw r})}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:r}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":r&&(this._mediaSettings.videoCodec="VP8");let n=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:s,localAuxVideoTrack:o}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?o=this._publishingLocalVideoTrack:s=this._publishingLocalVideoTrack),wt){if(n&&n.mediaTrack){let a=n.mediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=n.profile.bitrate*1e3,this._mediaSettings.audioFs=a.sampleRate||0}if(s&&s.mediaTrack){let a=s.mediaTrack.getSettings();this._mediaSettings.videoWidth=a.width||0,this._mediaSettings.videoHeight=a.height||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=s.profile.bitrate*1e3,s.small&&(this._mediaSettings.smallVideoWidth=s.small.width,this._mediaSettings.smallVideoHeight=s.small.height,this._mediaSettings.smallVideoFps=s.small.frameRate,this._mediaSettings.smallVideoBps=s.small.bitrate*1e3)}if(o&&o.mediaTrack){let a=o.mediaTrack.getSettings();this._mediaSettings.auxVideoWidth=a.width||0,this._mediaSettings.auxVideoHeight=a.height||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=o.profile.bitrate*1e3}}else n&&n.mediaTrack&&(this._mediaSettings.audioChannel=n.profile.channelCount,this._mediaSettings.audioBps=n.profile.bitrate*1e3,this._mediaSettings.audioFs=n.profile.sampleRate),s&&s.mediaTrack&&(this._mediaSettings.videoWidth=s.profile.width,this._mediaSettings.videoHeight=s.profile.height,this._mediaSettings.videoFps=s.profile.frameRate,this._mediaSettings.videoBps=s.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:ne.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:Z.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return E(this,null,function*(){var n;if(!this._peerConnection)return;let r=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is adding ${e.kind} track to current published local ${r?m.AUXILIARY:m.MAIN} stream`),(n=this._sei)==null||n.handleEncodedStreams(),st()?yield this.addTrackByTransceiver(e,r):yield this.addTrackBySender(e)})}addTrackByTransceiver(e,r){return E(this,null,function*(){var o;if(!e.mediaTrack)return;let n=this._peerConnection.getTransceivers(),s=e.mediaTrack;if(e.kind===m.AUDIO)this._audioManager.addAudioTrack(e),s=this._audioManager.mediaStreamTrack,yield n[0].sender.replaceTrack(s);else{let a=r?3:1;if(yield n[a].sender.replaceTrack(s),a===1&&((o=this.localMainVideoTrack)==null?void 0:o.small)){this._smallGenerator=new Yt(this.localMainVideoTrack),yield this._smallGenerator.initialize();let c=this._smallGenerator.generateSmallVideoTrack(this.localMainVideoTrack.small);yield n[2].sender.replaceTrack(c)}n[a].direction===se.INACTIVE&&(yield this.setTransceiverDirection(se.SENDONLY,[a]))}this.updateMediaSettings(),yield this.doPublishChange()})}addTrackBySender(e){return E(this,null,function*(){if(!e.mediaTrack)return;let r=e.mediaTrack;st()&&this._peerConnection.getTransceivers().findIndex(o=>o.direction==="stopped")>=0&&(this._log.warn("transceiver is stopping, negotiate sdp first"),yield this.updateOffer("remove",r));let n=this._peerConnection.getSenders().find(o=>o.track&&o.track.kind===r.kind);if(n&&n.track){this._log.warn("sender already exists, remove sender first");let o=n.track;this.removeSender(n),yield this.updateOffer("remove",o)}let{mediaStream:s}=e;if(this._peerConnection.addTrack(r,s),r.kind===m.VIDEO&&e instanceof mt&&e.small){this._smallGenerator=new Yt(e),yield this._smallGenerator.initialize();let o=this._smallGenerator.generateSmallVideoTrack(e.small),a=new MediaStream;a.addTrack(o),this._peerConnection.addTrack(o,a)}yield this.updateOffer("add",r)})}isNeedToResetOfferOrder(){if(this._sdpSemantics===Pr||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,r=Re(e);for(let n=0;n<r.media.length;n++)if(Number(r.media[n].mid)===0&&r.media[n].type===m.VIDEO)return!0;return!1}removeSender(e){let r=null;st()&&(r=this._peerConnection.getTransceivers().find(n=>n.sender&&n.sender.track===e.track)),this._peerConnection.removeTrack(e),r&&ue(r.stop)&&(this._log.info("stop transceiver"),r.stop())}removeTrack(e){return E(this,null,function*(){if(!this._peerConnection)return;let r=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${r?m.AUXILIARY:m.MAIN} stream`),st()?yield this.removeTrackByTransceiver(e,r):yield this.removeTrackBySender(e)})}removeTrackByTransceiver(e,r){return E(this,null,function*(){if(!e.mediaTrack)return;let n=this._peerConnection.getTransceivers();if(e.kind===m.AUDIO)this._audioManager.removeAudioTrack(e),this._audioManager.isMixed||(yield n[0].sender.replaceTrack(null));else{let s=r?3:1;yield n[s].sender.replaceTrack(null),s===1&&this._smallGenerator&&(this._smallGenerator.destroy(),this._smallGenerator=null,yield n[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(se.INACTIVE,[s])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,r){return E(this,null,function*(){if(!pe)return;let n=!1,s=!1;this._log.info(`setting transceiver ${r.join(",")} direction to ${e}`);let o=this._peerConnection.getTransceivers();if(r.forEach(d=>{o[d].direction!==e&&(o[d].direction=e,n=!0)}),n){this._log.info("updating offer");let d=yield this._peerConnection.createOffer();yield this._peerConnection.setLocalDescription(d)}let a=-1,c=this._peerConnection.remoteDescription.sdp.split(`\r
94
+ `)}addSPSDescription(e){let r=Ie(e);return r.media.forEach(n=>{n.type===m.VIDEO&&n.fmtp.forEach(s=>{s.config+=";sps-pps-idr-in-keyframe=1"})}),ut(r)}removeSDESDescription(e){let r=["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"],n=Ie(e);return n.media.forEach(s=>{!s.ext||(s.ext=s.ext.filter(o=>!r.includes(o.uri)))}),ut(n)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,r){return E(this,null,function*(){var n,s;try{if((((n=this._peerConnection)==null?void 0:n.connectionState)===pe.NEW||((s=this._peerConnection)==null?void 0:s.connectionState)===pe.CONNECTING)&&(yield this.waitForPeerConnectionConnected()),this.isSubscriptionStateNotChanged(e)){this._peerConnection||(this.initialize(),yield this.connect(e));return}if(this._peerConnection||this._isSDPExchanging){let o="subscribe_change";Object.values(e).find(a=>a===!0)||(o="unsubscribe"),yield this.sendSubscription(o,e)}else this.initialize(),yield this.connect(e)}catch(o){throw this._room.isJoined&&this.isStreamUnpublished(r)?(this._log.warn(`${o.message} ${JSON.stringify(this.muteState)}`),new M({code:v.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):o}})}unsubscribe(n){return E(this,arguments,function*({remoteTracks:e,streamType:r}){if(this._currentState==="CONNECTED"&&(r==="main"&&!this.isMainStreamSubscribed||r==="auxiliary"&&!this.isAuxStreamSubscribed)){this._log.info(`${r} stream already unsubscribed`);return}let s=w({},this.subscribeState);e.forEach(a=>{switch(a.mediaType){case 1:s.audio=!1;break;case 4:s.video=!1;break;case 8:s.smallVideo=!1;break;case 2:s.auxiliary=!1;break;default:break}});let o="subscribe_change";Object.values(s).find(a=>a===!0)||(o="unsubscribe"),this._log.info(`${o==="unsubscribe"?o:"subscribe"} ${r} [${go(s)}]`),yield this.sendSubscription(o,s),o==="unsubscribe"&&(this.remoteAudioTrack.setMediaStreamTrack(null),this.remoteVideoTrack.setMediaStreamTrack(null),this.remoteAuxiliaryTrack.setMediaStreamTrack(null),this.closePeerConnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"))})}sendSubscription(e,r=this.subscribeState){let n={srcTinyId:this.tinyId,srcUserId:this.userId},s=ne.UNSUBSCRIBE,o=Q.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(n={audio:r.audio,bigVideo:r.video,auxVideo:r.auxiliary,smallVideo:r.smallVideo,srcTinyId:this.tinyId},s=ne.SUBSCRIBE_CHANGE,o=Q.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:s,data:n,responseCommand:o,timeout:1e4}).then(({data:a})=>{if(a.code!==0){let c=new M({code:a.code,message:B({key:V.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(c),c}})}connect(){return E(this,arguments,function*(e=this.subscribeState){try{yield this.exchangeSDP(e),yield this.waitForPeerConnectionConnected()}catch(r){throw this.closePeerConnection(!0),r}})}exchangeSDP(e){return E(this,null,function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info("createOffer success, sending offer");let{type:r,sdp:n}=this._peerConnection.localDescription,s={type:r,sdp:n,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},o=yield this._signalChannel.sendWaitForResponse({command:ne.SUBSCRIBE,commandDesc:"exchange sdp",data:s,responseCommand:Q.SUBSCRIBE_RESULT,timeout:Ta});if(!this._peerConnection){let a=new M({code:v.INVALID_OPERATION,message:B({key:V.CONNECTION_CLOSED})});throw this._log.warn(a),a}yield this.onSubscribeResult(o),this._isSDPExchanging=!1}catch(r){throw this._isSDPExchanging=!1,r}})}createOffer(){return E(this,null,function*(){let e={voiceActivityDetection:!1};mi()&&this._sdpSemantics===ci?(this._peerConnection.addTransceiver(m.AUDIO,{direction:se.RECVONLY}),this._peerConnection.addTransceiver(m.VIDEO,{direction:se.RECVONLY}),this._peerConnection.addTransceiver(m.VIDEO,{direction:se.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let r=yield this._peerConnection.createOffer(e);if(r.sdp){let{isH264DecodeSupported:n}=yield Gs();n||(this._log.warn("remove h264 desc from sdp"),r.sdp=$l(r.sdp)),r.sdp=this.addRRTRLine(r.sdp),r.sdp=this.addSPSDescription(r.sdp),r.sdp=Bl(r.sdp),this._sdpSemantics===ci&&(r.sdp=this.removeSDESDescription(r.sdp))}yield this._peerConnection.setLocalDescription(r)})}onSubscribeResult(e){return E(this,null,function*(){let{code:r,message:n=""}=e&&e.data||{},{type:s,sdp:o}=e&&e.data&&e.data.data||{};if(r===xi)throw new M({code:v.NOT_SUPPORTED_H264,message:B({key:V.NOT_SUPPORTED_H264DECODE})});try{if(r!==0)throw new M({code:r,message:B({key:V.EXCHANGE_SDP_FAILED,data:{errMsg:n}})});this._log.debug(`accept remote answer: ${o}`),yield this._peerConnection.setRemoteDescription({type:s,sdp:o}),this._sei&&(this._sei.handleEncodedStreams(),this._sei.onSEIMessage=a=>{this._emitter.emit("sei-message",ee(w({},a),{userId:this.userId}))}),this.updateSSRC(o)}catch(a){throw this._log.error(a),a}})}updateSSRC(e){try{Ie(e).media.forEach(n=>{if(!!n.ssrcs)if(n.type===m.AUDIO){let s=n.ssrcs.find(o=>{var a;return(a=o.value)==null?void 0:a.includes(Sn)});s&&(this.ssrc.audio=Number(s.id))}else{let s=n.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(Sn)}),o=n.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(ma)});s&&(this.ssrc.video=Number(s.id)),o&&(this.ssrc.auxiliary=Number(o.id))}})}catch(r){}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return E(this,null,function*(){if(!(Ci(Xc.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch(r){let n=ot(this._reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${n/1e3}s`),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},n)}})}getIsReconnecting(){return this._isReconnecting}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}getCurrentState(){return this._currentState}setDelay({audioDelay:e,videoDelay:r}){this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=r}},jn=Xc;H([ae(i=>function(...t){return new Promise((e,r)=>{let n=s=>{this._emitter.off("closed",n),r(new M({code:v.API_CALL_ABORTED,message:B({key:V.CONNECTION_ABORTED,data:s})}))};this._emitter.on("closed",n),i.apply(this,t).then(e,r).finally(()=>{this._emitter.off("closed",n)})})})],jn.prototype,"subscribe",1),H([Zs(Qe.prototype.afterConnect),Qs(Qe.prototype.beforeConnect)],jn.prototype,"connect",1);var Yc=jn;var PP=_(f());var aP=_(f());var jO=_(f());var gf="let width,height,offscreen,ctx;onmessage=function(e){const{action,data}=e.data;switch(action){case'render':offscreen=data.canvas;width=offscreen.width;height=offscreen.height;ctx=offscreen.getContext('2d');draw(data.readable,data.writable);break}};function draw(readable,writable){const transformer=new TransformStream({async transform(cameraFrame,controller){ctx.drawImage(cameraFrame,0,0,width,height);const frame=new VideoFrame(offscreen,{timestamp:cameraFrame.timestamp});cameraFrame.close();controller.enqueue(frame)}});readable.pipeThrough(transformer).pipeTo(writable)}",If=new Blob([gf],{type:"application/javascript"}),zc=class{constructor(t){p(this,"width");p(this,"height");p(this,"canvas");p(this,"offscreen");p(this,"smallGenerator");p(this,"smallWritable");p(this,"bigProcessor");p(this,"bigReadable");p(this,"worker");let{videoTrack:e}=t;this.width=void 0,this.height=void 0,this.canvas=null,this.offscreen=null,this.smallGenerator=new MediaStreamTrackGenerator({kind:"video"}),this.smallWritable=this.smallGenerator.writable,this.bigProcessor=new MediaStreamTrackProcessor({track:e}),this.bigReadable=this.bigProcessor.readable,this.initWorker()}initWorker(){try{this.worker=new Worker(URL.createObjectURL(If)),O.info("init worker processor success")}catch(t){O.warn(`init worker processor failed. ${t.error}`)}}setCanvasRect(t,e){this.width=t,this.height=e,this.canvas=document.createElement("canvas"),this.canvas.width=t,this.canvas.height=e,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])}generateVideoTrack(){let t=new MediaStream([this.smallGenerator]);return t==null?void 0:t.getTracks()[0]}destroy(){this.worker.terminate()}},Fl=zc;var XO=_(f());var qc=class{constructor(t){p(this,"_player");p(this,"_canvas");p(this,"_canvasCtx");this._player=t,this._canvas=document.createElement("canvas"),this._canvasCtx=this._canvas.getContext("2d")}setCanvasRect(t,e){!this._canvas||(this._canvas.width=t,this._canvas.height=e)}drawVideoToCanvas(){let t=this._player.getElement();this._canvas&&this._canvasCtx&&t&&this._canvasCtx.drawImage(t,0,0,this._canvas.width,this._canvas.height)}generateVideoTrack(t){return this._canvas.captureStream(t).getVideoTracks()[0]}generateStreamFromTrack(t){let e=new MediaStream;return e.addTrack(t),e}destroy(){var t;(t=this._player)==null||t.stop(),this._canvas&&(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){let t=this._player.getElement();if(t)return t.readyState===t.HAVE_ENOUGH_DATA}return!1}},Qc=qc;var Zc=class{constructor(t){p(this,"_player");p(this,"_processor");p(this,"_initOffscreenSuccess");p(this,"_localVideoTrack");p(this,"_interval");this._localVideoTrack=t,this._player=t.player,this._processor=null,this._initOffscreenSuccess=!1}initialize(){return E(this,null,function*(){if(Pa()&&(navigator==null?void 0:navigator.hardwareConcurrency)>=6)try{yield this.initOffscreen(),this._initOffscreenSuccess=!0,O.info("Initialize VideoGenerator successfully!")}catch(t){this.initCanvas()}else this.initCanvas()})}generateSmallVideoTrack(t){let e=this.getSmallVideoProfile(t),r;return this._initOffscreenSuccess?(this._processor.setCanvasRect(e.width,e.height),r=this._processor.generateVideoTrack(e.frameRate)):(this._processor.setCanvasRect(e.width,e.height),this._player.setRect(e.width,e.height),r=this._processor.generateVideoTrack(e.frameRate),this._interval=me.run($t,this.render.bind(this),{fps:e.frameRate})),r}render(){this._processor instanceof Qc&&this._processor.drawVideoToCanvas()}destroy(){me.clearTask(this._interval),this._processor&&this._processor.destroy()}initOffscreen(){this._processor=new Fl({videoTrack:this._localVideoTrack.mediaTrack})}initCanvas(){this._player=new Gi({track:this._localVideoTrack.mediaTrack,muted:!0,objectFit:"cover",mirror:!1,container:null,id:"video-player",log:this._localVideoTrack.log}),this._player.play().then(()=>{O.info("VideoGenerator: play local video success")}).catch(()=>{O.error("VideoGenerator: Failed to play local video")}),this._processor=new Qc(this._player)}getSmallVideoProfile(t){let e=this._localVideoTrack.mediaTrack,r=this._localVideoTrack.profile;if(Ft){let c=e.getSettings();c&&c.width&&c.height&&(r.width=c.width,r.height=c.height)}let n,s=r.width*r.height,o=t.width*t.height;return O.info(`big res: ${r.width}*${r.height} small res: ${t.width}*${t.height} `),s>o?n=s/o:(O.warn(`Small stream resolution is larger than big stream, which is invalid. big: ${r.width} * ${r.height} small: ${t.width} * ${t.height}`),n=s/(160*120)),{width:r.width/Math.sqrt(n),height:r.height/Math.sqrt(n),frameRate:t.frameRate}}},Zt=Zc;var Gl={voiceActivityDetection:!1},ed=class extends Qe{constructor(e){super(ee(w({},e),{isUplink:!0}));p(this,"localMainAudioTrack",null);p(this,"localMainVideoTrack",null);p(this,"localAuxAudioTrack",null);p(this,"localAuxVideoTrack",null);p(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0});p(this,"_isPublishingAux",!1);p(this,"_publishingLocalAudioTrack");p(this,"_publishingLocalVideoTrack");p(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});p(this,"_smallGenerator");p(this,"_audioManager");this._audioManager=e.audioManager,this._smallGenerator=null}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}get publishState(){var r,n,s,o;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(at()?(e.audio=!!((r=a[0])!=null&&r.track),e.bigVideo=!!((n=a[1])!=null&&n.track),e.smallVideo=!!((s=a[2])!=null&&s.track),e.auxVideo=!!((o=a[3])!=null&&o.track)):a.forEach(c=>{c.track&&(c.track.kind===m.AUDIO?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.localMainVideoTrack&&this.localMainVideoTrack.canvasTrack&&this.localMainVideoTrack.destoryCanvasTrack()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._smallGenerator&&(this._smallGenerator.destroy(),this._smallGenerator=null)}installEvents(){this._emitter.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this._emitter.on("connection-state-changed",this.handleConnectionStateChange,this)}uninstallEvents(){this._emitter.off("connection-state-changed",this.handleConnectionStateChange,this)}emitConnectionStateChangedEvent(e,r){var o,a,c;let n=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&n!==e&&(r?r.emit("connection-state-changed",{prevState:n,state:e}):((o=this.localMainVideoTrack)==null||o.emit("connection-state-changed",{prevState:n,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:n,state:e}),(c=this._publishingLocalVideoTrack)==null||c.emit("connection-state-changed",{prevState:n,state:e}))),s}publish(s){return E(this,arguments,function*({localAudioTrack:e,localVideoTrack:r,isAuxiliary:n}){var a;this._peerConnection||this.initialize(),e&&(this._publishingLocalAudioTrack=e),r&&(this._publishingLocalVideoTrack=r),this._isPublishingAux=n;let o;r&&!n&&r.small&&(this._smallGenerator=new Zt(r),yield this._smallGenerator.initialize(),o=this._smallGenerator.generateSmallVideoTrack(r.small)),this.sendMediaSettings(),mi()?yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:r,smallTrack:o,isAuxiliary:n}):yield this.publishByAddTrack({localAudioTrack:e,localVideoTrack:r,smallTrack:o}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,n?(r&&(this.localAuxVideoTrack=r),e&&(this.localAuxAudioTrack=e)):(r&&(this.localMainVideoTrack=r),e&&(this.localMainAudioTrack=e)),(a=this._sei)==null||a.handleEncodedStreams(),this.installTrackMuteEvents(e,r),this.sendMutedFlag()})}publishByTransceiver(o){return E(this,arguments,function*({localAudioTrack:e,localVideoTrack:r,smallTrack:n,isAuxiliary:s}){this._log.info("publish by transceiver");let a=new MediaStream;r&&Ni&&hn&&r.genCanvasTrack();let c=(r==null?void 0:r.canvasTrack)||(r==null?void 0:r.mediaTrack),d=this._audioManager.mediaStreamTrack;d&&a.addTrack(d),c&&a.addTrack(c);let u=this._peerConnection.getTransceivers();if(u.length===0)this._peerConnection.addTransceiver(d||m.AUDIO,{direction:se.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(s?m.VIDEO:c||m.VIDEO,{direction:se.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(n||m.VIDEO,{direction:se.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(s?c||m.VIDEO:m.VIDEO,{direction:se.SENDONLY,streams:[a]}),yield this.connect();else{let l=[];if(d&&(u[0].sender.track||l.push(0),yield u[0].sender.replaceTrack(d),yield this.setBandwidth({bandwidth:(e==null?void 0:e.profile.bitrate)||40,type:m.AUDIO})),c){let h=s?3:1;yield u[h].sender.replaceTrack(c),yield this.setBandwidth({bandwidth:r.profile.bitrate,type:m.VIDEO,videoType:s?m.AUXILIARY:m.BIG}),l.push(h),n&&(yield u[2].sender.replaceTrack(n),yield this.setBandwidth({bandwidth:r.small.bitrate,type:m.VIDEO,videoType:m.SMALL}),l.push(2))}yield this.setTransceiverDirection(se.SENDONLY,l),yield this.doPublishChange(),r==null||r.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),r==null||r.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"})}})}publishByAddTrack(s){return E(this,arguments,function*({localAudioTrack:e,localVideoTrack:r,smallTrack:n}){this._log.info("publish by addtrack");let o=r==null?void 0:r.mediaTrack,a=e!=null&&e.mediaTrack?this._audioManager.mediaStreamTrack:null;if(this._peerConnection&&this._peerConnection.connectionState!=="new"){a&&(yield this.addTrack(e)),o&&(yield this.addTrack(r));return}let c=new MediaStream;if(a&&c.addTrack(a),o&&c.addTrack(o),a&&this._peerConnection.addTrack(a,c),o&&(this._peerConnection.addTrack(o,c),n)){let d=new MediaStream;d.addTrack(n),this._peerConnection.addTrack(n,d)}yield this.connect()})}installTrackMuteEvents(...e){e.forEach(r=>{r&&(r==null||r.on("mute",this.sendMutedFlag,this),r==null||r.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(r=>{r&&(r==null||r.off("mute",this.sendMutedFlag,this),r==null||r.off("unmute",this.sendMutedFlag,this))})}unpublish(n){return E(this,arguments,function*({localAudioTrack:e,localVideoTrack:r}){if(!at()){if(e&&e.mediaTrack&&!r&&this.localMainVideoTrack){yield this.removeTrack(e),this.localMainAudioTrack=null;return}if(r&&r.mediaTrack&&!e&&this.localMainAudioTrack){yield this.removeTrack(r),this.localMainVideoTrack=null;return}yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,r),this.emitConnectionStateChangedEvent("DISCONNECTED",r);return}let s=r&&r===this.localAuxVideoTrack,o=e==null?void 0:e.mediaTrack,a=r==null?void 0:r.mediaTrack,c=this._peerConnection.getSenders(),d=[];o&&(this._audioManager.removeAudioTrack(e),this._audioManager.isMixed||(yield c[0].replaceTrack(null),d.push(0),this.localMainAudioTrack=null)),a&&(s?(yield c[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=ee(w({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),d.push(3)):(yield c[1].replaceTrack(null),yield c[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=ee(w({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),d.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.setTransceiverDirection(se.INACTIVE,d),yield this.doPublishChange(!1)):yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,r),r==null||r.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return E(this,null,function*(){let r={state:this.publishState,constraintConfig:this._mediaSettings},n=yield this._signalChannel.sendWaitForResponse({command:ne.PUBLISH_STATE_CHANGE,data:r,responseCommand:Q.PUBLISH_STATE_CHANGE_RESULT,enableLog:e});this.checkPublishResultCode(n.data.code,n.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:ne.UNPUBLISH,commandDesc:"unpublish",responseCommand:Q.UNPUBLISH_RESULT,enableLog:e}).catch(r=>{if(r.getCode()===v.API_CALL_TIMEOUT)return Promise.resolve();throw r})}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:r}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":r&&(this._mediaSettings.videoCodec="VP8");let n=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:s,localAuxVideoTrack:o}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?o=this._publishingLocalVideoTrack:s=this._publishingLocalVideoTrack),Ft){if(n&&n.mediaTrack){let a=n.mediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=n.profile.bitrate*1e3,this._mediaSettings.audioFs=a.sampleRate||0}if(s&&s.mediaTrack){let a=s.mediaTrack.getSettings();this._mediaSettings.videoWidth=a.width||0,this._mediaSettings.videoHeight=a.height||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=s.profile.bitrate*1e3,s.small&&(this._mediaSettings.smallVideoWidth=s.small.width,this._mediaSettings.smallVideoHeight=s.small.height,this._mediaSettings.smallVideoFps=s.small.frameRate,this._mediaSettings.smallVideoBps=s.small.bitrate*1e3)}if(o&&o.mediaTrack){let a=o.mediaTrack.getSettings();this._mediaSettings.auxVideoWidth=a.width||0,this._mediaSettings.auxVideoHeight=a.height||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=o.profile.bitrate*1e3}}else n&&n.mediaTrack&&(this._mediaSettings.audioChannel=n.profile.channelCount,this._mediaSettings.audioBps=n.profile.bitrate*1e3,this._mediaSettings.audioFs=n.profile.sampleRate),s&&s.mediaTrack&&(this._mediaSettings.videoWidth=s.profile.width,this._mediaSettings.videoHeight=s.profile.height,this._mediaSettings.videoFps=s.profile.frameRate,this._mediaSettings.videoBps=s.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:ne.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:Q.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return E(this,null,function*(){var n;if(!this._peerConnection)return;let r=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is adding ${e.kind} track to current published local ${r?m.AUXILIARY:m.MAIN} stream`),(n=this._sei)==null||n.handleEncodedStreams(),at()?yield this.addTrackByTransceiver(e,r):yield this.addTrackBySender(e)})}addTrackByTransceiver(e,r){return E(this,null,function*(){var o;if(!e.mediaTrack)return;let n=this._peerConnection.getTransceivers(),s=e.mediaTrack;if(e.kind===m.AUDIO)this._audioManager.addAudioTrack(e),s=this._audioManager.mediaStreamTrack,yield n[0].sender.replaceTrack(s);else{let a=r?3:1;if(yield n[a].sender.replaceTrack(s),a===1&&((o=this.localMainVideoTrack)==null?void 0:o.small)){this._smallGenerator=new Zt(this.localMainVideoTrack),yield this._smallGenerator.initialize();let c=this._smallGenerator.generateSmallVideoTrack(this.localMainVideoTrack.small);yield n[2].sender.replaceTrack(c)}n[a].direction===se.INACTIVE&&(yield this.setTransceiverDirection(se.SENDONLY,[a]))}this.updateMediaSettings(),yield this.doPublishChange()})}addTrackBySender(e){return E(this,null,function*(){if(!e.mediaTrack)return;let r=e.mediaTrack;at()&&this._peerConnection.getTransceivers().findIndex(o=>o.direction==="stopped")>=0&&(this._log.warn("transceiver is stopping, negotiate sdp first"),yield this.updateOffer("remove",r));let n=this._peerConnection.getSenders().find(o=>o.track&&o.track.kind===r.kind);if(n&&n.track){this._log.warn("sender already exists, remove sender first");let o=n.track;this.removeSender(n),yield this.updateOffer("remove",o)}let{mediaStream:s}=e;if(this._peerConnection.addTrack(r,s),r.kind===m.VIDEO&&e instanceof St&&e.small){this._smallGenerator=new Zt(e),yield this._smallGenerator.initialize();let o=this._smallGenerator.generateSmallVideoTrack(e.small),a=new MediaStream;a.addTrack(o),this._peerConnection.addTrack(o,a)}yield this.updateOffer("add",r)})}isNeedToResetOfferOrder(){if(this._sdpSemantics===Ir||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,r=Ie(e);for(let n=0;n<r.media.length;n++)if(Number(r.media[n].mid)===0&&r.media[n].type===m.VIDEO)return!0;return!1}removeSender(e){let r=null;at()&&(r=this._peerConnection.getTransceivers().find(n=>n.sender&&n.sender.track===e.track)),this._peerConnection.removeTrack(e),r&&ce(r.stop)&&(this._log.info("stop transceiver"),r.stop())}removeTrack(e){return E(this,null,function*(){if(!this._peerConnection)return;let r=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${r?m.AUXILIARY:m.MAIN} stream`),at()?yield this.removeTrackByTransceiver(e,r):yield this.removeTrackBySender(e)})}removeTrackByTransceiver(e,r){return E(this,null,function*(){if(!e.mediaTrack)return;let n=this._peerConnection.getTransceivers();if(e.kind===m.AUDIO)this._audioManager.removeAudioTrack(e),this._audioManager.isMixed||(yield n[0].sender.replaceTrack(null));else{let s=r?3:1;yield n[s].sender.replaceTrack(null),s===1&&this._smallGenerator&&(this._smallGenerator.destroy(),this._smallGenerator=null,yield n[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(se.INACTIVE,[s])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,r){return E(this,null,function*(){if(!ue)return;let n=!1,s=!1;this._log.info(`setting transceiver ${r.join(",")} direction to ${e}`);let o=this._peerConnection.getTransceivers();if(r.forEach(d=>{o[d].direction!==e&&(o[d].direction=e,n=!0)}),n){this._log.info("updating offer");let d=yield this._peerConnection.createOffer();yield this._peerConnection.setLocalDescription(d)}let a=-1,c=this._peerConnection.remoteDescription.sdp.split(`\r
96
95
  `).map(d=>{if(d.match(new RegExp(`a=(${se.INACTIVE}|${se.RECVONLY}|${se.SENDONLY})`))&&a++,r.includes(a)){if(e===se.INACTIVE&&d.includes(`a=${se.RECVONLY}`))return s=!0,`a=${e}`;if(e===se.SENDONLY&&d.includes(`a=${se.INACTIVE}`))return s=!0,`a=${se.RECVONLY}`}return d}).join(`\r
97
- `);s&&(this._log.info("updating answer"),yield this._peerConnection.setRemoteDescription({type:"answer",sdp:c}))})}removeTrackBySender(e){return E(this,null,function*(){var n,s;if(!e.mediaTrack)return;if(e.kind===m.VIDEO&&this.isNeedToResetOfferOrder()&&this.localMainAudioTrack){this.reset(),this.initialize(),(s=(n=this.localMainVideoTrack)==null?void 0:n.mediaStream)==null||s.removeTrack(e.mediaTrack),yield this.publish({localAudioTrack:this.localMainAudioTrack,isAuxiliary:!1});return}let r=this._peerConnection.getSenders().find(o=>o.track===e.mediaTrack);r&&(this.removeSender(r),e.kind===m.VIDEO&&this._smallGenerator&&(this._smallGenerator.destroy(),this._smallGenerator=null,this._peerConnection.getSenders().forEach(o=>{o.track&&o.track.kind===m.VIDEO&&this.removeSender(o)}))),yield this.updateOffer("remove",e.mediaTrack)})}replaceTrack(e){return E(this,null,function*(){var o,a;let r=(o=this._peerConnection)==null?void 0:o.getSenders();if(!r||r.length===0||!e.mediaTrack)return;let n=e.mediaTrack,s=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;if(this._log.info(`is replacing ${n.kind} track on ${s?m.AUXILIARY:m.MAIN} stream`),n.kind===m.AUDIO&&r[0])this._audioManager.addAudioTrack(e),this._audioManager.isMixed&&(n=this._audioManager.mediaStreamTrack),yield r[0].replaceTrack(n);else if(n.kind===m.VIDEO){if(!s&&r[1]&&(yield r[1].replaceTrack(n),this._smallGenerator&&r[2])){this._log.info("replacing smallVideo"),this._smallGenerator.destroy(),this._smallGenerator=new Yt(this.localMainVideoTrack),yield this._smallGenerator.initialize();let c=this._smallGenerator.generateSmallVideoTrack(((a=this.localMainVideoTrack)==null?void 0:a.small)||this._room.smallStreamConfig);yield r[2].replaceTrack(c)}s&&r[3]&&(yield r[3].replaceTrack(n))}})}updateOffer(e,r){return E(this,null,function*(){try{let n=yield this._peerConnection.createOffer(Ll);pe&&n.sdp&&(n.sdp=this.setSDPDirection(n.sdp,"sendrecv")),yield this._peerConnection.setLocalDescription(n);let s=this.updateMediaSettings(),o={action:e,trackId:r.id,kind:r.kind===m.VIDEO?"bigVideo":r.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: ${o.sdp}`);let a=yield this._signalChannel.sendWaitForResponse({command:ne.PUBLISH_CHANGE,data:o,responseCommand:Z.UPDATE_OFFER_RESULT,timeout:Bd,commandDesc:"update offer"}),{code:c,message:d}=a.data;c!==0&&this.checkPublishResultCode(c,d),yield this.acceptAnswer(a.data.data),n.sdp&&this.updateSSRC(n.sdp)}catch(n){throw this._log.error(n),n}})}setBandwidth(o){return E(this,arguments,function*({bandwidth:e,type:r,videoType:n,sdp:s}){if(!tn())return s?r===m.VIDEO?this.updateVideoBandwidthRestriction(s,e,n):this.updateAudioBandwidthRestriction(s,e):void 0;let a=0;r===m.VIDEO&&(n===m.SMALL?a=2:n===m.AUXILIARY?a=3:a=1);let c=this._peerConnection.getSenders()[a];if(c){let d=c.getParameters();(!d.encodings||d.encodings.length===0)&&(d.encodings=[{}]),d.encodings[0].maxBitrate=e*1e3;try{return yield c.setParameters(d),this._log.info(`${n||""}${r} bandwidth ${e} kbps`),s}catch(u){if(this._log.info(`failed to set bandwidth by setting maxBitrate: ${u}`),s)return r===m.VIDEO?this.updateVideoBandwidthRestriction(s,e,n):this.updateAudioBandwidthRestriction(s,e)}}return s})}updateVideoBandwidthRestriction(e,r,n){let s="AS";pe&&(s="TIAS",r=r*1e3);let o=0,a=-1;return n===m.SMALL?o=1:n===m.AUXILIARY&&(o=2),e=e.replace(/m=video (.*)\r\nc=IN (.*)\r\n/g,c=>(a+=1,a===o?`${c}b=${s}:${r}\r
98
- `:c)),e}updateAudioBandwidthRestriction(e,r){let n="AS";return pe&&(n="TIAS",r=r*1e3),e=e.replace(/m=audio (.*)\r\nc=IN (.*)\r\n/,`m=audio $1\r
96
+ `);s&&(this._log.info("updating answer"),yield this._peerConnection.setRemoteDescription({type:"answer",sdp:c}))})}removeTrackBySender(e){return E(this,null,function*(){var n,s;if(!e.mediaTrack)return;if(e.kind===m.VIDEO&&this.isNeedToResetOfferOrder()&&this.localMainAudioTrack){this.reset(),this.initialize(),(s=(n=this.localMainVideoTrack)==null?void 0:n.mediaStream)==null||s.removeTrack(e.mediaTrack),yield this.publish({localAudioTrack:this.localMainAudioTrack,isAuxiliary:!1});return}let r=this._peerConnection.getSenders().find(o=>o.track===e.mediaTrack);r&&(this.removeSender(r),e.kind===m.VIDEO&&this._smallGenerator&&(this._smallGenerator.destroy(),this._smallGenerator=null,this._peerConnection.getSenders().forEach(o=>{o.track&&o.track.kind===m.VIDEO&&this.removeSender(o)}))),yield this.updateOffer("remove",e.mediaTrack)})}replaceTrack(e){return E(this,null,function*(){var o,a;let r=(o=this._peerConnection)==null?void 0:o.getSenders();if(!r||r.length===0||!e.mediaTrack)return;let n=e.mediaTrack,s=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;if(this._log.info(`is replacing ${n.kind} track on ${s?m.AUXILIARY:m.MAIN} stream`),n.kind===m.AUDIO&&r[0])this._audioManager.addAudioTrack(e),this._audioManager.isMixed&&(n=this._audioManager.mediaStreamTrack),yield r[0].replaceTrack(n);else if(n.kind===m.VIDEO){if(!s&&r[1]&&(yield r[1].replaceTrack(n),this._smallGenerator&&r[2])){this._log.info("replacing smallVideo"),this._smallGenerator.destroy(),this._smallGenerator=new Zt(this.localMainVideoTrack),yield this._smallGenerator.initialize();let c=this._smallGenerator.generateSmallVideoTrack(((a=this.localMainVideoTrack)==null?void 0:a.small)||this._room.smallStreamConfig);yield r[2].replaceTrack(c)}s&&r[3]&&(yield r[3].replaceTrack(n))}})}updateOffer(e,r){return E(this,null,function*(){try{let n=yield this._peerConnection.createOffer(Gl);ue&&n.sdp&&(n.sdp=this.setSDPDirection(n.sdp,"sendrecv")),yield this._peerConnection.setLocalDescription(n);let s=this.updateMediaSettings(),o={action:e,trackId:r.id,kind:r.kind===m.VIDEO?"bigVideo":r.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: ${o.sdp}`);let a=yield this._signalChannel.sendWaitForResponse({command:ne.PUBLISH_CHANGE,data:o,responseCommand:Q.UPDATE_OFFER_RESULT,timeout:Ea,commandDesc:"update offer"}),{code:c,message:d}=a.data;c!==0&&this.checkPublishResultCode(c,d),yield this.acceptAnswer(a.data.data),n.sdp&&this.updateSSRC(n.sdp)}catch(n){throw this._log.error(n),n}})}setBandwidth(o){return E(this,arguments,function*({bandwidth:e,type:r,videoType:n,sdp:s}){if(!Dn())return s?r===m.VIDEO?this.updateVideoBandwidthRestriction(s,e,n):this.updateAudioBandwidthRestriction(s,e):void 0;let a=0;r===m.VIDEO&&(n===m.SMALL?a=2:n===m.AUXILIARY?a=3:a=1);let c=this._peerConnection.getSenders()[a];if(c){let d=c.getParameters();(!d.encodings||d.encodings.length===0)&&(d.encodings=[{}]),d.encodings[0].maxBitrate=e*1e3;try{return yield c.setParameters(d),this._log.info(`${n||""}${r} bandwidth ${e} kbps`),s}catch(u){if(this._log.info(`failed to set bandwidth by setting maxBitrate: ${u}`),s)return r===m.VIDEO?this.updateVideoBandwidthRestriction(s,e,n):this.updateAudioBandwidthRestriction(s,e)}}return s})}updateVideoBandwidthRestriction(e,r,n){let s="AS";ue&&(s="TIAS",r=r*1e3);let o=0,a=-1;return n===m.SMALL?o=1:n===m.AUXILIARY&&(o=2),e=e.replace(/m=video (.*)\r\nc=IN (.*)\r\n/g,c=>(a+=1,a===o?`${c}b=${s}:${r}\r
97
+ `:c)),e}updateAudioBandwidthRestriction(e,r){let n="AS";return ue&&(n="TIAS",r=r*1e3),e=e.replace(/m=audio (.*)\r\nc=IN (.*)\r\n/,`m=audio $1\r
99
98
  c=IN $2\r
100
99
  b=${n}:${r}\r
101
- `),e}removeBandwidthRestriction(e){return e.replace(/b=AS:.*\r\n/,"").replace(/b=TIAS:.*\r\n/,"")}removeVideoOrientation(e){return e.replace(/urn:3gpp:video-orientation/,"")}connect(){return E(this,null,function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(e){throw this.closePeerConnection(!0),this.uninstallEvents(),e}})}exchangeSDP(){return E(this,null,function*(){try{yield this.createOffer(),this._log.info("createOffer success, sending offer to remote server"),yield this.doExchangeSDP()}catch(e){throw e}})}createOffer(){return E(this,null,function*(){try{let e=yield this._peerConnection.createOffer(Ll);yield this._peerConnection.setLocalDescription(e),e.sdp&&this.updateSSRC(e.sdp)}catch(e){throw e}})}doExchangeSDP(){let e={command:ne.PUBLISH,responseCommand:Z.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof bt||this.localAuxVideoTrack instanceof bt,state:this.publishState,constraintConfig:this._mediaSettings},enableLog:!1};return this._log.debug(`sending sdp offer: ${e.data.sdp}`),this._signalChannel.sendWaitForResponse(e).then(r=>{let{code:n,message:s,data:o}=r.data;return n===0?this.acceptAnswer(o):this.checkPublishResultCode(n,s)})}setSDPDirection(e,r,n="all"){let s=Re(e);return s.media.forEach(o=>{(n==="all"||o.type===n)&&(o.direction=r)}),ct(s)}acceptAnswer(e){return E(this,null,function*(){var r,n,s,o,a;try{let c;if(this._publishingLocalAudioTrack||this._publishingLocalVideoTrack||this.isMainStreamPublished){let l=((r=this._publishingLocalVideoTrack)==null?void 0:r.profile.bitrate)||((n=this.localMainVideoTrack)==null?void 0:n.profile.bitrate),h=((s=this._publishingLocalAudioTrack)==null?void 0:s.profile.bitrate)||((o=this.localMainAudioTrack)==null?void 0:o.profile.bitrate);if(l){let I=this._isPublishingAux?m.AUXILIARY:m.BIG;c=yield this.setBandwidth({bandwidth:l,type:m.VIDEO,sdp:c,videoType:I})}h&&(c=yield this.setBandwidth({bandwidth:h,type:m.AUDIO,sdp:c}))}if(c=this.removeVideoOrientation(e.sdp),(a=this._publishingLocalVideoTrack)!=null&&a.small){let{smallStreamConfig:l}=this._room;c=yield this.setBandwidth({bandwidth:this._publishingLocalVideoTrack.small.bitrate||l.bitrate,type:m.VIDEO,videoType:m.SMALL,sdp:c})}let u={type:e.type,sdp:c};yield this._peerConnection.setRemoteDescription(u),this._log.debug(`accepted answer: ${c}`)}catch(c){throw this._log.error(`failed to accept remote answer ${c}`),c}})}sendMutedFlag(e){var s,o,a;if(e===this.localAuxAudioTrack||e===this.localAuxVideoTrack)return;let n={audio:!!((s=this.localMainAudioTrack)!=null&&s.muted),bigVideo:!!((o=this.localMainVideoTrack)!=null&&o.muted),auxVideo:!!((a=this.localAuxVideoTrack)!=null&&a.muted)};this._log.info(`send muted state: ${JSON.stringify(n)}`),this._signalChannel.send(ne.UPDATE_MUTE_STAT,n)}getIsReconnecting(){return this._isReconnecting}reconnect(){return E(this,null,function*(){if(!(Ei(Dc.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:ne.UNPUBLISH,responseCommand:Z.UNPUBLISH_RESULT,enableLog:!1}),this.closePeerConnection(),this.initialize(),this.isMainStreamPublished&&(yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0})),this._log.warn("reconnect() uplink reconnect successfully"),this.stopReconnection()}catch(r){let n=rt(this._reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${n/1e3}s`),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},n)}})}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&C.emit(S.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{Re(e).media.forEach((n,s)=>{if(n.type===m.AUDIO){let o=n.ssrcs&&n.ssrcs[0];o&&(this.ssrc.audio=Number(o.id))}else{if(this._sdpSemantics===Pr&&n.ssrcGroups){n.ssrcGroups.forEach((a,c)=>{let d=Number(a.ssrcs.split(" ")[0]);c===0?this.ssrc.video=d:c===1&&(this.ssrc.small=d)});return}let o=n.ssrcs&&n.ssrcs[0];if(!o)return;switch(s){case 1:this.ssrc.video=Number(o.id);break;case 2:this.ssrc.small=Number(o.id);break;case 3:this.ssrc.auxiliary=Number(o.id);break;default:break}}})}catch(r){}}getVideoTrackId(e=m.VIDEO){if(this._peerConnection){let r=this._peerConnection.getSenders();if(e===m.AUXILIARY&&r[3]&&r[3].track)return r[3].track.id;if(e===m.VIDEO&&r[1]&&r[1].track)return r[1].track.id}if(this.localMainVideoTrack&&e===m.VIDEO){let r=this.localMainVideoTrack.mediaTrack;if(r)return r.id}if(this.localAuxVideoTrack&&e===m.AUXILIARY){let r=this.localAuxVideoTrack.mediaTrack;if(r)return r.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,r){if(e!==0)throw e===qi?(this._log.error(Le.NOT_SUPPORTED_H264ENCODE),new L({code:v.NOT_SUPPORTED_H264,message:$({key:w.NOT_SUPPORTED_H264ENCODE})})):new L({code:v.UNKNOWN,message:$({key:w.SIGNAL_RESPONSE_FAILED,data:{signalResponse:Z.PUBLISH_RESULT,code:e,message:r}})})}sendSEI(e,r){var n;(n=this._sei)==null||n.push(e,r)}},In=Dc;F([ce(i=>function(...t){return new Promise((e,r)=>{let n=s=>{this._emitter.off("closed",n),r(new L({code:v.API_CALL_ABORTED,message:$({key:w.CONNECTION_ABORTED,data:s})}))};this._emitter.on("closed",n),i.apply(this,t).then(e,r).finally(()=>{this._emitter.off("closed",n)})})})],In.prototype,"publish",1),F([vs(Qe.prototype.afterConnect),ys(Qe.prototype.beforeConnect)],In.prototype,"connect",1);var Ks=In;var zO=_(f());var Rn=class{constructor(t,e){this.room=t;p(this,"_log");p(this,"_prevReportTime");p(this,"_prevReport",{});p(this,"_prevEncoderImplementation");p(this,"_prevQualityLimitationReason");p(this,"_prevAuxQualityLimitationReason");p(this,"_prevDecoderImplementationMap",new Map);p(this,"_spcStats",null);this._log=e,this._prevReportTime=0,this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevAuxQualityLimitationReason=""}get statInterval(){return this._prevReportTime===0?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(t){return E(this,null,function*(){var s;let e={audio:{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0},video:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},small:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},auxiliary:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},rtt:0},r=t.getPeerConnection(),n=t.getSSRC();if(r)try{(this._spcStats||(yield r.getStats())).forEach(a=>{if(a.type==="outbound-rtp")if(a.mediaType===m.VIDEO){let c;if(a.ssrc===n.video?c=m.VIDEO:a.ssrc===n.small?c=m.SMALL:a.ssrc===n.auxiliary&&(c=m.AUXILIARY),!c)return;e[c].bytesSent=a.bytesSent,e[c].packetsSent=a.packetsSent,e[c].framesEncoded=a.framesEncoded,a.ssrc===n.video?(!b(a.encoderImplementation)&&this._prevEncoderImplementation!==a.encoderImplementation&&(this._log.info(`encoderImplementation change to ${a.encoderImplementation}`),this._prevEncoderImplementation=a.encoderImplementation),!b(a.qualityLimitationReason)&&a.bytesSent!==0&&this._prevQualityLimitationReason!==a.qualityLimitationReason&&(this._log.info(`qualityLimitationReason change to ${a.qualityLimitationReason}`),this._prevQualityLimitationReason=a.qualityLimitationReason)):a.ssrc===n.auxiliary&&!b(a.qualityLimitationReason)&&a.bytesSent!==0&&this._prevAuxQualityLimitationReason!==a.qualityLimitationReason&&(this._log.info(`aux qualityLimitationReason change to ${a.qualityLimitationReason}`),this._prevAuxQualityLimitationReason=a.qualityLimitationReason)}else a.mediaType===m.AUDIO&&(e.audio.bytesSent=a.bytesSent,e.audio.packetsSent=a.packetsSent);else a.type==="candidate-pair"?ci(a)&&de(a.currentRoundTripTime)&&(e.rtt=Math.floor(a.currentRoundTripTime*1e3)):a.type==="media-source"&&(a.kind===m.AUDIO?(e.audio.audioLevel=a.audioLevel||0,e.audio.totalAudioEnergy=a.totalAudioEnergy||0):a.kind===m.VIDEO&&(a.trackIdentifier===t.getVideoTrackId(m.VIDEO)?e.video.fpsCapture=a.framesPerSecond:a.trackIdentifier===t.getVideoTrackId(m.AUXILIARY)?e.auxiliary.fpsCapture=a.framesPerSecond:e.small.fpsCapture=a.framesPerSecond));if(b(a.audioLevel)||(e.audio.audioLevel=a.audioLevel||0),!b(a.frameWidth)){let c=m.SMALL;a.trackIdentifier===t.getVideoTrackId(m.VIDEO)||a.ssrc===n.video?c=m.VIDEO:(a.trackIdentifier===t.getVideoTrackId(m.AUXILIARY)||a.ssrc===n.auxiliary)&&(c=m.AUXILIARY),e[c].frameWidth=a.frameWidth,e[c].frameHeight=a.frameHeight,e[c].framesSent=a.framesSent}}),e.audio.audioLevel===0&&(e.audio.audioLevel=((s=t.localMainAudioTrack)==null?void 0:s.getInternalAudioLevel())||0)}catch(o){this._log.warn(`failed to getStats on sender connection ${o}`)}return e})}getReceiverStats(t){return E(this,null,function*(){let e={tinyId:t.tinyId,userId:t.userId,rtt:0,hasAudio:!1,hasVideo:!1,hasAuxiliary:!1,audio:{bytesReceived:0,packetsReceived:0,packetsLost:0,jitter:0,audioLevel:0,totalAudioEnergy:0,insertedSamplesForDeceleration:0,removedSamplesForAcceleration:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0}},r=t.getPeerConnection();if(r)try{let{ssrc:n}=t,{muteState:s}=t;(this._spcStats||(yield r.getStats())).forEach(a=>{if(a.type==="inbound-rtp"){if(a.mediaType===m.AUDIO&&a.ssrc===n.audio&&s.hasAudio){e.audio.packetsReceived=a.packetsReceived,e.audio.bytesReceived=a.bytesReceived,e.audio.packetsLost=a.packetsLost,a.insertedSamplesForDeceleration&&(e.audio.insertedSamplesForDeceleration=a.insertedSamplesForDeceleration),a.removedSamplesForAcceleration&&(e.audio.removedSamplesForAcceleration=a.removedSamplesForAcceleration);let{remoteAudioTrack:c}=t;c.stat.packetsReceived=a.packetsReceived,c.stat.bytesReceived=a.bytesReceived,c.stat.packetsLost=a.packetsLost,a.jitterBufferDelay&&(c.stat.jitterBufferDelay=Math.floor(a.jitterBufferDelay/a.jitterBufferEmittedCount*1e3)),e.hasAudio=!0}else if(a.mediaType===m.VIDEO){if(pe&&a.bytesReceived===0)return;let c;a.ssrc===n.video&&s.hasVideo&&(e.video.packetsReceived=a.packetsReceived,e.video.bytesReceived=a.bytesReceived,e.video.packetsLost=a.packetsLost,e.video.framesReceived=a.framesReceived,e.video.framesDecoded=a.framesDecoded,e.video.fpsDecoded=a.framesPerSecond,e.hasVideo=!0,c=t.remoteVideoTrack,a.decoderImplementation&&(!this._prevDecoderImplementationMap.has(e.userId)||this._prevDecoderImplementationMap.get(e.userId)!==a.decoderImplementation)&&(this._log.info(`${e.userId} decoderImplementation change to ${a.decoderImplementation}`),this._prevDecoderImplementationMap.set(e.userId,a.decoderImplementation))),a.ssrc===n.auxiliary&&s.hasAuxiliary&&(e.auxiliary.packetsReceived=a.packetsReceived,e.auxiliary.bytesReceived=a.bytesReceived,e.auxiliary.packetsLost=a.packetsLost,e.auxiliary.framesReceived=a.framesReceived,e.auxiliary.framesDecoded=a.framesDecoded,e.auxiliary.fpsDecoded=a.framesPerSecond,c=t.remoteAuxiliaryTrack,e.hasAuxiliary=!0),c&&(c.stat.packetsReceived=a.packetsReceived,c.stat.bytesReceived=a.bytesReceived,c.stat.packetsLost=a.packetsLost,c.stat.framesReceived=a.framesReceived,c.stat.framesDecoded=a.framesDecoded,a.jitterBufferDelay&&(c.stat.jitterBufferDelay=Math.floor(a.jitterBufferDelay/a.jitterBufferEmittedCount*1e3)))}}else a.type==="candidate-pair"&&ci(a)&&de(a.currentRoundTripTime)&&(e.rtt=Math.floor(a.currentRoundTripTime*1e3));b(a.frameWidth)||((a.trackIdentifier===t.getMainStreamVideoTrackId()||a.ssrc===n.video)&&(e.video.frameWidth=a.frameWidth,e.video.frameHeight=a.frameHeight,t.remoteVideoTrack.stat.frameWidth=a.frameWidth,t.remoteVideoTrack.stat.frameHeight=a.frameHeight),(a.trackIdentifier===t.getAuxStreamVideoTrackId()||a.ssrc===n.auxiliary)&&(e.auxiliary.frameWidth=a.frameWidth,e.auxiliary.frameHeight=a.frameHeight,t.remoteAuxiliaryTrack.stat.frameWidth=a.frameWidth,t.remoteAuxiliaryTrack.stat.frameHeight=a.frameHeight)),b(a.audioLevel)||(e.audio.audioLevel=a.audioLevel||0,e.audio.totalAudioEnergy=a.totalAudioEnergy||0)}),e.audio.audioLevel===0&&(e.audio.audioLevel=t.remoteAudioTrack.getInternalAudioLevel()||0)}catch(n){this._log.warn(`failed to getStats on receiver connection ${n}`)}return e})}getStats(t,e){return E(this,null,function*(){let r={},n=[];if(this.room.singlePC){let s=this.room.singlePC.getPeerConnection();if(!s)return{senderStats:r,receiverStats:n};let o=yield s.getStats(),a=[],c=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source"]);o.forEach(d=>c.has(d.type)&&a.push(d)),this._spcStats=a}t&&(r=yield this.getSenderStats(t));for(let[s,o]of e){let a=yield this.getReceiverStats(o);n.push(a)}return{senderStats:r,receiverStats:n}})}getDifferenceValue(t,e){if(Ft(t))return e;let r=e-t;return r<0?0:r}prepareReport({stats:t,report:e,freezeMap:r}){if(!Ft(t.senderStats)){let u={uint32_audio_level:t.senderStats.audio.audioLevel*Ai,uint32_audio_energy:t.senderStats.audio.totalAudioEnergy*1e6,uint32_audio_codec_bitrate:t.senderStats.audio.bytesSent},l=[],h={uint32_video_stream_type:2,uint32_video_codec_fps:t.senderStats.video.framesSent,uint32_video_capture_fps:t.senderStats.video.fpsCapture,uint32_video_width:t.senderStats.video.frameWidth,uint32_video_height:t.senderStats.video.frameHeight,uint32_video_codec_bitrate:t.senderStats.video.bytesSent,uint32_video_enc_fps:t.senderStats.video.framesEncoded};if(l.push(h),t.senderStats.small.bytesSent){let T={uint32_video_stream_type:3,uint32_video_codec_fps:t.senderStats.small.framesSent||0,uint32_video_capture_fps:t.senderStats.small.fpsCapture||0,uint32_video_width:t.senderStats.small.frameWidth||0,uint32_video_height:t.senderStats.small.frameHeight||0,uint32_video_codec_bitrate:t.senderStats.small.bytesSent,uint32_video_enc_fps:t.senderStats.small.framesEncoded||0};l.push(T)}if(t.senderStats.auxiliary.bytesSent){let T={uint32_video_stream_type:7,uint32_video_codec_fps:t.senderStats.auxiliary.framesSent||0,uint32_video_capture_fps:t.senderStats.auxiliary.fpsCapture||0,uint32_video_width:t.senderStats.auxiliary.frameWidth||0,uint32_video_height:t.senderStats.auxiliary.frameHeight||0,uint32_video_codec_bitrate:t.senderStats.auxiliary.bytesSent,uint32_video_enc_fps:t.senderStats.auxiliary.framesEncoded||0};l.push(T)}let I={uint32_bitrate:0,uint32_lost:0,uint32_rtt:t.senderStats.rtt};e.msg_up_stream_info={msg_audio_status:u,msg_video_status:l,msg_network_status:I}}let{statInterval:n}=this;e.msg_down_stream_info=[],t.receiverStats.forEach(u=>{let l={msg_user_info:{str_identifier:u.userId,uint64_tinyid:u.tinyId},msg_network_status:{uint32_rtt:u.rtt,uint32_bitrate:0,uint32_lost:0},msg_audio_status:{},msg_video_status:[]};if(u.hasAudio){let h={uint32_audio_codec_bitrate:u.audio.bytesReceived,uint32_audio_total_bitrate:u.audio.bytesReceived,uint32_audio_level:u.audio.audioLevel*1e8,uint32_audio_energy:u.audio.totalAudioEnergy*1e6,uint32_audio_receive:u.audio.packetsReceived,uint32_audio_origin_lost:u.audio.packetsLost};l.msg_audio_status=h}if(u.hasVideo){let h=r.get(`${u.userId}_${Ud}`),I=h?h.duration:0,T={uint32_video_stream_type:2,uint32_video_receive_fps:u.video.framesReceived,uint32_video_width:u.video.frameWidth,uint32_video_height:u.video.frameHeight,uint32_video_codec_bitrate:u.video.bytesReceived,uint32_video_receive:u.video.packetsReceived,uint32_video_origin_lost:u.video.packetsLost,uint32_video_block_time:I,uint32_video_dec_fps:u.video.framesDecoded};l.msg_video_status.push(T)}if(u.hasAuxiliary){let h=r.get(`${u.userId}_${Kn}`),I=h?h.duration:0,T={uint32_video_stream_type:7,uint32_video_receive_fps:u.auxiliary.framesReceived,uint32_video_width:u.auxiliary.frameWidth,uint32_video_height:u.auxiliary.frameHeight,uint32_video_codec_bitrate:u.auxiliary.bytesReceived,uint32_video_receive:u.auxiliary.packetsReceived+u.auxiliary.packetsLost,uint32_video_origin_lost:u.auxiliary.packetsLost,uint32_video_block_time:I,uint32_video_dec_fps:u.auxiliary.framesDecoded};l.msg_video_status.push(T)}e.msg_down_stream_info.push(l)});let s=this._prevReport;if(this._prevReport=JSON.parse(JSON.stringify(e)),e.msg_up_stream_info.msg_audio_status&&s.msg_up_stream_info.msg_audio_status){let u=s.msg_up_stream_info.msg_audio_status,l=e.msg_up_stream_info.msg_audio_status,h=this.getDifferenceValue(u.uint32_audio_codec_bitrate,l.uint32_audio_codec_bitrate);l.uint32_audio_codec_bitrate=Math.round(h*8/n),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=l.uint32_audio_codec_bitrate}let o=s.msg_up_stream_info.msg_video_status;e.msg_up_stream_info.msg_video_status.forEach(u=>{let l=o.find(H=>H.uint32_video_stream_type===u.uint32_video_stream_type);if(!l||l.uint32_video_codec_bitrate===0){u.uint32_video_codec_bitrate=0,u.uint32_video_enc_fps=0,u.uint32_video_codec_fps=0;return}let h=0,I=0,T=0;l&&u.uint32_video_codec_bitrate>=l.uint32_video_codec_bitrate&&(h=l.uint32_video_codec_bitrate,I=l.uint32_video_enc_fps,T=l.uint32_video_codec_fps);let N=this.getDifferenceValue(h,u.uint32_video_codec_bitrate);u.uint32_video_codec_bitrate=Math.round(N*8/n),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=u.uint32_video_codec_bitrate,u.uint32_video_enc_fps=Math.round(this.getDifferenceValue(I,u.uint32_video_enc_fps)/n),u.uint32_video_codec_fps=Math.round(this.getDifferenceValue(T,u.uint32_video_codec_fps)/n)});let c=e.msg_down_stream_info,d=s.msg_down_stream_info;return c.forEach(u=>{let l=d.find(h=>h.msg_user_info.uint64_tinyid===u.msg_user_info.uint64_tinyid);if(!!l){if(!Ft(u.msg_audio_status)&&!Ft(l.msg_audio_status)){let h=u.msg_audio_status,I=l.msg_audio_status;h.uint32_audio_origin_lost=this.getDifferenceValue(I.uint32_audio_origin_lost,h.uint32_audio_origin_lost),h.uint32_audio_receive=this.getDifferenceValue(I.uint32_audio_receive,h.uint32_audio_receive),h.uint32_audio_receive+=h.uint32_audio_origin_lost;let T=this.getDifferenceValue(I.uint32_audio_codec_bitrate,h.uint32_audio_codec_bitrate);h.uint32_audio_codec_bitrate=Math.round(T*8/n),h.uint32_audio_total_bitrate=Math.round(T*8/n)}else u.msg_audio_status={};if(u.msg_video_status&&l.msg_video_status){let h=l.msg_video_status;u.msg_video_status=u.msg_video_status.filter(T=>h.find(N=>N.uint32_video_stream_type===T.uint32_video_stream_type)),u.msg_video_status.forEach(T=>{let N=h.find(Y=>Y.uint32_video_stream_type===T.uint32_video_stream_type),H=N.uint32_video_receive,U=N.uint32_video_origin_lost,G=N.uint32_video_codec_bitrate,Ie=N.uint32_video_receive_fps,A=N.uint32_video_dec_fps;T.uint32_video_origin_lost=this.getDifferenceValue(U,T.uint32_video_origin_lost),T.uint32_video_receive=this.getDifferenceValue(H,T.uint32_video_receive)+T.uint32_video_origin_lost;let V=this.getDifferenceValue(G,T.uint32_video_codec_bitrate);T.uint32_video_codec_bitrate=Math.round(V*8/n);let y=this.getDifferenceValue(Ie,T.uint32_video_receive_fps);T.uint32_video_receive_fps=Math.round(y/n),T.uint32_video_dec_fps=Math.round(this.getDifferenceValue(A,T.uint32_video_dec_fps)/n)})}}}),e}getStatsReport(n){return E(this,arguments,function*({uplinkConnection:t,downlinkConnections:e,freezeMap:r}){let 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},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:0},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},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}}]},o=yield this.getStats(t,e);return JSON.stringify(this._prevReport)==="{}"&&(this._prevReport=JSON.parse(JSON.stringify(s))),this.prepareReport({stats:o,report:s,freezeMap:r}),this._prevReportTime=Date.now(),s})}reset(){this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map}};var uP=_(f());var kl=_(nt());var Oc=class extends kl.default{constructor({signalChannel:e,room:r}){super();p(this,"_room");p(this,"_signalChannel");p(this,"_log");p(this,"_uplinkRTT",0);p(this,"_uplinkLoss",0);p(this,"_downlinkRTT",0);p(this,"_downlinkLoss",0);p(this,"_downlinkPrevStatMap",new Map);p(this,"_downlinkLossAndRTTMap",new Map);p(this,"_interval",-1);p(this,"_uplinkNetworkQuality",0);p(this,"_downlinkNetworkQuality",0);this._room=r,this._signalChannel=e,this._log=M.createLogger({id:"q",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),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){let{rtt:r,loss:n}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._log.info(`downlink network quality change ${this.downlinkNetworkQuality} -> ${e}, rtt: ${r}, loss: ${n}`)}this._downlinkNetworkQuality=e}initialize(){this._signalChannel.on(Z.UPLINK_NETWORK_STATS,e=>{this.handleUplinkNetworkQuality(e)}),this._signalChannel.on(ge.CONNECTION_STATE_CHANGED,this.handleSignalConnectionStateChange.bind(this)),this.start()}handleUplinkNetworkQuality(e){var c,d;if(e.data.code!==0)return;let r=e.data.data;if(r.delay&&this.updateDelay(r.delay),!this._room.uplinkConnection){this.uplinkNetworkQuality=0,this._uplinkLoss=0,this._uplinkRTT=0;return}let n=(d=(c=this._room)==null?void 0:c.uplinkConnection)==null?void 0:d.getPeerConnection();if(n&&this.isPeerConnectionDisconnected(n)){this.uplinkNetworkQuality=6,this._uplinkLoss=0,this._uplinkRTT=0;return}let s=r.expectAudPkg+r.expectVidPkg,o=r.recvAudPkg+r.recvVidPkg,a=s-o;s===0&&o===0||(a<=0?this._uplinkLoss=0:this._uplinkLoss=Math.round(a/s*100),this._uplinkRTT=r.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this._uplinkLoss,this._uplinkRTT))}handleDownlinkNetworkQuality(){return E(this,null,function*(){if(this._room.remotePublishedUserMap.size===0){this.downlinkNetworkQuality=0;return}let e=[...this._room.remotePublishedUserMap.values()],r=e.filter(a=>{var c;return((c=a.getPeerConnection())==null?void 0:c.connectionState)===fe.CONNECTED});if(e.filter(a=>this.isPeerConnectionDisconnected(a.getPeerConnection())).length===e.length){this.downlinkNetworkQuality=6;return}for(let a=0;a<r.length;a++){let c=r[a].getPeerConnection();if(!c)return;let{rtt:d,totalPacketsLost:u,totalPacketsReceived:l}=yield this.getStat(c);if(!this._downlinkPrevStatMap.has(c)){this._downlinkPrevStatMap.set(c,{totalPacketsLost:u,totalPacketsReceived:l});continue}let h=0,I=this._downlinkPrevStatMap.get(c),T=u-I.totalPacketsLost,N=l-I.totalPacketsReceived;T<=0||N<0?h=0:h=Math.round(T/(T+N)*100),this._downlinkPrevStatMap.set(c,{totalPacketsLost:u,totalPacketsReceived:l}),this._downlinkLossAndRTTMap.set(c,{rtt:d,loss:h,userId:r[a].getUserId(),audioDelay:r[a].remoteAudioTrack.stat.end2EndDelay,videoDelay:r[a].remoteVideoTrack.stat.end2EndDelay})}if([...this._downlinkPrevStatMap.keys()].forEach(a=>{this.isPeerConnectionDisconnected(a)&&(this._downlinkPrevStatMap.delete(a),this._downlinkLossAndRTTMap.delete(a))}),this._downlinkLossAndRTTMap.size===0)return;let{rtt:s,loss:o}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._downlinkRTT=s,this._downlinkLoss=o,this.downlinkNetworkQuality=this.getNetworkQuality(o,s)})}getStat(e){return E(this,null,function*(){let r={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!vi())return r;let n=e.getReceivers();try{for(let s=0;s<n.length;s++)(yield n[s].getStats()).forEach(c=>{c.type==="candidate-pair"&&de(c.currentRoundTripTime)&&(r.rtt=Math.round(c.currentRoundTripTime*1e3)),c.type==="inbound-rtp"&&(c.mediaType===m.AUDIO||c.mediaType===m.VIDEO)&&(r.totalPacketsLost+=c.packetsLost,r.totalPacketsReceived+=c.packetsReceived)});return r}catch(s){return r}})}getAverageLossAndRTT(e){let r={rtt:0,loss:0};return Array.isArray(e)&&e.length>0&&(e.forEach(n=>{r.rtt+=n.rtt,r.loss+=n.loss}),Object.keys(r).forEach(n=>{r[n]=Math.round(r[n]/e.length)})),r}getNetworkQuality(e,r){return e>50||r>500?5:e>30||r>350?4:e>20||r>200?3:e>10||r>100?2:e>=0||r>=0?1:0}handleSignalConnectionStateChange(e){e.state===qe.DISCONNECTED?(this._uplinkRTT=0,this._uplinkLoss=0,this.uplinkNetworkQuality=6):e.state===qe.CONNECTED&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=5)}handleUplinkConnectionStateChange({state:e}){e==="DISCONNECTED"?(this._uplinkLoss=0,this._uplinkRTT=0,this.uplinkNetworkQuality=6):e==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=5)}isPeerConnectionDisconnected(e){return!!(e&&(e.connectionState===fe.DISCONNECTED||e.connectionState===fe.FAILED||e.connectionState===fe.CLOSED))}setUplinkConnection(e){this._room.uplinkConnection=e,this._room.uplinkConnection?this._room.uplinkConnection.on(Ou.CONNECTION_STATE_CHANGED,this.handleUplinkConnectionStateChange.bind(this)):(this.uplinkNetworkQuality=0,this._uplinkRTT=0,this._uplinkLoss=0)}start(){if(this._interval!==-1){this._log.info("network quality calculating is already started");return}this._log.debug("start network quality calculating"),this._interval=me.run(kt,()=>{this.handleDownlinkNetworkQuality();let e=[...this._downlinkLossAndRTTMap.values()];C.emit(S.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this._uplinkRTT,loss:this._uplinkLoss},downlinks:e}),this.emit(Oc.EVENT_NETWORK_QUALITY,{uplinkNetworkQuality:this.uplinkNetworkQuality,downlinkNetworkQuality:this.downlinkNetworkQuality,uplinkRTT:this._uplinkRTT,uplinkLoss:this._uplinkLoss,downlinkRTT:this._downlinkRTT,downlinkLoss:this._downlinkLoss,downlinkInfo:e})},{delay:2e3})}stop(){this._log.info("stop network quality calculating"),this._interval!==-1&&(me.clearTask(this._interval),this._interval=-1),this._downlinkLossAndRTTMap.clear(),this._downlinkPrevStatMap.clear()}updateDelay(e){let{tinyIdToUserIdMap:r}=this._room;e.forEach(({srcTinyId:n,videoDelay:s,audioDelay:o})=>{let a=r.get(n);if(a){let c=this._room.remotePublishedUserMap.get(a);c==null||c.setDelay({videoDelay:s,audioDelay:o})}})}},Bi=Oc;p(Bi,"EVENT_NETWORK_QUALITY","0");var xL=_(f(),1);var xP=_(f(),1);var _P=_(f(),1);var Xt=new WeakMap;function An({settings:i={retries:5,timeout:2e3},onError:t,onRetrying:e,onRetryFailed:r}){return function(n,s,o){let a=vt({retryFunction:o.value,settings:i,onError(c,d,u){t&&t.call(this,c,()=>{var l;(l=Xt.get(n))!=null&&l.has(s)?d():u(c)},u)},onRetrying:(c,d)=>{var u;ue(e)&&e(c,d),(u=Xt.get(n))!=null&&u.has(s)&&(Xt.get(n).get(s).stopRetry=d)},onRetryFailed:r});return o.value=function(...c){let d=Xt.get(n);return d?d.set(s,{args:c}):Xt.set(n,new Map([[s,{args:c}]])),a.apply(this,c).finally(()=>{var u;return(u=Xt.get(n))==null?void 0:u.delete(s)})},o}}function Cn({fnName:i,callback:t,validateArgs:e=!0}){return function(r,n,s){let o=s.value;return s.value=function(...a){var c,d;if((c=Xt.get(r))!=null&&c.has(i)){let{stopRetry:u,args:l}=Xt.get(r).get(i),h=!0;if(e){for(let I of l)if(!a.find(T=>T===I)){h=!1;break}}h&&(t&&t.apply(this,a),u&&u(),(d=Xt.get(r))==null||d.delete(i))}return o.apply(this,a)},s}}var js=class{constructor(t){this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0};this._apiSuccessRateMap=new Map;this._eventMap=new Map;this._frameWorkType=t.frameWorkType||30,this._component=t.component||0,this.connectionType=t.connectionType||1,this._room=t.room,this._keyPrefix="key_point",this._log=M.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(e=>{e.startsWith("handle")&&ue(this[e])&&(this[e]=Xo({fn:this[e],context:this}))}),this.initData(),this.installEvents(),this._intervalId=me.run(kt,this.setStorage.bind(this),{delay:2e4})}get _storageKey(){return`${this._keyPrefix}_${this._room.userId}`}initData(){this._firstPublishedUserList=[],this._networkQuality={totalUplinkRTT:0,totalUplinkLoss:0,count:0,totalDownlinkRTTAndLossMap:new Map},this._basicInfo={string_sdk_version:We,uint32_os_type:15,string_device_name:"",string_http_user_agent:navigator.userAgent,string_os_version:"",uint32_avg_rtt:0,uint32_avg_up_loss:0,uint32_scene:this._room.scene==="live"?1:0,uint32_joining_duration:0,uint32_networkType:Si[us()],uint32_framework:this._frameWorkType,uint32_component:this._component,uint32_connection_type:this.connectionType},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._localStreamStat={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._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,this._apiSuccessRateMap.clear()}addEvent(t,e){return this._eventMap.set(t,e),C.on(t,e),this}installEvents(){this._room.once("banned",()=>this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})),this.addEvent(S.JOIN_START,this.handleJoinStart).addEvent(S.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(S.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(S.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(S.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(S.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(S.JOIN_FAILED,this.handleJoinFailed).addEvent(S.LEAVE_START,this.handleLeaveStart).addEvent(S.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(S.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(S.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(S.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(S.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(S.PUBLISH_START,this.handlePublishStart).addEvent(S.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(S.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(S.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(S.PLAY_TRACK_START,this.handlePlayStart).addEvent(S.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(S.PLAYER_STATE_CHANGED,({track:t,state:e,type:r})=>{!si(t)||!this.hitTest(t.room)||e==="PLAYING"&&(r===m.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))}).addEvent(S.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(S.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(S.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(S.REMOTE_PUBLISH_STATE_CHANGED,({room:t,prevMuteState:e,muteState:r})=>{if(!this.hitTest(t))return;let n=e.hasAudio||e.hasVideo||e.hasSmall,s=e.hasAuxiliary,o=r.hasAudio||r.hasVideo||r.hasSmall,a=r.hasAuxiliary;!n&&o&&this.handleRemoteStreamAdded(r.userId,"main"),!s&&a&&this.handleRemoteStreamAdded(r.userId,"auxiliary")}).addEvent(S.API_SUCCESS_RATE,this.handleAPISuccessRate)}uninstallEvents(){this._eventMap.forEach((t,e)=>C.off(e,t)),this._eventMap.clear()}destroy(){this.uninstallEvents(),me.clearTask(this._intervalId)}handleJoinStart(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_start_time===0&&(this._pathJoinRoom.uint64_start_time=Date.now(),this.checkStorage())}handleSignalConnectionStart({room:t}){this.hitTest(t)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time=Date.now())}handleSignalConnectionEnd({room:t,error:e}){this.hitTest(t)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time=Date.now(),e&&(this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret=e instanceof L?Number(e.getExtraCode()||e.getCode()):v.UNKNOWN,this._pathJoinRoom.int32_end_ret=2))}handleJoinSendCMD(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now())}handleJoinReceivedCMDResponce(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=t.code,t.code!==0&&(this._pathJoinRoom.int32_end_ret=3))}handleJoinSuccess(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_end_time===0&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=t.room.getSignalInfo())}handleJoinFailed({room:t}){this.hitTest(t)&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret===0&&(this._pathJoinRoom.int32_end_ret=3),setTimeout(()=>{this.report()}))}handleReceivedPublishUserList(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_recv_userlist_time===0&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=t.publishedUserList||[])}handleSendFirstVideoFrame({room:t}){!this.hitTest(t)||this._pathJoinRoom.uint64_send_first_video_frame_time===0&&this._pathJoinRoom.uint64_start_time!==0&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now())}handleLeaveStart(t){this.hitTest(t.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(t){this.hitTest(t.room)&&this._pathLeaveRoom.uint64_end_time===0&&(this._pathLeaveRoom.uint64_end_time=Date.now(),this._pathJoinRoom.uint64_end_time!==0?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(t){this.hitTest(t.room)&&(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(t,e){var n;let r=`${t}_${e}`;if(!this._remoteStreamStatMap.has(r)){let s={userId:t,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:te(B({},F_),{msg_user_info:new yn({userId:t,tinyId:(n=this._room.remotePublishedUserMap.get(t))==null?void 0:n.tinyId,role:20})})};s.statsToReport.uint32_stream_type=e==="main"?2:7,this._remoteStreamStatMap.set(r,s)}}handleSubscribeStart({room:t,remotePublishedUser:e,streamType:r,subscribeState:n}){if(!this.hitTest(t))return;let{userId:s,tinyId:o,role:a}=e,c=new yn({userId:s,tinyId:o,role:a==="anchor"?20:21}),d=Date.now(),u=`${s}_${r}`,l=this._remoteStreamStatMap.get(u);l&&l.subscribeStartTime===0&&(l.subscribeStartTime=d),r==="main"?(e.muteState.hasVideo&&(n.video||n.smallVideo)&&!this._pathMainVideoMap.has(u)&&this._pathMainVideoMap.set(u,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:s,sendSubscribeCMDTime:d}),e.muteState.hasAudio&&n.audio&&!this._pathMainAudioMap.has(u)&&this._pathMainAudioMap.set(u,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:s,sendSubscribeCMDTime:d})):e.muteState.hasAuxiliary&&n.auxiliary&&!this._pathAuxiliaryMap.has(u)&&this._pathAuxiliaryMap.set(u,{sendSubscribeCMDTime:d})}handleSubscribed({room:t,remotePublishedUser:e,streamType:r}){if(this.hitTest(t)){let n=`${e.userId}_${r}`,s=this._remoteStreamStatMap.get(n);s&&s.subscribedTime===0&&(s.subscribedTime=Date.now())}}handlePlayStart({track:t}){if(!si(t)||!this.hitTest(t.room))return;let e=`${t.userId}_${t.streamType}`,r=this._remoteStreamStatMap.get(e);(r==null?void 0:r.playStreamTime)===0&&(r.playStreamTime=Date.now())}handleVideoLoadedData({track:t}){if(!si(t)||!this.hitTest(t.room))return;let e=`${t.userId}_${t.streamType}`,r=this._pathMainVideoMap.get(e);r&&r.statsToReport.uint64_combine_first_frame_time===0&&(r.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(t){let e=`${t.userId}_${t.streamType}`,r=Date.now(),n=this._pathMainVideoMap.get(e),s=this._remoteStreamStatMap.get(e);if(n&&(n.statsToReport.uint64_render_first_frame_time===0&&(n.statsToReport.uint64_render_first_frame_time=r),s)){let{statsToReport:a,playStreamTime:c,subscribedTime:d}=s;a.uint32_video_render_first===0&&c-d<=100&&(a.uint32_video_render_first=r-n.sendSubscribeCMDTime)}let o=this._pathAuxiliaryMap.get(e);if(o&&s){let{statsToReport:a,playStreamTime:c,subscribedTime:d}=s;a.uint32_video_render_first===0&&c-d<=100&&(a.uint32_video_render_first=r-o.sendSubscribeCMDTime)}}handleAudioPlaying(t){let e=`${t.userId}_${t.streamType}`,r=this._pathMainAudioMap.get(e);r&&r.statsToReport.uint64_play_first_frame_time===0&&(r.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(t){this.hitTest(t.room)&&(this._networkQuality.totalUplinkLoss+=t.uplink.loss,this._networkQuality.totalUplinkRTT+=t.uplink.rtt,this._networkQuality.count++,t.downlinks.forEach(({rtt:e,loss:r,userId:n,videoDelay:s,audioDelay:o})=>{let a=this._networkQuality.totalDownlinkRTTAndLossMap.get(n);if(a)a.totalRTT+=e,a.totalLoss+=r,s&&(a.totalVideoDelay=(a.totalVideoDelay||0)+s,a.videoDelayCount=(a.videoDelayCount||0)+1),o&&(a.totalAudioDelay=(a.totalAudioDelay||0)+o,a.audioDelayCount=(a.audioDelayCount||0)+1),a.count++;else{let c,d,u,l;s&&(d=s,u=1),o&&(c=o,l=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(n,{totalRTT:e,totalLoss:r,count:1,totalAudioDelay:c,totalVideoDelay:d,audioDelayCount:l,videoDelayCount:u})}}))}handleHeartbeatStats(t){if(this.hitTest(t.room)){let{msg_up_stream_info:e,msg_down_stream_info:r}=t.report;if(e.msg_video_status[0]){let{uint32_video_codec_bitrate:n,uint32_video_enc_fps:s,uint32_video_width:o,uint32_video_height:a}=e.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=n,this._localStreamStat.totalVideoFPS+=s,this._localStreamStat.totalVideoWidth+=o,this._localStreamStat.totalVideoHeight+=a,this._localStreamStat.videoCount++}if(e.msg_audio_status){let{uint32_audio_level:n}=e.msg_audio_status;Math.floor(n/Ai*100)>0&&(this._localStreamStat.totalAudioLevel+=n/Ai,this._localStreamStat.audioLevelCount++)}r.forEach(n=>{let{msg_user_info:s,msg_audio_status:o,msg_video_status:a}=n,c=s.str_identifier,d=this._room.remotePublishedUserMap.get(c);if(a.forEach(u=>{let l=u.uint32_video_stream_type===2,h=u.uint32_video_stream_type===7,I=`${c}_${l?"main":"auxiliary"}`,T=this._remoteStreamStatMap.get(I);if(!!T&&(l&&(d==null?void 0:d.remoteVideoTrack.isSubscribed)||h&&(d==null?void 0:d.remoteAuxiliaryTrack))){T.totalVideoFPS+=u.uint32_video_receive_fps,T.totalVideoBitrate+=u.uint32_video_codec_bitrate,T.videoCount++,T.statsToReport.uint32_video_width===0&&(T.statsToReport.uint32_video_width=u.uint32_video_width),T.statsToReport.uint32_video_height===0&&(T.statsToReport.uint32_video_height=u.uint32_video_height);let N=l?d.remoteVideoTrack:d.remoteAuxiliaryTrack;N.stat.jitterBufferDelay&&(T.videoJitterBufferDelay=N.stat.jitterBufferDelay),N.stat.framesReceived&&(T.statsToReport.uint32_video_consume_render_rate=Math.floor(N.stat.framesDecoded/N.stat.framesReceived*Ln(10,6)))}}),o){let u=`${c}_${"main"}`,l=this._remoteStreamStatMap.get(u);this._remoteStreamStatMap.has(u)&&l&&(d==null?void 0:d.remoteAudioTrack.isSubscribed)&&(l.totalAudioBitrate+=o.uint32_audio_codec_bitrate,l.audioCount++,d.remoteAudioTrack.stat.jitterBufferDelay&&(l.audioJitterBufferDelay=d.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(o.uint32_audio_level/Ai*100)>0&&(l.totalAudioLevel+=o.uint32_audio_level/Ai,l.audioLevelCount++))}})}}handlePublishStart({room:t}){this.hitTest(t)&&this._localStreamStat.publishStartTime===0&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart({track:t}){t.mediaType===1&&this._pathJoinRoom.uint64_init_audio_start_time===0&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),t.mediaType===4&&this._pathJoinRoom.uint64_init_camera_start_time===0&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess({track:t}){t.mediaType===1&&this._pathJoinRoom.uint64_init_audio_end_time===0&&(this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),t.mediaType===4&&this._pathJoinRoom.uint64_init_camera_end_time===0&&(this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed({track:t,error:e}){let r={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5},n=e instanceof L?e.getExtraCode()||e.getCode():r[e.name]||v.UNKNOWN;t.mediaType===1&&this._pathJoinRoom.uint64_init_audio_end_time===0&&(this._pathJoinRoom.int32_init_audio_ret=n,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),t.mediaType===4&&this._pathJoinRoom.uint64_init_camera_end_time===0&&(this._pathJoinRoom.int32_init_camera_ret=n,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleAPISuccessRate({room:t,apiName:e,error:r,cost:n}){if(!this.hitTest(t))return;let s=xl[e],o={uint32_function_request_type:s,uint32_avg_value:0,uint32_max_value:0,uint32_request_count:1,uint32_success_count:0,msg_error_code:[]};if(r){let c=v.UNKNOWN;r instanceof L&&(c=r.extraCode||r.code),Ee.uploadEvent({log:`stat-${e}-failed-${c}`,userId:this._room.userId,error:r});let d={int32_error_code:c,error_count:1};o.msg_error_code.push(d)}else de(n)&&(o.uint32_avg_value=n,o.uint32_max_value=n,o.uint32_success_count=1);let a=this._apiSuccessRateMap.get(s);a?(a.uint32_success_count+o.uint32_success_count>0&&(a.uint32_avg_value=(a.uint32_avg_value*a.uint32_success_count+o.uint32_avg_value)/(a.uint32_success_count+o.uint32_success_count)),a.uint32_max_value=Math.max(a.uint32_max_value,o.uint32_max_value),a.uint32_request_count+=1,a.uint32_success_count=a.uint32_success_count+o.uint32_success_count,o.msg_error_code.forEach(c=>{let d=a.msg_error_code.find(u=>u.int32_error_code===c.int32_error_code);d?d.error_count+=1:a.msg_error_code.push(c)})):this._apiSuccessRateMap.set(s,o)}hasVideoFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&Dr)>=0}hasAudioFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&Or)>=0}hasAuxFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&Gn)>=0}hitTest(t){return t===this._room}checkStorage(){return E(this,null,function*(){try{let t=sr.getItem(this._storageKey);t&&(yield this.upload(t),sr.deleteItem(this._storageKey))}catch(t){this._log.warn(t)}})}setStorage(){this.prepareReport();let t=this.getReportData();t.msg_path_enter_room.uint64_start_time!==0&&sr.setItem(this._storageKey,t)}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._localStreamStat.videoCount>0){this._localStreamStat.statsToReport.uint32_video_big_capture_fps=Math.floor(this._localStreamStat.totalVideoFPS/this._localStreamStat.videoCount),this._localStreamStat.statsToReport.uint32_video_big_bitrate=Math.floor(this._localStreamStat.totalVideoBitrate/this._localStreamStat.videoCount);let t=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),e=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=t<<16|e}this._localStreamStat.audioLevelCount>0&&(this._localStreamStat.statsToReport.uint32_audio_capture_db=Math.floor(this._localStreamStat.totalAudioLevel/this._localStreamStat.audioLevelCount*100)),this._remoteStreamStatMap.forEach((t,e)=>{let{userId:r}=t,n=this._networkQuality.totalDownlinkRTTAndLossMap.get(r);if(n){let{totalLoss:u,count:l,audioDelayCount:h,videoDelayCount:I,totalAudioDelay:T,totalVideoDelay:N}=n;t.statsToReport.uint32_avg_down_loss=Math.floor(u/l),h&&T&&(t.statsToReport.uint32_audio_network_p2p_delay=Math.floor(T/h),t.audioJitterBufferDelay&&(t.statsToReport.uint32_p2p_delay=Math.floor(t.statsToReport.uint32_audio_network_p2p_delay+t.audioJitterBufferDelay))),I&&N&&(t.statsToReport.uint32_video_network_p2p_delay=Math.floor(N/I))}t.videoCount>0&&(t.statsToReport.uint32_video_avg_fps=Math.floor(t.totalVideoFPS/t.videoCount),t.statsToReport.uint32_video_avg_bitrate=Math.floor(t.totalVideoBitrate/t.videoCount)),t.audioCount>0&&(t.statsToReport.uint32_audio_recv_bitrate=t.statsToReport.uint32_audio_bitrate=Math.floor(t.totalAudioBitrate/t.audioCount)),t.audioLevelCount>0&&(t.statsToReport.uint32_audio_play_db=Math.floor(t.totalAudioLevel/t.audioLevelCount*100));let{callDurationCalculator:s}=this._room;s&&(t.statsToReport.uint32_audio_play_time=s.getDuration(e,m.AUDIO),t.statsToReport.uint32_video_play_time=s.getDuration(e,m.VIDEO)),t.statsToReport.uint32_video_render_first=Math.min(t.statsToReport.uint32_video_render_first,$i);let{badCaseDetector:o}=this._room,{dataFreeze:a,count:c}=o.getDataFreezeDuration(e),{renderFreeze:d}=o.getRenderFreezeDuration(e);t.statsToReport.uint32_video_block_count=c,t.statsToReport.uint32_video_block_time=Math.min(a,t.statsToReport.uint32_video_play_time),t.statsToReport.uint32_video_external_block_time=Math.min(d,t.statsToReport.uint32_video_play_time),o.isBlackStream(e)&&t.statsToReport.uint32_video_avg_fps===0?t.statsToReport.uint32_video_black_screen_subjective=1:t.statsToReport.uint32_video_black_screen_subjective=0,(t.subscribeStartTime===0||t.subscribeStartTime-t.streamAddedTime>100||t.playStreamTime===0)&&(this._pathMainAudioMap.delete(e),this._pathMainVideoMap.delete(e),t.statsToReport.uint32_video_render_first=0)}),this._pathMainAudioMap.forEach((t,e)=>{if(!this.hasAudioFlag(t.userId)){this._pathMainAudioMap.delete(e);return}t.statsToReport.uint64_play_first_frame_time-t.statsToReport.uint64_start_enter_time>$i&&(t.statsToReport.uint64_play_first_frame_time=t.statsToReport.uint64_start_enter_time+$i)}),this._pathMainVideoMap.forEach((t,e)=>{if(!this.hasVideoFlag(t.userId)){this._pathMainVideoMap.delete(e);return}t.statsToReport.uint64_render_first_frame_time-t.statsToReport.uint64_start_enter_time>$i&&(t.statsToReport.uint64_render_first_frame_time=t.statsToReport.uint64_start_enter_time+$i)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>$i&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+$i)}getReportData(){return{uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new yn({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:Zr(this._signalInfo.relayIp),uint32_client_ip:Zr(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*2147483648),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._remoteStreamStatMap.values()].map(e=>e.statsToReport),str_room_name:String(this._room.roomId||0),msg_path_recv_audio:[...this._pathMainAudioMap.values()].map(e=>e.statsToReport),uint32_info_client_ip:Zr(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,msg_function_request_stats:[...this._apiSuccessRateMap.values()]}}report(){return E(this,null,function*(){try{this.prepareReport();let t=this.getReportData();yield this.upload(t),sr.deleteItem(this._storageKey),this.initData()}catch(t){this._log.warn(t)}})}upload(t){return E(this,null,function*(){if(Rt||t.msg_path_enter_room.uint64_start_time===0||[Ro,Dd,Od].findIndex(s=>s===location.host)>=0)return;let e=Number(this._room.sdkAppId),r=Ci(e,Xi.KEY_POINT),n=yield ai({url:r,body:JSON.stringify(t)});if(n.data!=="ok")throw`key point upload failed: ${n.data}`})}setConnectionType(t){this.connectionType=t,this._basicInfo.uint32_connection_type=t}};F([An({settings:{timeout:500,retries:3}})],js.prototype,"upload",1);var $i=5e3,F_={msg_user_info:null,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,uint32_video_consume_render_rate:0},yn=class{constructor(t){this.str_identifier=String(t.userId),this.str_tinyid=String(t.tinyId||0),this.uint32_role=t.role}},xl=(g=>(g[g.enterRoom=50001]="enterRoom",g[g.exitRoom=50002]="exitRoom",g[g.switchRole=50003]="switchRole",g[g.destroy=50004]="destroy",g[g.startLocalAudio=50005]="startLocalAudio",g[g.updateLocalAudio=50006]="updateLocalAudio",g[g.stopLocalAudio=50007]="stopLocalAudio",g[g.startLocalVideo=50008]="startLocalVideo",g[g.updateLocalVideo=50009]="updateLocalVideo",g[g.stopLocalVideo=50010]="stopLocalVideo",g[g.startScreenShare=50011]="startScreenShare",g[g.updateScreenShare=50012]="updateScreenShare",g[g.stopScreenShare=50013]="stopScreenShare",g[g.enableAudioVolumeEvaluation=50014]="enableAudioVolumeEvaluation",g[g.startRemoteVideo=50015]="startRemoteVideo",g[g.updateRemoteVideo=50016]="updateRemoteVideo",g[g.stopRemoteVideo=50017]="stopRemoteVideo",g[g.muteRemoteAudio=50018]="muteRemoteAudio",g[g.setRemoteAudioVolume=50019]="setRemoteAudioVolume",g[g.startMixTranscode=50020]="startMixTranscode",g[g.stopMixTranscode=50021]="stopMixTranscode",g[g.startPublishCDNStream=50022]="startPublishCDNStream",g[g.stopPublishCDNStream=50023]="stopPublishCDNStream",g[g.PeerConnectionConnect=50024]="PeerConnectionConnect",g[g.PeerConnectionReconnect=50025]="PeerConnectionReconnect",g[g.WebsocketConnect=50026]="WebsocketConnect",g[g.WebsocketReconnect=50027]="WebsocketReconnect",g[g.schedule=50028]="schedule",g[g.SPCConnect=50029]="SPCConnect",g[g.SPCReconnect=50030]="SPCReconnect",g))(xl||{}),Ul=js;var YP=_(f(),1);var BP=_(f(),1);var Pc=class{constructor(){p(this,"_startTime");p(this,"_endTime");this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=q())}stop(){this._endTime===0&&(this._endTime=q())}getDuration(){return this._endTime===0?q()-this._startTime:this._endTime-this._startTime}get endTime(){return this._endTime}},gr=Pc;var Mc=class{constructor(t){p(this,"_room",null);p(this,"_durationMap");p(this,"_eventMap",new Map);this._room=t.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(S.SUBSCRIBE_SUCCESS,this.handleSubscribed).set(S.UNSUBSCRIBE_SUCCESS,this.handleStreamStopped).set(S.REMOTE_PUBLISH_STATE_CHANGED,({room:t,prevMuteState:e,muteState:r})=>{var o;let{userId:n}=r;if(!this.hitTest(t))return;e.hasAudio&&!r.hasAudio&&this.stopDurationItem(`${n}_${"main"}`,m.AUDIO),e.hasVideo&&!r.hasVideo&&this.stopDurationItem(`${n}_${"main"}`,m.VIDEO),e.hasAuxiliary&&!r.hasAuxiliary&&this.stopDurationItem(`${n}_${"auxiliary"}`,m.VIDEO);let s=(o=this._room)==null?void 0:o.remotePublishedUserMap.get(n);!s||(!e.hasAudio&&r.hasAudio&&s.remoteAudioTrack.isSubscribed&&this.addDuractionItem(n,m.AUDIO,"main"),!e.hasVideo&&r.hasVideo&&s.remoteVideoTrack.isSubscribed&&this.addDuractionItem(n,m.VIDEO,"main"),!e.hasAuxiliary&&r.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(n,m.VIDEO,"auxiliary"))}),this._eventMap.forEach((t,e)=>C.on(e,t,this))}uninstallEvents(){this._eventMap.forEach((t,e)=>C.off(e,t,this)),this._eventMap.clear()}handleSubscribed({room:t,streamType:e,remotePublishedUser:r}){if(!this.hitTest(t))return;let{userId:n}=r,s=`${n}_${e}`;if(r.muteState.hasAudio&&e==="main")if(r.remoteAudioTrack.isSubscribed){let o=new gr,a=this._durationMap.get(s);a?this.isRecording(a.audio)||a.audio.push(o):this._durationMap.set(s,{userId:n,type:e,audio:[o],video:[]})}else this.stopDurationItem(s,m.AUDIO);if(r.muteState.hasVideo||r.muteState.hasAuxiliary)if(r.remoteVideoTrack.isSubscribed||r.remoteAuxiliaryTrack.isSubscribed){let o=new gr,a=this._durationMap.get(s);a?this.isRecording(a.video)||a.video.push(o):this._durationMap.set(s,{userId:n,type:e,audio:[],video:[o]})}else this.stopDurationItem(s,m.VIDEO)}handleStreamStopped({room:t,streamType:e,remotePublishedUser:r}){if(!this.hitTest(t))return;let{userId:n}=r,s=`${n}_${e}`;this.stopDurationItem(s,m.AUDIO),this.stopDurationItem(s,m.VIDEO)}isRecording(t){return t.findIndex(e=>e.endTime===0)>=0}addDuractionItem(t,e,r){let n=`${t}_${r}`,s=new gr,o=this._durationMap.get(n);o?this.isRecording(o[e])||o[e].push(s):this._durationMap.set(n,{userId:t,type:r,audio:e===m.AUDIO?[s]:[],video:e===m.AUDIO?[]:[s]})}stopDurationItem(t,e){if(this._durationMap.has(t)){let n=this._durationMap.get(t)[e].find(s=>s.endTime===0);n&&n.stop()}}hitTest(t){return this._room===t}getDuration(t,e){return this._durationMap.has(t)?this._durationMap.get(t)[e].reduce((n,s)=>n+s.getDuration(),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},Vl=Mc;var cM=_(f(),1);var Lc=class{constructor(t){p(this,"_room");p(this,"_renderFreezeMap",new Map);p(this,"_isVideoPlayingEventFiredMap",new Map);p(this,"_dataFreezeMap",new Map);p(this,"_monitorFreezeData",new Map);p(this,"_eventMap",new Map);this._room=t.room,this.installEvents()}installEvents(){this._eventMap.set(S.LEAVE_SUCCESS,({room:t})=>{this.hitTest(t)&&this.stop()}).set(S.PLAY_TRACK_START,this.onPlayTrackStart).set(S.UNSUBSCRIBE_SUCCESS,({room:t,streamType:e,remotePublishedUser:r})=>{if(!this.hitTest(t))return;let{userId:n}=r,s=`${n}_${e}`;this.stopDataFreeze({key:s,userId:n,type:e})}).set(S.REMOTE_PUBLISH_STATE_CHANGED,({room:t,prevMuteState:e,muteState:r})=>{if(!this.hitTest(t))return;let{userId:n}=r;if(e.hasVideo&&!r.hasVideo){let s="main",o=`${r.userId}_${s}`;this.stopDataFreeze({key:o,userId:n,type:s})}if(e.hasAuxiliary&&!r.hasAuxiliary){let s="auxiliary",o=`${r.userId}_${s}`;this.stopDataFreeze({key:o,userId:n,type:s})}}).set(S.PLAYER_STATE_CHANGED,({track:t,state:e,reason:r,type:n})=>{if(!(!si(t)||!this.hitTest(t.room)||n!==m.VIDEO)){if(e==="PLAYING"){let s=`${t.userId}_${t.streamType}`;this._isVideoPlayingEventFiredMap.set(s,!0)}r===m.MUTE?this.onVideoTrackMuted(t):r===m.UNMUTE&&this.onVideoTrackUnmuted(t)}}).set(S.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach((t,e)=>C.on(e,t,this))}uninstallEvents(){this._eventMap.forEach((t,e)=>C.off(e,t,this)),this._eventMap.clear()}stop(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}onVideoTrackMuted(t){if(!t.isSubscribed)return;let{userId:e,streamType:r}=t,n=`${e}_${r}`,s=this._dataFreezeMap.get(n),o=new gr;s?s.durationItemList.push(o):this._dataFreezeMap.set(n,{userId:e,type:r,durationItemList:[o],isFreezing(){let a=this.durationItemList[this.durationItemList.length-1];return a&&a.endTime===0}})}onVideoTrackUnmuted(t){if(!t.isSubscribed)return;let{userId:e,streamType:r}=t,n=`${e}_${r}`;this.stopDataFreeze({key:n,userId:e,type:r})}onHearBeatReport({room:t,report:e}){!this.hitTest(t)||e.msg_down_stream_info.forEach(r=>{let n=this._room.remotePublishedUserMap.get(r.msg_user_info.str_identifier);if(!n)return;let{userId:s,muteState:o}=n;r.msg_video_status.forEach(a=>{a.uint32_video_stream_type===2&&o.hasVideo&&!o.videoMuted&&n.remoteVideoTrack.isSubscribed&&this.handleRenderFreeze({userId:s,fps:a.uint32_video_dec_fps,type:"main"}),a.uint32_video_stream_type===7&&o.hasAuxiliary&&n.remoteAuxiliaryTrack.isSubscribed&&this.handleRenderFreeze({userId:s,fps:a.uint32_video_dec_fps,type:"auxiliary"})})})}stopDataFreeze({key:t,userId:e,type:r}){let n=this._dataFreezeMap.get(t);if(!n||!n.isFreezing())return;let s=n.durationItemList[n.durationItemList.length-1];s.stop();let o=s.getDuration();o>Do?this._monitorFreezeData.set(t,{userId:e,type:r,duration:o}):n.durationItemList.pop()}getTotalDuration(t){return t.reduce((e,r)=>{let n=r.getDuration();return e+Math.min(n,5e3)},0)}handleRenderFreeze(n){return E(this,arguments,function*({userId:t,fps:e,type:r}){let s=`${t}_${r}`,o=this._renderFreezeMap.get(s);if(e<=2){let a=q();o&&!o.isFreeze&&(o.freezeTimeline.push({startTime:a,endTime:0}),o.isFreeze=!0),o||this._renderFreezeMap.set(s,{userId:t,type:r,isFreeze:!0,freezeTimeline:[{startTime:a,endTime:0}],renderFreezeTotal:0})}else if(o&&o.isFreeze){o.isFreeze=!1;let a=o.freezeTimeline.pop();if(a){a.endTime=q();let c=a.endTime-a.startTime;o.freezeTimeline.push(a),o.renderFreezeTotal+=Math.min(5e3,c)}}})}onPlayTrackStart({track:t}){if(!si(t)||!this.hitTest(t.room)||t.kind!==m.VIDEO||t.hasFlag)return;let e=`${t.userId}_${t.streamType}`;this._isVideoPlayingEventFiredMap.has(e)||this._isVideoPlayingEventFiredMap.set(e,!1)}getDataFreezeDuration(t){let e={dataFreeze:0,count:0},r=this._dataFreezeMap.get(t);if(r){if(r.isFreezing()){let n=r.durationItemList[r.durationItemList.length-1];n.stop(),n.getDuration()<Do&&r.durationItemList.pop()}e.dataFreeze=this.getTotalDuration(r.durationItemList),e.count=r.durationItemList.length}return e}getRenderFreezeDuration(t){let e=this._renderFreezeMap.get(t),r=0,n=0;if(e)if(!e.isFreeze)r=e.renderFreezeTotal;else{let s=q(),o=e.freezeTimeline[e.freezeTimeline.length-1],a=s-o.startTime;r=e.renderFreezeTotal+Math.min(a,5e3),n=e.freezeTimeline.length}return{renderFreeze:r,count:n}}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(t){return this._isVideoPlayingEventFiredMap.has(t)?!this._isVideoPlayingEventFiredMap.get(t):!1}resetMonitor(){this._monitorFreezeData.clear()}hitTest(t){return t===this._room}destroy(){this.uninstallEvents()}},wl=Lc;var CM=_(f(),1);var $l=_(kc(),1);var xc=class{constructor(t){p(this,"_room");p(this,"_log");p(this,"_config",null);p(this,"_data");p(this,"_remoteVideoTrackMap",new Map);this._room=t,this._log=M.createLogger({id:"mix",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this.installEvents()}get isPresetLayoutMode(){return this._config&&this._config.mode===Ii.MODE.PRESET_LAYOUT}get isMixing(){return!!this._data}installEvents(){C.on(S.REMOTE_TRACK_SUBSCRIBED,this.onSubscribed,this),C.on(S.REMOTE_TRACK_UNSUBSCRIBED,this.onUnSubscribed,this),C.on(S.REMOTE_PUBLISH_STATE_CHANGED,this.onRemotePublishedChanged,this)}uninstallEvents(){C.off(S.REMOTE_TRACK_SUBSCRIBED,this.onSubscribed,this),C.off(S.REMOTE_TRACK_UNSUBSCRIBED,this.onUnSubscribed,this),C.off(S.REMOTE_PUBLISH_STATE_CHANGED,this.onRemotePublishedChanged,this)}reset(){this.uninstallEvents(),this._config=null}onSubscribed({track:t}){t.room!==this._room||t.kind!==m.VIDEO||(this._remoteVideoTrackMap.set(`${t.userId}_${t.streamType}`,!1),this.isMixing&&this.hasAvailablePlaceHolder()&&this._config&&this.startMixTranscode(this._config))}onUnSubscribed({track:t}){t.room!==this._room||t.kind!==m.VIDEO||this.handleRemoteTrackUnavailable(`${t.userId}_${t.streamType}`)}onRemotePublishedChanged({room:t,prevMuteState:e,muteState:r}){t===this._room&&(e.hasVideo&&!r.hasVideo&&this.handleRemoteTrackUnavailable(`${r.userId}_${"main"}`),e.hasAuxiliary&&!r.hasAuxiliary&&this.handleRemoteTrackUnavailable(`${r.userId}_${"auxiliary"}`))}handleRemoteTrackUnavailable(t){if(this._remoteVideoTrackMap.has(t)){let e=this._remoteVideoTrackMap.get(t);this._remoteVideoTrackMap.delete(t),this.isMixing&&this.isPresetLayoutMode&&e&&this._config&&this.startMixTranscode(this._config)}}startMixTranscode(t){return E(this,null,function*(){try{this.resetIsUsedFlag(),this._config=t;let e=this.getInputParam(t),r=this.getOutputParam(t),n=this.getOutputSessionId({config:t,roomId:this._room.roomId,userId:this._room.userId});this.isMixing&&this._data&&n!==this._data.outputSessionId&&(this._log.info("startMixTranscode() streamId changed, stop mixing before start"),yield this.doStopMixTranscode()),yield this.doStartMixTranscode({outputSessionId:n,inputParam:e,outputParam:r})}catch(e){throw this.resetIsUsedFlag(),e}})}doStartMixTranscode(n){return E(this,arguments,function*({outputSessionId:t,inputParam:e,outputParam:r}){let s={roomId:String(this._room.roomId),mcuRequestTime:Date.now(),outputSessionId:t,inputParam:e,outputParam:r};this._log.info(`startMixTranscode: ${JSON.stringify(s)}`);let o=yield this._room.sendStartMixTranscode(s),{code:a}=o.data,{message:c}=o.data;if(a!==0)throw a===-102083&&(c=`Please enable relayed-push in ${Fn} and try later, refer to ${Yi}tutorial-26-advanced-publish-cdn-stream.html`),this._log.error(`startMixTranscode failed, errCode: ${a} errMsg: ${c}`),new L({code:v.START_MIX_TRANSCODE_FAILED,message:$({key:w.START_MIX_TRANSCODE_FAILED,data:{message:c},link:{className:"Client",fnName:"startMixTranscode"}})});this._data=s})}reStartMixTranscode(){!this.isMixing||this._config&&this.startMixTranscode(this._config)}stopMixTranscode(){return E(this,null,function*(){if(!this.isMixing)throw new L({code:v.INVALID_OPERATION,message:$({key:w.MIX_TRANSCODE_NOT_STARTED})});yield this.doStopMixTranscode(),this.resetIsUsedFlag()})}doStopMixTranscode(){return E(this,null,function*(){let t={mcuRequestTime:Date.now(),outputSessionId:this._data.outputSessionId,streamType:this._data.outputParam.streamType};this._log.info(`stopMixTranscode: ${JSON.stringify(t)}`);let e=yield this._room.sendStopMixTranscode(t),{code:r,message:n}=e.data;if(r===0)this._data=void 0;else throw this._log.error(`stopMixTranscode failed, errCode: ${r} errMsg: ${n}`),new L({code:v.STOP_MIX_TRANSCODE_FAILED,message:$({key:w.STOP_MIX_TRANSCODE_FAILED,data:{message:n},link:{className:"Client",fnName:"stopMixTranscode"}})})})}getOutputSessionId({config:t,userId:e,roomId:r}){return oe(t.streamId)&&t.streamId.length>0?t.streamId:(0,$l.default)(`${r}_${e}_main`)}getInputParam(t){let e=t.mixUsers.map(r=>({userId:r.userId,roomId:String(r.roomId||this._room.roomId),width:r.width||0,height:r.height||0,locationX:r.locationX||0,locationY:r.locationY||0,zOrder:r.zOrder,streamType:!b(r.streamType)&&r.streamType===Kn?1:0,inputType:r.pureAudio?Ii.STREAM_TYPE.IT_PURE_AUDIO:Ii.STREAM_TYPE.IT_AUDIO_VIDEO,renderMode:r.renderMode||0}));return t.mode===Ii.MODE.PRESET_LAYOUT&&(e.forEach(r=>{if(r.userId===Ii.PLACE_HOLDER.REMOTE){let n=[...this._remoteVideoTrackMap.entries()].find(([,s])=>!s);if(n){let[s]=n,o=s.split("_");r.userId=o.slice(0,o.length-1).join("_"),r.streamType=o.splice(-1)[0]==="auxiliary"?1:0,this._remoteVideoTrackMap.set(s,!0)}}}),e=e.filter(r=>r.userId!==Ii.PLACE_HOLDER.REMOTE)),e}getOutputParam(t){let e=t.streamId||"";return{streamId:e,streamType:e.length>0?1:0,width:b(t.videoWidth)?640:t.videoWidth,height:b(t.videoHeight)?480:t.videoHeight,videoBps:t.videoBitrate||0,fps:t.videoFramerate||15,gop:t.videoGOP||2,audioSampleRate:t.audioSampleRate||48e3,audioBps:t.audioBitrate||64,audioChannels:t.audioChannels||1,backgroundColor:t.backgroundColor||0,backgroundImg:t.backgroundImage||"",extraInfo:"",videoCodec:2,audioCodec:0}}hasAvailablePlaceHolder(){var t,e;return!(!this.isPresetLayoutMode||((t=this._data)==null?void 0:t.inputParam.length)===((e=this._config)==null?void 0:e.mixUsers.length))}resetIsUsedFlag(){this._remoteVideoTrackMap.forEach((t,e)=>{this._remoteVideoTrackMap.set(e,!1)})}},Hl=xc;var VM=_(f(),1),Ys=_(kc(),1);var vn=class{constructor(t){p(this,"_room");p(this,"_publishTencentMainStreamObj",{params:null,streamId:void 0,isPublishing:!1});p(this,"_publishTencentAuxStreamObj",{params:null,streamId:void 0,isPublishing:!1});p(this,"_publishGivenCDNData",null);p(this,"_isPublishingGivenCDN",!1);this._room=t}get _isPublishingTencentCDN(){return this._publishTencentMainStreamObj.isPublishing||this._publishTencentAuxStreamObj.isPublishing}generatePublishCDNStreamId(t,e){if(!t){let r=`${this._room.roomId}_${this._room.userId}_${this.convertStreamType(e)}`;return/^[A-Za-z\d_-]*$/.test(r)||(r=(0,Ys.default)(r)),`${this._room.sdkAppId}_${r}`}return t}convertStreamType(t){return t==="main"?t:"aux"}generatePublishCDNSessionId(t){return(0,Ys.default)(`${this._room.roomId}_${this._room.userId}_${this.convertStreamType(t)}`)}startPublishCDN(t){return E(this,null,function*(){let{streamId:e="",streamType:r="main",appId:n,bizId:s,url:o}=t;yield this.startPublishTencentCDN({streamId:e,streamType:r}),n&&s&&o&&(yield this.startPublishGivenCDN({streamType:r,appId:n,bizId:s,url:o}))})}stopPublishCDN(){return E(this,null,function*(){if(!this._isPublishingTencentCDN)throw new L({code:v.INVALID_OPERATION,message:$({key:w.INVALID_OPERATION_STOP_PUBLISH_CDN})});yield this.stopPublishTencentCDN(),this._isPublishingGivenCDN&&(yield this.stopPublishGivenCDN())})}startPublishTencentCDN(t){return E(this,null,function*(){if(t.streamType==="auxiliary"?(this._publishTencentAuxStreamObj.params=t,this._publishTencentAuxStreamObj.isPublishing=!0):(this._publishTencentMainStreamObj.params=t,this._publishTencentMainStreamObj.isPublishing=!0),!this._room.isJoined)return;let e=this.generatePublishCDNStreamId(t.streamId,t.streamType),r=this.generatePublishCDNSessionId(t.streamType),n=t.streamType==="auxiliary"?1:0,s={requestTime:Date.now(),sessionId:r,streamId:e,streamType:n};yield this.doStartPublishTencentCDN(s,t.streamType)})}doStartPublishTencentCDN(t,e){return E(this,null,function*(){try{M.info(`startPublishTencentCDN: ${JSON.stringify(t)}`);let r=yield this._room.sendStartPublishCDN(t,!0),{code:n}=r.data,{message:s}=r.data;if(n===0)e==="auxiliary"?this._publishTencentAuxStreamObj.streamId=t.streamId:this._publishTencentMainStreamObj.streamId=t.streamId;else throw e==="auxiliary"?this._publishTencentAuxStreamObj.isPublishing=!1:this._publishTencentMainStreamObj.isPublishing=!1,n===-102083&&(s=`Please enable relayed-push in ${Fn} and try later, refer to ${Yi}tutorial-26-advanced-publish-cdn-stream.html`),M.error(`startPublishTencentCDN failed, errCode: ${n}, errMsg: ${s}`),new L({code:v.START_PUBLISH_CDN_FAILED,message:$({key:w.START_PUBLISH_CDN_FAILED,data:{message:s},link:{className:"Client",fnName:"startPublishCDNStream"}})})}catch(r){throw e==="auxiliary"?this._publishTencentAuxStreamObj.isPublishing=!1:this._publishTencentMainStreamObj.isPublishing=!1,r}})}resetPublishTencentParam(t){t==="main"&&(this._publishTencentMainStreamObj={params:null,streamId:void 0,isPublishing:!1}),t==="auxiliary"&&(this._publishTencentAuxStreamObj={params:null,streamId:void 0,isPublishing:!1})}stopPublishTencentCDN(){return E(this,null,function*(){if(!this._room.isJoined){this.resetPublishTencentParam("main"),this.resetPublishTencentParam("auxiliary");return}this._publishTencentMainStreamObj.isPublishing&&(yield this.doStopPublishTencentCDN("main")),this._publishTencentAuxStreamObj.isPublishing&&(yield this.doStopPublishTencentCDN("auxiliary"))})}doStopPublishTencentCDN(t){return E(this,null,function*(){let e={requestTime:Date.now(),sessionId:(0,Ys.default)(`${this._room.roomId}_${this._room.userId}_${this.convertStreamType(t)}`)};M.info(`stopPublishTencentCDN: ${JSON.stringify(e)}`);let r=yield this._room.sendStopPublishCDN(e,!0),{code:n,message:s}=r.data;if(n===0)this.resetPublishTencentParam(t);else if(n===-102069)M.warn("stopPublishTencentCDN failed, can not stopPublishTencentCDN in auto relayed-push mode"),this.resetPublishTencentParam(t);else throw M.error(`stopPublishTencentCDN failed, errCode: ${n} errMsg: ${s}`),new L({code:v.STOP_PUBLISH_CDN_FAILED,message:$({key:w.STOP_PUBLISH_CDN_FAILED,data:{message:s},link:{className:"Client",fnName:"stopPublishCDNStream"}})})})}startPublishGivenCDN(t){return E(this,null,function*(){let e=t.streamType==="main"?this._publishTencentMainStreamObj.streamId:this._publishTencentAuxStreamObj.streamId,r={pushRequestTime:Date.now(),pushAppId:t.appId,pushBizId:t.bizId,pushCdnUrl:t.url,pushStreamType:this.convertStreamType(t.streamType),pushStreamId:e};if(M.info(`startPublishGivenCDN: ${JSON.stringify(r)}`),this._publishGivenCDNData=r,this._isPublishingGivenCDN=!0,!!this._room.isJoined)try{let n=yield this._room.sendStartPublishCDN(r,!1),{code:s,message:o}=n.data;if(s!==0)throw M.error(`startPublishGivenCDN failed, errCode: ${s}, errMsg: ${o}`),this._publishGivenCDNData=null,this._isPublishingGivenCDN=!1,new L({code:v.START_PUBLISH_CDN_FAILED,message:$({key:w.START_PUBLISH_CDN_FAILED,data:{message:o},link:{className:"Client",fnName:"startPublishCDNStream"}})})}catch(n){throw this._publishGivenCDNData=null,this._isPublishingGivenCDN=!1,n}})}stopPublishGivenCDN(){return E(this,null,function*(){if(!this._room.isJoined||!this._publishGivenCDNData){this._publishGivenCDNData=null,this._isPublishingGivenCDN=!1;return}let{pushAppId:t,pushBizId:e,pushCdnUrl:r,pushStreamType:n}=this._publishGivenCDNData,s={pushRequestTime:Date.now(),pushAppId:t,pushBizId:e,pushCdnUrl:r,pushStreamType:n};M.info(`stopPublishGivenCDN: ${JSON.stringify(s)}`);let o=yield this._room.sendStopPublishCDN(s,!1),{code:a,message:c}=o.data;if(a===0)this._publishGivenCDNData=null,this._isPublishingGivenCDN=!1;else throw M.error(`stopPublishGivenCDN failed, errCode: ${a} errMsg: ${c}`),new L({code:v.STOP_PUBLISH_CDN_FAILED,message:$({key:w.STOP_PUBLISH_CDN_FAILED,data:{message:c},link:{className:"Client",fnName:"stopPublishCDNStream"}})})})}handleCDNConfigForJoinData(t){let e=t,r;if(this._publishTencentMainStreamObj.isPublishing||this._publishTencentAuxStreamObj.isPublishing){let n={};oe(e)&&(n=JSON.parse(e)),n.Str_uc_params||(n.Str_uc_params={}),this._publishTencentMainStreamObj.isPublishing&&(this._publishTencentMainStreamObj.streamId?n.Str_uc_params.userdefine_streamid_main=this._publishTencentMainStreamObj.streamId:this._publishTencentMainStreamObj.params&&(n.Str_uc_params.userdefine_streamid_main=this.generatePublishCDNStreamId(this._publishTencentMainStreamObj.params.streamId,"main"))),this._publishTencentAuxStreamObj.isPublishing&&(this._publishTencentAuxStreamObj.streamId?n.Str_uc_params.userdefine_streamid_aux=this._publishTencentAuxStreamObj.streamId:this._publishTencentAuxStreamObj.params&&(n.Str_uc_params.userdefine_streamid_aux=this.generatePublishCDNStreamId(this._publishTencentAuxStreamObj.params.streamId,"auxiliary"))),e=JSON.stringify(n)}if(this._isPublishingGivenCDN&&this._publishGivenCDNData){let{pushAppId:n,pushBizId:s,pushCdnUrl:o,pushStreamType:a,pushStreamId:c}=this._publishGivenCDNData;r={pushRequestTime:Date.now(),pushAppId:n,pushBizId:s,pushCdnUrl:o,pushStreamType:a,pushStreamId:c}}return{bussinessInfo:e,pushUserCdnInfo:r}}reset(){this.resetPublishTencentParam("main"),this.resetPublishTencentParam("auxiliary"),this._publishGivenCDNData=null,this._isPublishingGivenCDN=!1}};var zM=_(f(),1);function Wl(a){return E(this,arguments,function*({userId:i,sdkAppId:t,useStringRoomId:e,roomId:r,userSig:n,version:s,frameWorkType:o}){let c={delta:0,count:[1,1],msg:[]};try{let d=new FormData;d.append("userId",String(i)),d.append("sdkAppId",String(t)),d.append("isStrGroupId",String(e)),d.append("groupId",String(r)),d.append("sdkVersion",s),d.append("userSig",String(n)),d.append("frameWorkType",String(o));let u=q(),l=yield W_(d,c,t);return c.delta=q()-u,l}catch(d){let u=Ve(d)?d[0]:d,l=de(u.code)?u.code:0,h=`get websocket url failed: ${u.message.includes("timeout")?"timeout":u.message}`,I=new L({code:v.SCHEDULE_FAILED,extraCode:l,message:$({key:w.JOIN_ROOM_FAILED,data:{error:h,code:l}})});throw M.error(I),I}})}function Fl(i,t=m.MAIN){let e;return ds(i)?e=t===m.MAIN?Mr.MAIN_OVERSEA:Mr.BACKUP_OVERSEA:e=t===m.MAIN?Mr.MAIN:Mr.BACKUP,`https://${e}/api/v1/config`}function G_(i,t,e){return new Promise((r,n)=>{ai({url:i,body:t,timeout:e.timeout}).then(s=>{s.data.code===0?r(s.data.data):n({code:s.data.code,message:s.data.msg})}).catch(n)})}var Gl=(i,t)=>vt({retryFunction:G_,settings:{retries:3,timeout:0},onError:t,onRetrying:i});function W_(i,t,e){return new Promise((r,n)=>{let s=null;qo([Gl(o=>t.count[0]=o+1,(o,a)=>{t.msg[0]=o.message,s||a()})(Fl(e,m.MAIN),i,{get timeout(){return ir(2+t.count[0])*1e3}}),Gl(o=>t.count[1]=o+1,(o,a)=>{t.msg[1]=o.message,s||a()})(Fl(e,m.BACKUP),i,{get timeout(){return ir(2+t.count[1])*1e3}})]).then(o=>{s=o,r(s)}).catch(n)})}var K_=0;var Xs=class extends he{constructor(e){super("room");this.seq=++K_;this.role="anchor";this.localTracks=new Set;this.enableAutoPlayDialog=!0;this.autoReceiveAudio=!0;this.autoReceiveVideo=!0;this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null};this._log=M.createLogger({id:`r${this.seq}`});this._joinedTimestamp=0;this._isDestroyed=!1;this.useStringRoomId=!!e.useStringRoomId,be(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),be(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),be(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this.keyPointManager=new Ul({room:this,frameWorkType:e.frameWorkType,component:e.component}),this.callDurationCalculator=new Vl({room:this}),this.badCaseDetector=new wl({room:this}),this.mixTranscodeManager=new Hl(this),this.publishCDNManager=new vn(this)}get isMainStreamPublished(){for(let e of this.localTracks)if(e.mediaType&4)return!0;return!1}get isAuxStreamPublished(){for(let e of this.localTracks)if(e.mediaType&2)return!0;return!1}get hasAuxStream(){for(let e of this.remotePublishedUserMap.values())if(e.muteState.hasAuxiliary)return!0;return this.isAuxStreamPublished}getLogger(){return this._log}get isJoined(){return this.state==="joined"}addTrack(e){return E(this,null,function*(){return this.publish(e)})}removeTrack(e){return E(this,null,function*(){return this.unpublish(e)})}replaceTrack(e){return E(this,null,function*(){})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}getRemoteAudioStats(){return E(this,null,function*(){let e={};return this.remotePublishedUserMap.forEach(r=>{e[r.userId]=r.remoteAudioTrack.stat}),e})}getTransportStats(){return E(this,null,function*(){var r;let e={rtt:((r=this.quality)==null?void 0:r.uplinkRTT)||0,downlinksRTT:{}};if(this.quality)for(let n of this.quality.downlinkInfo)e.downlinksRTT[n.userId]=n.rtt;return e})}getRemoteVideoStats(){return E(this,arguments,function*(e="main"){let r={};return this.remotePublishedUserMap.forEach(n=>{let s=e==="auxiliary"?n.remoteAuxiliaryTrack:n.remoteVideoTrack;r[n.userId]=s.stat}),r})}checkDestroy(){if(this._isDestroyed)throw new L({code:v.INVALID_OPERATION,message:$({key:w.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(Le.INVALID_DESTROY),new L({code:v.INVALID_OPERATION,message:$({key:w.INVALID_DESTROY})});this._log.info("destroy room"),this.keyPointManager.destroy(),this.callDurationCalculator.destroy(),this.badCaseDetector.destroy(),this._isDestroyed=!0,C.emit(S.ROOM_DESTROY,{room:this})}startMixTranscode(e){return this.mixTranscodeManager.startMixTranscode(e)}stopMixTranscode(){return this.mixTranscodeManager.stopMixTranscode()}startPublishCDNStream(){return E(this,arguments,function*(e={}){if(this._log.info(`startPublishCDNStream with params: ${JSON.stringify(e)}; isJoined: ${this.isJoined}; hasMainStream: ${this.isMainStreamPublished}; hasAuxStream: ${!!this.isAuxStreamPublished};`),this.isJoined){if(e.streamType==="main"&&!this.isMainStreamPublished)throw new L({code:v.INVALID_OPERATION,message:$({key:w.INVALID_OPERATION_START_PUBLISH_CDN})});if(e.streamType==="auxiliary"&&!this.isAuxStreamPublished)throw new L({code:v.INVALID_OPERATION,message:$({key:w.INVALID_OPERATION_START_PUBLISH_CDN})})}yield this.publishCDNManager.startPublishCDN(e)})}stopPublishCDNStream(){return this.publishCDNManager.stopPublishCDN()}schedule(e,r,n){return E(this,null,function*(){var o,a;let s=q();try{let c=yield Wl({userId:this.userId,sdkAppId:this.sdkAppId,roomId:e,useStringRoomId:this.useStringRoomId,version:n,userSig:this.userSig,frameWorkType:r});this._log.info(`schedule: ${JSON.stringify(c)}`),this.scheduleResult=B(B({},this.scheduleResult),c),de((o=c.config)==null?void 0:o.retryCount)&&wd(c.config.retryCount),oe((a=c.config)==null?void 0:a.loggerDomain)&&Hn(c.config.loggerDomain),C.emit(S.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult}),C.emit(S.API_SUCCESS_RATE,{room:this,apiName:"schedule",cost:q()-s})}catch(c){throw C.emit(S.API_SUCCESS_RATE,{room:this,apiName:"schedule",error:c}),c}})}};var HL=_(f(),1);var _i=new WeakMap,Ot=new WeakMap;function Nn(){return function(i,t,e){let r=e.value,n=({fn:s,args:o,context:a,resolve:c,reject:d})=>{s.apply(a,o).then(c,d)};return e.value=function(...s){return new Promise((a,c)=>{if(_i.has(this)){let d=_i.get(this),{length:u}=d;d.push({fn:r,args:s,context:this,resolve:a,reject:c}),u===0&&n({fn:r,args:s,context:this,resolve:a,reject:c})}else _i.set(this,[{fn:r,args:s,context:this,resolve:a,reject:c}]),n({fn:r,args:s,context:this,resolve:a,reject:c})}).finally(()=>{let a=_i.get(this);a&&(a.shift(),a[0]&&n(B({},a[0])))})},e}}function Kl(i){return function(t,e,r){let n=r.value;return r.value=function(...s){let o=_i.get(this);if(o){let a=o.filter((c,d)=>{if(d===0)return!0;let u=!0;return c.args.forEach(l=>{s.find(h=>h===l)||(u=!1)}),u?(c.reject(new L({code:v.API_CALL_ABORTED,message:i})),!1):!0});_i.set(this,a)}return n.apply(this,s)},r}}function jl(i){return function(t,e,r){let n=r.value;return r.value=function(...s){var a,c;let o=[];return(a=_i.get(this))==null||a.forEach(d=>o.push(d)),(c=Ot.get(this))==null||c.forEach(d=>d.forEach(u=>o.push(u))),o.forEach(d=>{d.reject(new L({code:v.API_CALL_ABORTED,message:i}))}),_i.delete(this),Ot.delete(this),n.apply(this,s)},r}}function Uc(i){return function(t,e,r){let n=r.value,s=a=>de(i)?a[i]:i(...a),o=({fn:a,args:c,context:d,resolve:u,reject:l})=>{a.apply(d,c).then(u,l).finally(()=>{if(Ot.has(d)&&Ot.get(d).has(s(c))){let h=Ot.get(d).get(s(c));h&&(h.shift(),h[0]&&o(B({},h[0])))}})};return r.value=function(...a){return new Promise((c,d)=>{if(Ot.has(this))if(Ot.get(this).has(s(a))){let u=Ot.get(this).get(s(a));if(u){let{length:l}=u;u.push({fn:n,args:a,context:this,resolve:c,reject:d}),l===0&&o({fn:n,args:a,context:this,resolve:c,reject:d})}}else Ot.get(this).set(s(a),[{fn:n,args:a,context:this,resolve:c,reject:d}]),o({fn:n,args:a,context:this,resolve:c,reject:d});else{let u=new Map;u.set(s(a),[{fn:n,args:a,context:this,resolve:c,reject:d}]),Ot.set(this,u),o({fn:n,args:a,context:this,resolve:c,reject:d})}})},r}}var WL=_(f(),1),Yl=_(nt(),1);var Jl=Symbol("instance"),bn=Symbol("abortCtrl"),Hi=Symbol("cacheResult"),Vc=class{constructor(t,e,r){p(this,"oldState");p(this,"newState");p(this,"action");p(this,"error");this.oldState=t,this.newState=e,this.action=r}toString(){return`${this.action}ing`}},Dn=class extends Error{constructor(e,r,n){super(r);p(this,"state");p(this,"message");p(this,"cause");this.state=e,this.message=r,this.cause=n}},On=new Map,j_=Object.getPrototypeOf((()=>E(void 0,null,function*(){}))()).constructor;function wc(i,t,e={}){return(r,n,s)=>{let o=e.action||n;if(!e.context){let c=On.get(r)||[];On.has(r)||On.set(r,c),c.push({from:i,to:t,action:o})}let a=s.value;s.value=function(...c){return E(this,null,function*(){var I;let d=this;if(e.context&&(d=et.get(typeof e.context=="function"?e.context.call(this,...c):e.context)),d.state===t)return d[Hi];let u=null;if(Array.isArray(i)?i.length==0?d[bn]&&(d[bn].aborted=!0):(typeof d.state!="string"||!i.includes(d.state))&&(u=new Dn(d._state,`${d.name} ${o} to ${t} failed: current state ${d._state} not in from config`)):i!==d.state&&(u=new Dn(d._state,`${d.name} ${o} to ${t} failed: current state ${d._state} not from ${i}`)),u)if(e.fail)e.fail.call(this,u);else{if(e.ignoreError)return u;throw u}let l=d.state;zs.call(d,new Vc(l,t,o));let h={aborted:!1};d[bn]=h;try{let T=a.apply(this,c);return T instanceof j_?d[Hi]=yield T:d[Hi]=T,h.aborted||(d[bn]=void 0,zs.call(d,t),(I=e.success)==null||I.call(this,d[Hi])),d[Hi]}catch(T){let N=T instanceof Error?T.message:String(T);if(zs.call(d,l,N),e.fail)e.fail.call(this,new Dn(d._state,`action '${o}' failed :${N}`,T instanceof Error?T:new Error(N)));else{if(e.ignoreError)return T;throw T}}})}}}var J_=(()=>typeof window!="undefined"&&window.__AFSM__?(e,r)=>{window.dispatchEvent(new CustomEvent(e,{detail:r}))}:typeof importScripts!="undefined"?(e,r)=>{postMessage({type:e,payload:r})}:()=>{})();function zs(i,t){let e=this._state;this._state=i;let r=i.toString();i&&this.emit(r,e),this.emit(et.STATECHANGED,i,e,t),this.updateDevTools({value:i,old:e,err:t})}var Y_,X_,Ze=class extends Yl.default{constructor(e,r,n){super();p(this,"name");p(this,"groupName");p(this,"_state",Ze.INIT);p(this,Y_);p(this,X_);this.name=e,this.groupName=r,e||(e=Date.now().toString(36)),n?Object.setPrototypeOf(this,n):n=Object.getPrototypeOf(this),r||(this.groupName=this.constructor.name);let s=n[Jl];s?this.name=s.name+"-"+s.count++:n[Jl]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),r=On.get(e)||[],n=new Set,s=[],o=[],a=new Set,c=Object.getPrototypeOf(e);On.has(c)&&(c.stateDiagram.forEach(u=>n.add(u)),c.allStates.forEach(u=>a.add(u))),r.forEach(({from:u,to:l,action:h})=>{typeof u=="string"?s.push({from:u,to:l,action:h}):u.length?u.forEach(I=>{s.push({from:I,to:l,action:h})}):o.push({to:l,action:h})}),s.forEach(({from:u,to:l,action:h})=>{a.add(u),a.add(l),a.add(h+"ing"),n.add(`${u} --> ${h}ing : ${h}`),n.add(`${h}ing --> ${l} : ${h} \u{1F7E2}`),n.add(`${h}ing --> ${u} : ${h} \u{1F534}`)}),o.forEach(({to:u,action:l})=>{n.add(`${l}ing --> ${u} : ${l} \u{1F7E2}`),a.forEach(h=>{h!==u&&n.add(`${h} --> ${l}ing : ${l}`)})});let d=[...n];return Object.defineProperty(this,"stateDiagram",{value:d}),d}static get(e){let r;return typeof e=="string"?(r=Ze.instances.get(e),r||Ze.instances.set(e,r=new Ze(e,void 0,Object.create(Ze.prototype)))):(r=Ze.instances2.get(e),r||Ze.instances2.set(e,r=new Ze(e.constructor.name,void 0,Object.create(Ze.prototype)))),r}static getState(e){var r;return(r=Ze.get(e))==null?void 0:r.state}updateDevTools(e={}){J_(Ze.UPDATEAFSM,B({name:this.name,group:this.groupName},e))}get state(){return this._state}set state(e){zs.call(this,e)}},et=Ze;Y_=Hi,X_=bn,p(et,"STATECHANGED","stateChanged"),p(et,"UPDATEAFSM","updateAFSM"),p(et,"INIT","[*]"),p(et,"ON","on"),p(et,"OFF","off"),p(et,"instances",new Map),p(et,"instances2",new WeakMap);var fk=_(f()),ep=_(nt());var qL=_(f());var Bc=_(Ic()),Xl=i=>{let t=Re(i),e={audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0};return t.media.forEach((r,n)=>{var s;if(r.ssrcs&&!b(r.ssrcs[0].id)){let o=Number(r.ssrcs[0].id),a=Number((s=r.ssrcs.filter(c=>c.attribute==="cname")[1])==null?void 0:s.id);switch(n){case 0:e.audioSsrc=o;break;case 1:e.bigVideoSsrc=o,e.bigVideoRtxSsrc=a;break;case 2:e.smallVideoSsrc=o,e.smallVideoRtxSsrc=a;break;case 3:e.auxVideoSsrc=o,e.auxVideoRtxSsrc=a;break}}}),e},zl=(i,t)=>{var a,c;let e=Re(i),r={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],extensions:[]},useDataChannel:t};r.ice.ufrag=String(e.media[0].iceUfrag),r.ice.password=e.media[0].icePwd||"",e.fingerprint&&(r.dtls.hash=e.fingerprint.type,r.dtls.fingerprint=e.fingerprint.hash,r.dtls.setup=e.setup||""),e.media[0].fingerprint&&(r.dtls.hash=e.media[0].fingerprint.type,r.dtls.fingerprint=e.media[0].fingerprint.hash),r.dtls.setup=e.media[0].setup||"";let n=e.media[0],s=e.media[1];n.ext&&(r.audio.extensions=n.ext.map(d=>({id:d.value,uri:d.uri}))),s.ext&&(r.video.extensions=s.ext.map(d=>({id:d.value,uri:d.uri})));let o={codec:n.rtp[0].codec,fmtp:n.fmtp[0].config,payload:n.fmtp[0].payload,rate:n.rtp[0].rate,channel:n.rtp[0].encoding,rtcpFb:[],rtx:0};(a=n.rtcpFb)==null||a.forEach(({payload:d,type:u,subtype:l})=>{if(d===o.payload){let h={id:u,params:[]};l&&h.params.push(l),o.rtcpFb.push(h)}}),r.audio.codecs.push(o);for(let d=0;d<s.rtp.length;d++){if(["rtx","red","ulpfec"].includes(s.rtp[d].codec))continue;let u=s.fmtp.filter(l=>l.payload===s.rtp[d].payload)[0];r.video.codecs.push({payload:s.rtp[d].payload,codec:s.rtp[d].codec,fmtp:u?u.config:"",rate:s.rtp[d].rate,rtx:((c=s.rtp[d+1])==null?void 0:c.codec)==="rtx"?s.rtp[d+1].payload:0,rtcpFb:((s==null?void 0:s.rtcpFb)||[]).filter(l=>l.payload===s.rtp[d].payload).map(({type:l,subtype:h})=>({id:l,params:h?[h]:[]}))})}return r},ql=({serverAbility:i,clientAbility:t,offerSDP:e,enableCustomMessage:r})=>{let n=Re(e),s={extmapAllowMixed:"extmap-allow-mixed",groups:n.groups,icelite:"ice-lite",media:[],msidSemantic:{semantic:"",token:"WMS"},name:"-",origin:{address:"127.0.0.1",username:"-",sessionId:String(Date.now()),sessionVersion:1,netType:"IN",ipVer:4},timing:{start:0,stop:0},version:0},o={candidates:i.candidates.map(a=>({component:1,foundation:"1",generation:0,ip:a.ip,port:a.port,priority:a.priority,transport:a.foundation,type:a.type})),connection:{version:4,ip:"0.0.0.0"},direction:m.TRANSCEIVER_DIRECTION_RECVONLY,ext:i.audio.extensions.map(a=>({value:a.id,uri:a.uri})),fingerprint:{type:i.dtls.hash,hash:i.dtls.fingerprint},fmtp:[{payload:i.audio.codecs[0].payload,config:i.audio.codecs[0].fmtp}],icePwd:i.ice.password,iceUfrag:i.ice.ufrag,mid:"0",payloads:String(i.audio.codecs[0].payload),port:n.media[0].port,protocol:n.media[0].protocol,type:m.AUDIO,setup:i.dtls.setup,rtcpFb:i.audio.codecs[0].rtcpfb.map(a=>({payload:i.audio.codecs[0].payload,type:a.id,subtype:a.params[0]})),rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[{payload:i.audio.codecs[0].payload,codec:i.audio.codecs[0].codec,rate:i.audio.codecs[0].rate,encoding:i.audio.codecs[0].channels}]};return s.media.push(o),[1,2,3].forEach(a=>{s.media.push($c({mid:a,serverAbility:i,clientAbility:t,parsedOffer:n}))}),r&&s.media.push(n.media.find(a=>a.mid==="dc")),ct(s)},$c=({mid:i,serverAbility:t,clientAbility:e,parsedOffer:r,useAllCodec:n=!1})=>{let s={candidates:t.candidates.map(o=>({component:1,foundation:"1",generation:0,ip:o.ip,port:o.port,priority:o.priority,transport:o.foundation,type:o.type})),connection:{version:4,ip:"0.0.0.0"},direction:m.TRANSCEIVER_DIRECTION_RECVONLY,ext:t.video.extensions.map(o=>({value:o.id,uri:o.uri})),fingerprint:{type:t.dtls.hash,hash:t.dtls.fingerprint},fmtp:[],icePwd:t.ice.password,iceUfrag:t.ice.ufrag,mid:String(i),payloads:"",port:r.media[0].port,protocol:r.media[0].protocol,type:m.VIDEO,setup:t.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(t.video.codecs.length>0)if(n)for(let o=0;o<t.video.codecs.length;o++)qs(s,t.video.codecs[o]);else{let o=t.video.codecs.findIndex(a=>a.codec.toLowerCase()===(t.useVp8?"vp8":"h264"));qs(s,t.video.codecs[o])}else if(n)for(let o=0;o<e.video.codecs.length;o++)qs(s,e.video.codecs[o]);else qs(s,e.video.codecs[0]);return s.payloads=s.payloads.trim(),s},qs=(i,t)=>{i.payloads=`${i.payloads} ${t.payload}`,i.fmtp.push({payload:t.payload,config:t.fmtp}),i.rtcpFb=[...i.rtcpFb||[],...(t.rtcpfb||t.rtcpFb).map(e=>({payload:t.payload,type:e.id,subtype:e.params[0]}))],i.rtp.push({payload:t.payload,codec:t.codec.toUpperCase(),rate:t.rate}),t.rtx&&(i.payloads=`${i.payloads} ${t.rtx}`,i.fmtp.push({payload:t.rtx,config:`apt=${t.payload}`}),i.rtp.push({payload:t.rtx,codec:"rtx",rate:t.rate}))};function z_(i){let t=new Set(["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.ext&&(i.ext=i.ext.filter(e=>!t.has(e.uri)))}function q_(i){if(!i.rtcpFb)return;let t=[];i.rtcpFb.forEach((e,r)=>{var n;t.push(e),i.rtcpFb&&((n=i.rtcpFb[r+1])==null?void 0:n.payload)!==e.payload&&e.type!=="rrtr"&&t.push({payload:e.payload,type:"rrtr"})}),i.rtcpFb=t}function Q_(i){i.type===m.VIDEO&&i.fmtp&&i.fmtp.forEach(t=>{t.config.includes("apt")||(t.config+=";sps-pps-idr-in-keyframe=1")})}function Z_(i){i.type===m.AUDIO&&i.fmtp&&i.fmtp.forEach(t=>{t.config+=";sprop-stereo=1;stereo=1"})}var Ql=i=>{let t=Bc.default.parse(i);return t.media.forEach(e=>{var r;(e.type===m.AUDIO||e.type===m.VIDEO)&&(q_(e),Q_(e),Z_(e),z_(e)),((r=e.payloads)==null?void 0:r.includes("datachannel"))&&t.groups&&e.mid&&(t.groups[0].mids=t.groups[0].mids.replace(e.mid,"dc"),e.mid="dc")}),Bc.default.write(t)};var fi=(a=>(a.TRACK="track",a.DATA_CHANNEL_MESSAGE="data_channel_msg",a[a.CONNECTION_STATE_CHANGED="connection-state-changed"]="CONNECTION_STATE_CHANGED",a[a.FIREWALL_RESTRICTION="firewall-restriction"]="FIREWALL_RESTRICTION",a.RECONNECTED="spc-reconnected",a.RECONNECT_FAILED="spc-reconnect-failed",a.ERROR="error",a))(fi||{}),tp=0,ip=!1,ef=new Set,tf=i=>tp>2&&!ip&&ef.size===0&&i,Ir=class extends ep.default{constructor({signalChannel:e,room:r,enableCustomMessage:n}){super();p(this,"currentState","DISCONNECTED");p(this,"_room");p(this,"_signalChannel");p(this,"_peerConnection",null);p(this,"_datachannel",null);p(this,"_enableCustomMessage");p(this,"_log");p(this,"_downlinkMIDMap",new Map);p(this,"_reconnectionTimer",-1);p(this,"reconnectionCount",0);p(this,"_clientAbility",null);p(this,"_serverAbility",null);p(this,"addDownlinkQueue",new Set);p(this,"removeDownlinkQueue",new Set);p(this,"_parsedAnswer",null);p(this,"_updateSDPPromise",null);p(this,"_waitForPCConnectedPromise");p(this,"_waitForPCConnectedPromiseReject",null);p(this,"_isSDPLogged",!1);this._room=r,this._enableCustomMessage=n,this._signalChannel=e,this._log=M.createLogger({id:"spc",userId:this._room.userId,sdkAppId:this._room.sdkAppId})}get isH264EncodeSupported(){let e=this._room.checkSystemResult.detail.isH264EncodeSupported;return this._serverAbility&&(e=e&&!!this._serverAbility.video.codecs.find(r=>r.codec.toLowerCase()==="h264")),e}get isVP8EncodeSupported(){let e=this._room.checkSystemResult.detail.isVp8EncodeSupported;return this._serverAbility&&(e=e&&this._serverAbility.useVp8),e}get uplinkSSRC(){return this._peerConnection&&this._peerConnection.localDescription?Xl(this._peerConnection.localDescription.sdp):{audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0}}get isReconnecting(){return this.currentState==="RECONNECTING"||this._reconnectionTimer>0}initialize(){return E(this,null,function*(){try{this._peerConnection=new RTCPeerConnection({offerExtmapAllowMixed:!0,iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._room.sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"}),this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this._peerConnection.ontrack=r=>this.emit("track",r),this._enableCustomMessage&&(this._datachannel=this._peerConnection.createDataChannel(`${this._room.userId}dc`),this._datachannel.binaryType="arraybuffer",this._datachannel.onopen=()=>{this._log.info("datachannel open")},this._datachannel.onclose=()=>{this._log.warn("datachannel close")},this._datachannel.onmessage=r=>{let n=new Fc(r.data);this.emit("data_channel_msg",{data:n})},this._datachannel.onerror=r=>{this._log.warn("datachannel error",r)}),this._peerConnection.addTransceiver(m.AUDIO,{direction:m.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(m.VIDEO,{direction:m.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(m.VIDEO,{direction:m.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(m.VIDEO,{direction:m.TRANSCEIVER_DIRECTION_SENDONLY});let e=yield this._peerConnection.createOffer();return yield this.setOffer(e),this._clientAbility=zl(e.sdp,this._enableCustomMessage),this._clientAbility}catch(e){throw this._log.error(`initialize failed ${e}`),e}})}connect(e,r=!1){return E(this,null,function*(){try{if(this.currentState==="CONNECTED")return;let n=q(),s={type:"answer",sdp:ql({serverAbility:e,clientAbility:this._clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(s),yield this.waitForPeerConnectionConnected(),r||C.emit(S.API_SUCCESS_RATE,{room:this._room,apiName:"SPCConnect",cost:Math.min(q()-n,30*1e3)})}catch(n){let s=n instanceof L&&n.code===v.API_CALL_ABORTED;throw s||this._log.error(`connect failed: ${n} ${e}`),this.reset(),!s&&!this.isReconnecting&&(C.emit(S.API_SUCCESS_RATE,{room:this._room,apiName:"SPCConnect",error:n}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),n}})}reconnect(){return E(this,null,function*(){if(this._reconnectionTimer!==-1){this._log.warn("reconnect() is reconnecting, ignore current reconnection");return}if(!this._signalChannel.isConnected){this._log.warn("reconnect() wait signal channel is connected"),this._signalChannel.once(ge.CONNECTED,this.reconnect,this);return}try{this.reconnectionCount++,this._log.warn(`reconnect() trying [${this.reconnectionCount}]`),this.reset();let e=yield this.initialize(),r=yield this._signalChannel.sendWaitForResponse({command:ne.REBUILD_PEER_CONNECTION,responseCommand:Z.REBUILD_PEER_CONNECTION_RES,data:{ability:e},enableLog:!1});yield this.connect(r.data.data.ability,!0),this._log.warn("reconnect() successfully"),this.stopReconnection(),this.emit("spc-reconnected")}catch(e){if(e)if(e.message.includes("timeout")){let r=rt(this.reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${r/1e3}s`),this._reconnectionTimer=window.setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},r)}else this._log.error(`reconnect() failed ${e}`),C.emit(S.API_SUCCESS_RATE,{room:this._room,apiName:"SPCReconnect",error:e}),this.reconnectionCount>=ti()&&this._log.warn(`SDK has tried reconnect for ${ti()} times, but all failed, please check your network`),this.stopReconnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.emit("error")}})}getPeerConnection(){return this._peerConnection}startReconnection(){return E(this,null,function*(){this._log.warn("start reconnect"),this.emitConnectionStateChangedEvent("RECONNECTING");let e=q();yield this.reconnect(),C.emit(S.API_SUCCESS_RATE,{room:this._room,apiName:"SPCReconnect",cost:Math.min(q()-e,30*1e3)})})}stopReconnection(){this._reconnectionTimer!==-1&&(this._log.info("stop reconnect"),this.reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(ge.CONNECTED,this.reconnect,this))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&((e=this._peerConnection)==null?void 0:e.connectionState)===fe.CLOSED&&this.startReconnection()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}onConnectionStateChange(e){let r=this._peerConnection.iceConnectionState,n=this.getDTLSTransportState();if(this._log.info(`connectionState: ${e.target.connectionState}, ICE: ${r}, DTLS: ${n}`),e.target.connectionState===fe.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),e.target.connectionState===fe.FAILED||e.target.connectionState===fe.CLOSED){let s=`ICE/DTLS Transport connection ${e.target.connectionState}. ICE Transport state: ${r}, DTLS Transport state: ${n}`,o=new L({message:s,code:v.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()}(e.target.connectionState===fe.CONNECTED||e.target.connectionState===fe.COMPLETED)&&(this.logSelectedCandidate(),this.emitConnectionStateChangedEvent("CONNECTED"))}getDTLSTransportState(){if(!this._peerConnection)return St;let e=null;return!nr()||this._peerConnection.getSenders().length===0?St:(e=this._peerConnection.getSenders()[0].transport,!vi()||this._peerConnection.getReceivers().length===0?St:e?e.state:St)}emitConnectionStateChangedEvent(e){e!==this.currentState&&(this.currentState==="RECONNECTING"&&e==="CONNECTING"||(this.emit(fi.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:e}),this.currentState=e))}logSelectedCandidate(){return E(this,null,function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[r,n]of e)if(ci(n)){let s=e.get(n.localCandidateId),o=e.get(n.remoteCandidateId);s&&this._log.info(`local candidate: ${s.candidateType} ${s.protocol}:${s.ip||s.address}:${s.port} ${s.networkType||""} ${s.candidateType==="relay"?`relayProtocol:${s.relayProtocol}`:""}`),o&&this._log.info(`remote candidate: ${o.candidateType} ${o.protocol}:${o.ip||o.address}:${o.port}`);break}})}waitForPeerConnectionConnected(){return this._waitForPCConnectedPromise?this._waitForPCConnectedPromise:(this._waitForPCConnectedPromise=new Promise((e,r)=>{if(this.currentState==="CONNECTED")return e();this._waitForPCConnectedPromiseReject=r;let n=c=>{c.state==="CONNECTED"&&(clearTimeout(a),o(),e())},s=({room:c})=>{c===this._room&&(clearTimeout(a),o(),r(new L({code:v.API_CALL_ABORTED,message:$({key:w.CONNECTION_ABORTED,data:"leave room"})})))},o=()=>{C.off(S.LEAVE_SUCCESS,s,this),this.off(fi.CONNECTION_STATE_CHANGED,n,this)},a=setTimeout(()=>{o();let c=new L({code:v.API_CALL_TIMEOUT,message:"connection timeout"});tp+=1,tf(this._signalChannel.isConnected)&&(this._log.warn("firewall restrition"),ip=!0,this.emit(fi.FIREWALL_RESTRICTION)),r(c)},Jn);C.on(S.LEAVE_SUCCESS,s,this),this.on(fi.CONNECTION_STATE_CHANGED,n,this)}),this._waitForPCConnectedPromise=this._waitForPCConnectedPromise.finally(()=>{this._waitForPCConnectedPromise=null,this._waitForPCConnectedPromiseReject=null}),this._waitForPCConnectedPromise)}waitForReconnected(){return this.isReconnecting?new Promise((e,r)=>{this.once("spc-reconnected",e),this.once("error",r)}):Promise.resolve()}addDownlink(e){return E(this,null,function*(){if(this._log.info(`addDownlink(${e.userId}) trying`),this.isReconnecting&&(yield this.waitForReconnected()),this.updateLocalAndRemoteSDPConfig(e),this.addDownlinkQueue.size===0)try{yield this.updateSDP({isNeedToCreateOffer:!0}),this._log.info(`addDownlink(${e.userId}) done`)}catch(r){this._log.info(`addDownlink(${e.userId}) failed`),yield this.startReconnection()}})}updateLocalAndRemoteSDPConfig({ssrc:e,tinyId:r}){if(!this._peerConnection)return;this._log.info(`updateLocalAndRemoteSDPConfig ${JSON.stringify(e)} ${r}`);let n=this._peerConnection.getTransceivers().filter(d=>d.direction==="inactive").slice(0,3).map(d=>(d.direction=m.TRANSCEIVER_DIRECTION_RECVONLY,Number(d.mid)));n.length===0&&(this._peerConnection.addTransceiver(m.AUDIO,{direction:m.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(m.VIDEO,{direction:m.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(m.VIDEO,{direction:m.TRANSCEIVER_DIRECTION_RECVONLY})),this._parsedAnswer||(this._parsedAnswer=Re(this._peerConnection.remoteDescription.sdp));let s,o,a;if(n.length===3)s=this._parsedAnswer.media.find(d=>Number(d.mid)===Number(n[0])),o=this._parsedAnswer.media.find(d=>Number(d.mid)===Number(n[1])),a=this._parsedAnswer.media.find(d=>Number(d.mid)===Number(n[2]));else{s=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let d=$c({mid:1,serverAbility:this._serverAbility,clientAbility:this._clientAbility,parsedOffer:Re(this._peerConnection.localDescription.sdp),useAllCodec:!0});o=JSON.parse(JSON.stringify(d)),a=JSON.parse(JSON.stringify(d)),s.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(s),o.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(o),a.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(a)}s.direction=m.TRANSCEIVER_DIRECTION_SENDONLY,s.ssrcs=[{id:e.audio,attribute:"cname",value:`${r}`},{id:e.audio,attribute:"msid",value:`${r}-${m.MAIN} ${r}-audio`}],o.direction=m.TRANSCEIVER_DIRECTION_SENDONLY,o.ssrcs=[{id:e.video,attribute:"cname",value:`${r}`},{id:e.video,attribute:"msid",value:`${r}-${m.MAIN} ${r}-bigvideo`},{id:e.videoRtx,attribute:"cname",value:`${r}`},{id:e.videoRtx,attribute:"msid",value:`${r}-${m.MAIN} ${r}-bigvideo`}],o.ssrcGroups=[{semantics:"FID",ssrcs:`${e.video} ${e.videoRtx}`}],a.direction=m.TRANSCEIVER_DIRECTION_SENDONLY;let c=`${r}-aux`;a.ssrcs=[{id:e.auxiliary,attribute:"cname",value:c},{id:e.auxiliary,attribute:"msid",value:`${c} ${r}-aux${m.VIDEO}`},{id:e.auxiliaryRtx,attribute:"cname",value:`${c} ${r}-aux${m.VIDEO}`},{id:e.auxiliaryRtx,attribute:"msid",value:`${c} ${r}-aux${m.VIDEO}`}],a.ssrcGroups=[{semantics:"FID",ssrcs:`${e.auxiliary} ${e.auxiliaryRtx}`}],this._parsedAnswer.groups&&(this._parsedAnswer.groups[0].mids=this._parsedAnswer.media.map(d=>d.mid).join(" ")),this._downlinkMIDMap.set(r,[s.mid,o.mid,a.mid])}removeDownlink(e,r){return E(this,null,function*(){if(!this._downlinkMIDMap.has(e)||!this._peerConnection)return;this._log.info(`removeDownlink(${r}) trying`),this.isReconnecting&&(yield this.waitForReconnected());let n=this._downlinkMIDMap.get(e),s=!1;this._peerConnection.getTransceivers().forEach(o=>{n!=null&&n.includes(Number(o.mid))&&(s=!0,o.direction="inactive")}),this._parsedAnswer||(this._parsedAnswer=Re(this._peerConnection.remoteDescription.sdp)),this._parsedAnswer.media.forEach(o=>{n!=null&&n.includes(Number(o.mid))&&(s=!0,o.direction="inactive",o.ssrcs=[],o.ssrcGroups=[])}),this.removeDownlinkQueue.size===0&&s&&(yield this.updateSDP({isNeedToCreateOffer:!0,tinyIdRemoving:e})),this._downlinkMIDMap.delete(e),this._log.info(`removeDownlink(${r}) done`)})}getDownlinkMids(e){return this._downlinkMIDMap.get(e)}setBandwidth(e){return E(this,null,function*(){if(!this._peerConnection)return;let{audio:r,bigVideo:n,smallVideo:s,auxVideo:o}=e;try{if(tn()){let a=this._peerConnection.getSenders().slice(0,4);for(let c=0;c<a.length;c++){let d=a[c],u;c===0&&r?u=r:c===1&&n?u=n:c===2&&s?u=s:c===3&&o&&(u=o),u&&(yield this.setSenderMaxBitrate(d,u))}}else yield this.setBandwidthBySDP(e);Object.keys(e).forEach(a=>{e[a]&&this._log.info(`${a} bandwidth was set to ${e[a]} kbps`)})}catch(a){this._log.error(`failed to set bandwidth${a}`)}})}setSenderMaxBitrate(e,r){let n=e.getParameters();return(!n.encodings||n.encodings.length===0)&&(n.encodings=[{}]),r==="unlimited"?delete n.encodings[0].maxBitrate:n.encodings[0].maxBitrate=r*1e3,e.setParameters(n)}setBandwidthBySDP({audio:e,bigVideo:r,smallVideo:n,auxVideo:s}){if(!this._peerConnection||!this._peerConnection.localDescription)return;let o=Re(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=Re(this._peerConnection.remoteDescription.sdp));let a=pe?"TIAS":"AS";e&&(o.media[0].bandwidth=[{type:a,limit:pe?e*1e3:e}],this._parsedAnswer.media[0].bandwidth=[{type:a,limit:pe?e*1e3:e}]),r&&(o.media[1].bandwidth=[{type:a,limit:pe?r*1e3:r}],this._parsedAnswer.media[1].bandwidth=[{type:a,limit:pe?r*1e3:r}]),n&&(o.media[2].bandwidth=[{type:a,limit:pe?n*1e3:n}],this._parsedAnswer.media[2].bandwidth=[{type:a,limit:pe?n*1e3:n}]),s&&(o.media[3].bandwidth=[{type:a,limit:pe?s*1e3:s}],this._parsedAnswer.media[3].bandwidth=[{type:a,limit:pe?s*1e3:s}]);let c={type:"offer",sdp:ct(o)};return this.updateSDP({localDescription:c})}updateSDP({isNeedToCreateOffer:e=!1,localDescription:r,tinyIdRemoving:n}){if(!this._parsedAnswer)return;let s=ct(this._parsedAnswer);return this._updateSDPPromise=new Promise((o,a)=>E(this,null,function*(){var c,d;try{e&&this._peerConnection&&(this._log.info("creating offer"),r=yield this._peerConnection.createOffer()),r&&(yield this.setOffer(r)),yield this.setAnswer({type:"answer",sdp:s}),this._updateSDPPromise=null,o()}catch(u){this._log.error(u),!this._isSDPLogged&&this._peerConnection&&(this._log.warn(`transceivers: ${JSON.stringify(this._peerConnection.getTransceivers().map(({mid:l,currentDirection:h,direction:I,stopped:T})=>({mid:l,currentDirection:h,direction:I,stopped:T})))}`),this._log.warn(`parsedAnswer: ${JSON.stringify(this._parsedAnswer)}`),this._log.warn(`local sdp: ${r==null?void 0:r.sdp}`||((c=this._peerConnection.localDescription)==null?void 0:c.sdp)),this._log.warn(`remote sdp: ${s}`||((d=this._peerConnection.remoteDescription)==null?void 0:d.sdp)),this._isSDPLogged=!0),this._updateSDPPromise=null,a(u)}})),this._updateSDPPromise}setOffer(e){return this._log.info("setting offer"),this._peerConnection.setLocalDescription({type:"offer",sdp:Ql(e.sdp)})}setAnswer(e){return this._log.info("setting answer"),this._peerConnection.setRemoteDescription(e)}sendDataChannelMessage(e){var r;(r=this._datachannel)==null||r.send(e)}reset(){var e;(e=this._peerConnection)==null||e.close(),this._waitForPCConnectedPromise=null,this._parsedAnswer=null}close(){this._log.info("close pc"),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners()}};F([Nn()],Ir.prototype,"updateSDP",1);var Hc=class{constructor(t){p(this,"tag");p(this,"len");p(this,"data");let e=new DataView(t);this.tag=e.getUint16(),this.len=e.getUint16(2),this.data=new Uint8Array(t).slice(4,2+2+this.len).buffer}},Fc=class{constructor(t){p(this,"tinyId");p(this,"data");let e=new DataView(t),r=0,n=[];for(;r<e.byteLength;){let s=e.getUint16(r+2),o=new Hc(new Uint8Array(t).slice(r,r+2+2+s).buffer);n.push(o),r+=2+2+s}n.forEach(s=>{s.tag===1?this.tinyId=new TextDecoder().decode(s.data):s.tag===2&&(this.data=s.data)})}},Zl=new Set;function Fi(){let i=Math.floor(Math.random()*4294967296);return Zl.has(i)?Fi():(Zl.add(i),i)}var Xk=_(f());var Nk=_(f()),rp=_(nt());var Gi=class extends rp.default{constructor(e){super();p(this,"userId");p(this,"tinyId");p(this,"_sdpSemantics");p(this,"_isUplink");p(this,"_room");p(this,"_log");p(this,"_signalChannel");p(this,"_currentState","DISCONNECTED");p(this,"_prevTime",-1);p(this,"_enableSEI");p(this,"_sei");this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=M.createLogger({id:"n",userId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=e.signalChannel,this._enableSEI=e.enableSEI,this._enableSEI&&ui&&(this._sei=new Fs(this,this._log,this._isUplink))}get _peerConnection(){var e;return((e=this.singlePC)==null?void 0:e.getPeerConnection())||null}get singlePC(){return this._room.singlePC}close(e){this._log.info("close connection"),this.emit("closed",e),this._sei&&(this._sei.destroy(),this._sei=null)}emitConnectionStateChangedEvent(e){return e===this._currentState?!1:(C.emit(S.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:e,remoteUserId:this._isUplink?void 0:this.userId}),this.emit("connection-state-changed",{prevState:this._currentState,state:e}),this._currentState=e,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}getCurrentState(){return this._currentState}get isH264(){var e,r;return!!((r=(e=this._peerConnection)==null?void 0:e.remoteDescription)!=null&&r.sdp.includes("H264"))}};var Gc=class extends Gi{constructor(e){super(te(B({},e),{isUplink:!0}));p(this,"localMainAudioTrack",null);p(this,"localMainVideoTrack",null);p(this,"localAuxAudioTrack",null);p(this,"localAuxVideoTrack",null);p(this,"_isPublishingAux",!1);p(this,"_publishingLocalAudioTrack");p(this,"_publishingLocalVideoTrack");p(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});p(this,"_smallGenerator");p(this,"_audioManager");this._audioManager=e.audioManager,this._smallGenerator=null,this.initialize()}get ssrc(){if(!this.singlePC)return{audio:0,video:0,videoRtx:0,small:0,smallRtx:0,auxiliary:0,auxiliaryRtx:0};let{audioSsrc:e,bigVideoSsrc:r,bigVideoRtxSsrc:n,smallVideoSsrc:s,smallVideoRtxSsrc:o,auxVideoSsrc:a,auxVideoRtxSsrc:c}=this.singlePC.uplinkSSRC;return{audio:e||0,video:r||0,videoRtx:n||0,small:s||0,smallRtx:o||0,auxiliary:a||0,auxiliaryRtx:c||0}}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}get publishState(){var r,n,s,o;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(st()?(e.audio=!!((r=a[0])!=null&&r.track),e.bigVideo=!!((n=a[1])!=null&&n.track),e.smallVideo=!!((s=a[2])!=null&&s.track),e.auxVideo=!!((o=a[3])!=null&&o.track)):a.forEach(c=>{c.track&&(c.track.kind===m.AUDIO?e.audio=!0:(e.bigVideo=!0,this._smallGenerator&&(e.smallVideo=!0)))}))}return e}initialize(){this.installEvents()}reset(){this.uninstallEvents(),this.localMainVideoTrack&&this.localMainVideoTrack.canvasTrack&&this.localMainVideoTrack.destoryCanvasTrack()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._smallGenerator&&(this._smallGenerator.destroy(),this._smallGenerator=null)}installEvents(){var e;this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||(e=this.singlePC)==null||e.on("spc-reconnected",this.onSinglePCReconnected,this)}uninstallEvents(){var e;this.off("connection-state-changed",this.handleConnectionStateChange,this),(e=this.singlePC)==null||e.off("spc-reconnected",this.onSinglePCReconnected,this)}emitConnectionStateChangedEvent(e,r){var o,a,c;let n=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&n!==e&&(r?r.emit("connection-state-changed",{prevState:n,state:e}):((o=this.localMainVideoTrack)==null||o.emit("connection-state-changed",{prevState:n,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:n,state:e}),(c=this._publishingLocalVideoTrack)==null||c.emit("connection-state-changed",{prevState:n,state:e}))),s}publish(s){return E(this,arguments,function*({localAudioTrack:e,localVideoTrack:r,isAuxiliary:n}){var a,c,d,u,l,h;if(!this.singlePC)return;if(yield this.singlePC.waitForPeerConnectionConnected(),e&&(this._publishingLocalAudioTrack=e),r){if(!this.singlePC.isH264EncodeSupported&&!this.singlePC.isVP8EncodeSupported)throw new L({code:v.NOT_SUPPORTED_H264,message:$({key:w.NOT_SUPPORTED_H264ENCODE})});this._publishingLocalVideoTrack=r}this._isPublishingAux=n;let o;r&&!n&&r.small&&(this._smallGenerator=new Yt(r),yield this._smallGenerator.initialize(),o=this._smallGenerator.generateSmallVideoTrack(r.small)),di()&&(yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:r,smallTrack:o,isAuxiliary:n})),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,n?(r&&(this.localAuxVideoTrack=r),e&&(this.localAuxAudioTrack=e)):(r&&(this.localMainVideoTrack=r),e&&(this.localMainAudioTrack=e)),yield this.singlePC.setBandwidth({audio:((a=this.localMainAudioTrack)==null?void 0:a.profile.bitrate)||((c=this.localAuxAudioTrack)==null?void 0:c.profile.bitrate),bigVideo:(d=this.localMainVideoTrack)==null?void 0:d.profile.bitrate,smallVideo:(l=(u=this.localMainVideoTrack)==null?void 0:u.small)==null?void 0:l.bitrate,auxVideo:(h=this.localAuxVideoTrack)==null?void 0:h.profile.bitrate}),yield this._signalChannel.sendWaitForResponse({command:ne.SPC_PUBLISH,responseCommand:Z.SPC_PUBLISH_RESULT,data:te(B({},this.singlePC.uplinkSSRC),{state:this.publishState})}),this.sendMediaSettings(),this.installTrackMuteEvents(e,r),this.sendMutedFlag()})}publishByTransceiver({localAudioTrack:e,localVideoTrack:r,smallTrack:n,isAuxiliary:s}){this._log.info("publish by transceiver");let o=new MediaStream;r&&er&&as&&r.genCanvasTrack();let a=(r==null?void 0:r.canvasTrack)||(r==null?void 0:r.mediaTrack),c=this._audioManager.mediaStreamTrack,d=this._peerConnection.getTransceivers(),u=[];if(c){o.addTrack(c);let l=d[0].sender.replaceTrack(c);u.push(l)}if(a)if(o.addTrack(a),s){let l=d[3].sender.replaceTrack(a);u.push(l)}else{let l=d[1].sender.replaceTrack(a);u.push(l)}if(n){let l=d[2].sender.replaceTrack(n);u.push(l)}return Promise.all(u)}installTrackMuteEvents(...e){e.forEach(r=>{r&&(r==null||r.on("mute",this.sendMutedFlag,this),r==null||r.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(r=>{r&&(r==null||r.off("mute",this.sendMutedFlag,this),r==null||r.off("unmute",this.sendMutedFlag,this))})}unpublish(n){return E(this,arguments,function*({localAudioTrack:e,localVideoTrack:r}){let s=r&&r===this.localAuxVideoTrack,o=e==null?void 0:e.mediaTrack,a=r==null?void 0:r.mediaTrack,c=this._peerConnection.getSenders(),d=[];o&&(this._audioManager.removeAudioTrack(e),this._audioManager.isMixed||(yield c[0].replaceTrack(null),d.push(0),this.localMainAudioTrack=null)),a&&(s?(yield c[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=te(B({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),d.push(3)):(yield c[1].replaceTrack(null),yield c[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=te(B({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),d.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.setTransceiverDirection(se.INACTIVE,d),yield this.doPublishChange(!1)):yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,r),r==null||r.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return E(this,null,function*(){let r={state:this.publishState,constraintConfig:this._mediaSettings},n=yield this._signalChannel.sendWaitForResponse({command:ne.PUBLISH_STATE_CHANGE,data:r,responseCommand:Z.PUBLISH_STATE_CHANGE_RESULT,enableLog:e});this.checkPublishResultCode(n.data.code,n.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:ne.UNPUBLISH,commandDesc:"unpublish",responseCommand:Z.UNPUBLISH_RESULT,enableLog:e}).catch(r=>{if(r.getCode()===v.API_CALL_TIMEOUT)return Promise.resolve();throw r})}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:r}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":r&&(this._mediaSettings.videoCodec="VP8");let n=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:s,localAuxVideoTrack:o}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?o=this._publishingLocalVideoTrack:s=this._publishingLocalVideoTrack),wt){if(n&&n.mediaTrack){let a=n.mediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=n.profile.bitrate*1e3,this._mediaSettings.audioFs=a.sampleRate||0}if(s&&s.mediaTrack){let a=s.mediaTrack.getSettings();this._mediaSettings.videoWidth=a.width||0,this._mediaSettings.videoHeight=a.height||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=s.profile.bitrate*1e3,s.small&&(this._mediaSettings.smallVideoWidth=s.small.width,this._mediaSettings.smallVideoHeight=s.small.height,this._mediaSettings.smallVideoFps=s.small.frameRate,this._mediaSettings.smallVideoBps=s.small.bitrate*1e3)}if(o&&o.mediaTrack){let a=o.mediaTrack.getSettings();this._mediaSettings.auxVideoWidth=a.width||0,this._mediaSettings.auxVideoHeight=a.height||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=o.profile.bitrate*1e3}}else n&&n.mediaTrack&&(this._mediaSettings.audioChannel=n.profile.channelCount,this._mediaSettings.audioBps=n.profile.bitrate*1e3,this._mediaSettings.audioFs=n.profile.sampleRate),s&&s.mediaTrack&&(this._mediaSettings.videoWidth=s.profile.width,this._mediaSettings.videoHeight=s.profile.height,this._mediaSettings.videoFps=s.profile.frameRate,this._mediaSettings.videoBps=s.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:ne.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:Z.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return E(this,null,function*(){var n;if(!this._peerConnection)return;let r=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is adding ${e.kind} track to current published local ${r?m.AUXILIARY:m.MAIN} stream`),(n=this._sei)==null||n.handleEncodedStreams(),st()&&(yield this.addTrackByTransceiver(e,r))})}addTrackByTransceiver(e,r){return E(this,null,function*(){var o;if(!e.mediaTrack)return;let n=this._peerConnection.getTransceivers(),s=e.mediaTrack;if(e.kind===m.AUDIO)this._audioManager.addAudioTrack(e),s=this._audioManager.mediaStreamTrack,yield n[0].sender.replaceTrack(s);else{let a=r?3:1;if(yield n[a].sender.replaceTrack(s),a===1&&((o=this.localMainVideoTrack)==null?void 0:o.small)){this._smallGenerator=new Yt(this.localMainVideoTrack),yield this._smallGenerator.initialize();let c=this._smallGenerator.generateSmallVideoTrack(this.localMainVideoTrack.small);yield n[2].sender.replaceTrack(c)}n[a].direction===se.INACTIVE&&(yield this.setTransceiverDirection(se.SENDONLY,[a]))}this.updateMediaSettings(),yield this.doPublishChange()})}removeTrack(e){return E(this,null,function*(){if(!this._peerConnection)return;let r=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${r?m.AUXILIARY:m.MAIN} stream`),st()&&(yield this.removeTrackByTransceiver(e,r))})}removeTrackByTransceiver(e,r){return E(this,null,function*(){if(!e.mediaTrack)return;let n=this._peerConnection.getTransceivers();if(e.kind===m.AUDIO)this._audioManager.removeAudioTrack(e),this._audioManager.isMixed||(yield n[0].sender.replaceTrack(null));else{let s=r?3:1;yield n[s].sender.replaceTrack(null),s===1&&this._smallGenerator&&(this._smallGenerator.destroy(),this._smallGenerator=null,yield n[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(se.INACTIVE,[s])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,r){return E(this,null,function*(){if(!pe)return;let n=!1,s=!1;this._log.info(`setting transceiver ${r.join(",")} direction to ${e}`);let o=this._peerConnection.getTransceivers();if(r.forEach(d=>{o[d].direction!==e&&(o[d].direction=e,n=!0)}),n){this._log.info("updating offer");let d=yield this._peerConnection.createOffer();yield this._peerConnection.setLocalDescription(d)}let a=-1,c=this._peerConnection.remoteDescription.sdp.split(`\r
100
+ `),e}removeBandwidthRestriction(e){return e.replace(/b=AS:.*\r\n/,"").replace(/b=TIAS:.*\r\n/,"")}removeVideoOrientation(e){return e.replace(/urn:3gpp:video-orientation/,"")}connect(){return E(this,null,function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(e){throw this.closePeerConnection(!0),this.uninstallEvents(),e}})}exchangeSDP(){return E(this,null,function*(){try{yield this.createOffer(),this._log.info("createOffer success, sending offer to remote server"),yield this.doExchangeSDP()}catch(e){throw e}})}createOffer(){return E(this,null,function*(){try{let e=yield this._peerConnection.createOffer(Gl);yield this._peerConnection.setLocalDescription(e),e.sdp&&this.updateSSRC(e.sdp)}catch(e){throw e}})}doExchangeSDP(){let e={command:ne.PUBLISH,responseCommand:Q.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof Mt||this.localAuxVideoTrack instanceof Mt,state:this.publishState,constraintConfig:this._mediaSettings},enableLog:!1};return this._log.debug(`sending sdp offer: ${e.data.sdp}`),this._signalChannel.sendWaitForResponse(e).then(r=>{let{code:n,message:s,data:o}=r.data;return n===0?this.acceptAnswer(o):this.checkPublishResultCode(n,s)})}setSDPDirection(e,r,n="all"){let s=Ie(e);return s.media.forEach(o=>{(n==="all"||o.type===n)&&(o.direction=r)}),ut(s)}acceptAnswer(e){return E(this,null,function*(){var r,n,s,o,a;try{let c;if(this._publishingLocalAudioTrack||this._publishingLocalVideoTrack||this.isMainStreamPublished){let l=((r=this._publishingLocalVideoTrack)==null?void 0:r.profile.bitrate)||((n=this.localMainVideoTrack)==null?void 0:n.profile.bitrate),h=((s=this._publishingLocalAudioTrack)==null?void 0:s.profile.bitrate)||((o=this.localMainAudioTrack)==null?void 0:o.profile.bitrate);if(l){let I=this._isPublishingAux?m.AUXILIARY:m.BIG;c=yield this.setBandwidth({bandwidth:l,type:m.VIDEO,sdp:c,videoType:I})}h&&(c=yield this.setBandwidth({bandwidth:h,type:m.AUDIO,sdp:c}))}if(c=this.removeVideoOrientation(e.sdp),(a=this._publishingLocalVideoTrack)!=null&&a.small){let{smallStreamConfig:l}=this._room;c=yield this.setBandwidth({bandwidth:this._publishingLocalVideoTrack.small.bitrate||l.bitrate,type:m.VIDEO,videoType:m.SMALL,sdp:c})}let u={type:e.type,sdp:c};yield this._peerConnection.setRemoteDescription(u),this._log.debug(`accepted answer: ${c}`)}catch(c){throw this._log.error(`failed to accept remote answer ${c}`),c}})}sendMutedFlag(e){var s,o,a;if(e===this.localAuxAudioTrack||e===this.localAuxVideoTrack)return;let n={audio:!!((s=this.localMainAudioTrack)!=null&&s.muted),bigVideo:!!((o=this.localMainVideoTrack)!=null&&o.muted),auxVideo:!!((a=this.localAuxVideoTrack)!=null&&a.muted)};this._log.info(`send muted state: ${JSON.stringify(n)}`),this._signalChannel.send(ne.UPDATE_MUTE_STAT,n)}getIsReconnecting(){return this._isReconnecting}reconnect(){return E(this,null,function*(){if(!(Ci(ed.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:ne.UNPUBLISH,responseCommand:Q.UNPUBLISH_RESULT,enableLog:!1}),this.closePeerConnection(),this.initialize(),this.isMainStreamPublished&&(yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0})),this._log.warn("reconnect() uplink reconnect successfully"),this.stopReconnection()}catch(r){let n=ot(this._reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${n/1e3}s`),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},n)}})}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&C.emit(S.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{Ie(e).media.forEach((n,s)=>{if(n.type===m.AUDIO){let o=n.ssrcs&&n.ssrcs[0];o&&(this.ssrc.audio=Number(o.id))}else{if(this._sdpSemantics===Ir&&n.ssrcGroups){n.ssrcGroups.forEach((a,c)=>{let d=Number(a.ssrcs.split(" ")[0]);c===0?this.ssrc.video=d:c===1&&(this.ssrc.small=d)});return}let o=n.ssrcs&&n.ssrcs[0];if(!o)return;switch(s){case 1:this.ssrc.video=Number(o.id);break;case 2:this.ssrc.small=Number(o.id);break;case 3:this.ssrc.auxiliary=Number(o.id);break;default:break}}})}catch(r){}}getVideoTrackId(e=m.VIDEO){if(this._peerConnection){let r=this._peerConnection.getSenders();if(e===m.AUXILIARY&&r[3]&&r[3].track)return r[3].track.id;if(e===m.VIDEO&&r[1]&&r[1].track)return r[1].track.id}if(this.localMainVideoTrack&&e===m.VIDEO){let r=this.localMainVideoTrack.mediaTrack;if(r)return r.id}if(this.localAuxVideoTrack&&e===m.AUXILIARY){let r=this.localAuxVideoTrack.mediaTrack;if(r)return r.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,r){if(e!==0)throw e===xi?(this._log.error(xe.NOT_SUPPORTED_H264ENCODE),new M({code:v.NOT_SUPPORTED_H264,message:B({key:V.NOT_SUPPORTED_H264ENCODE})})):new M({code:v.UNKNOWN,message:B({key:V.SIGNAL_RESPONSE_FAILED,data:{signalResponse:Q.PUBLISH_RESULT,code:e,message:r}})})}sendSEI(e,r){var n;(n=this._sei)==null||n.push(e,r)}},Jn=ed;H([ae(i=>function(...t){return new Promise((e,r)=>{let n=s=>{this._emitter.off("closed",n),r(new M({code:v.API_CALL_ABORTED,message:B({key:V.CONNECTION_ABORTED,data:s})}))};this._emitter.on("closed",n),i.apply(this,t).then(e,r).finally(()=>{this._emitter.off("closed",n)})})})],Jn.prototype,"publish",1),H([Zs(Qe.prototype.afterConnect),Qs(Qe.prototype.beforeConnect)],Jn.prototype,"connect",1);var Io=Jn;var GP=_(f());var Yn=class{constructor(t,e){this.room=t;p(this,"_log");p(this,"_prevReportTime");p(this,"_prevReport",{});p(this,"_prevEncoderImplementation");p(this,"_prevQualityLimitationReason");p(this,"_prevAuxQualityLimitationReason");p(this,"_prevDecoderImplementationMap",new Map);p(this,"_spcStats",null);this._log=e,this._prevReportTime=0,this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevAuxQualityLimitationReason=""}get statInterval(){return this._prevReportTime===0?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(t){return E(this,null,function*(){var s;let e={audio:{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0},video:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},small:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},auxiliary:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},rtt:0},r=t.getPeerConnection(),n=t.getSSRC();if(r)try{(this._spcStats||(yield r.getStats())).forEach(a=>{if(a.type==="outbound-rtp")if(a.mediaType===m.VIDEO){let c;if(a.ssrc===n.video?c=m.VIDEO:a.ssrc===n.small?c=m.SMALL:a.ssrc===n.auxiliary&&(c=m.AUXILIARY),!c)return;e[c].bytesSent=a.bytesSent,e[c].packetsSent=a.packetsSent,e[c].framesEncoded=a.framesEncoded,a.ssrc===n.video?(!b(a.encoderImplementation)&&this._prevEncoderImplementation!==a.encoderImplementation&&(this._log.info(`encoderImplementation change to ${a.encoderImplementation}`),this._prevEncoderImplementation=a.encoderImplementation),!b(a.qualityLimitationReason)&&a.bytesSent!==0&&this._prevQualityLimitationReason!==a.qualityLimitationReason&&(this._log.info(`qualityLimitationReason change to ${a.qualityLimitationReason}`),this._prevQualityLimitationReason=a.qualityLimitationReason)):a.ssrc===n.auxiliary&&!b(a.qualityLimitationReason)&&a.bytesSent!==0&&this._prevAuxQualityLimitationReason!==a.qualityLimitationReason&&(this._log.info(`aux qualityLimitationReason change to ${a.qualityLimitationReason}`),this._prevAuxQualityLimitationReason=a.qualityLimitationReason)}else a.mediaType===m.AUDIO&&(e.audio.bytesSent=a.bytesSent,e.audio.packetsSent=a.packetsSent);else a.type==="candidate-pair"?hi(a)&&de(a.currentRoundTripTime)&&(e.rtt=Math.floor(a.currentRoundTripTime*1e3)):a.type==="media-source"&&(a.kind===m.AUDIO?(e.audio.audioLevel=a.audioLevel||0,e.audio.totalAudioEnergy=a.totalAudioEnergy||0):a.kind===m.VIDEO&&(a.trackIdentifier===t.getVideoTrackId(m.VIDEO)?e.video.fpsCapture=a.framesPerSecond:a.trackIdentifier===t.getVideoTrackId(m.AUXILIARY)?e.auxiliary.fpsCapture=a.framesPerSecond:e.small.fpsCapture=a.framesPerSecond));if(b(a.audioLevel)||(e.audio.audioLevel=a.audioLevel||0),!b(a.frameWidth)){let c=m.SMALL;a.trackIdentifier===t.getVideoTrackId(m.VIDEO)||a.ssrc===n.video?c=m.VIDEO:(a.trackIdentifier===t.getVideoTrackId(m.AUXILIARY)||a.ssrc===n.auxiliary)&&(c=m.AUXILIARY),e[c].frameWidth=a.frameWidth,e[c].frameHeight=a.frameHeight,e[c].framesSent=a.framesSent}}),e.audio.audioLevel===0&&(e.audio.audioLevel=((s=t.localMainAudioTrack)==null?void 0:s.getInternalAudioLevel())||0)}catch(o){this._log.warn(`failed to getStats on sender connection ${o}`)}return e})}getReceiverStats(t){return E(this,null,function*(){let e={tinyId:t.tinyId,userId:t.userId,rtt:0,hasAudio:!1,hasVideo:!1,hasAuxiliary:!1,audio:{bytesReceived:0,packetsReceived:0,packetsLost:0,jitter:0,audioLevel:0,totalAudioEnergy:0,insertedSamplesForDeceleration:0,removedSamplesForAcceleration:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0}},r=t.getPeerConnection();if(r)try{let{ssrc:n}=t,{muteState:s}=t;(this._spcStats||(yield r.getStats())).forEach(a=>{if(a.type==="inbound-rtp"){if(a.mediaType===m.AUDIO&&a.ssrc===n.audio&&s.hasAudio){e.audio.packetsReceived=a.packetsReceived,e.audio.bytesReceived=a.bytesReceived,e.audio.packetsLost=a.packetsLost,a.insertedSamplesForDeceleration&&(e.audio.insertedSamplesForDeceleration=a.insertedSamplesForDeceleration),a.removedSamplesForAcceleration&&(e.audio.removedSamplesForAcceleration=a.removedSamplesForAcceleration);let{remoteAudioTrack:c}=t;c.stat.packetsReceived=a.packetsReceived,c.stat.bytesReceived=a.bytesReceived,c.stat.packetsLost=a.packetsLost,a.jitterBufferDelay&&(c.stat.jitterBufferDelay=Math.floor(a.jitterBufferDelay/a.jitterBufferEmittedCount*1e3)),e.hasAudio=!0}else if(a.mediaType===m.VIDEO){if(ue&&a.bytesReceived===0)return;let c;a.ssrc===n.video&&s.hasVideo&&(e.video.packetsReceived=a.packetsReceived,e.video.bytesReceived=a.bytesReceived,e.video.packetsLost=a.packetsLost,e.video.framesReceived=a.framesReceived,e.video.framesDecoded=a.framesDecoded,e.video.fpsDecoded=a.framesPerSecond,e.hasVideo=!0,c=t.remoteVideoTrack,a.decoderImplementation&&(!this._prevDecoderImplementationMap.has(e.userId)||this._prevDecoderImplementationMap.get(e.userId)!==a.decoderImplementation)&&(this._log.info(`${e.userId} decoderImplementation change to ${a.decoderImplementation}`),this._prevDecoderImplementationMap.set(e.userId,a.decoderImplementation))),a.ssrc===n.auxiliary&&s.hasAuxiliary&&(e.auxiliary.packetsReceived=a.packetsReceived,e.auxiliary.bytesReceived=a.bytesReceived,e.auxiliary.packetsLost=a.packetsLost,e.auxiliary.framesReceived=a.framesReceived,e.auxiliary.framesDecoded=a.framesDecoded,e.auxiliary.fpsDecoded=a.framesPerSecond,c=t.remoteAuxiliaryTrack,e.hasAuxiliary=!0),c&&(c.stat.packetsReceived=a.packetsReceived,c.stat.bytesReceived=a.bytesReceived,c.stat.packetsLost=a.packetsLost,c.stat.framesReceived=a.framesReceived,c.stat.framesDecoded=a.framesDecoded,a.jitterBufferDelay&&(c.stat.jitterBufferDelay=Math.floor(a.jitterBufferDelay/a.jitterBufferEmittedCount*1e3)))}}else a.type==="candidate-pair"&&hi(a)&&de(a.currentRoundTripTime)&&(e.rtt=Math.floor(a.currentRoundTripTime*1e3));b(a.frameWidth)||((a.trackIdentifier===t.getMainStreamVideoTrackId()||a.ssrc===n.video)&&(e.video.frameWidth=a.frameWidth,e.video.frameHeight=a.frameHeight,t.remoteVideoTrack.stat.frameWidth=a.frameWidth,t.remoteVideoTrack.stat.frameHeight=a.frameHeight),(a.trackIdentifier===t.getAuxStreamVideoTrackId()||a.ssrc===n.auxiliary)&&(e.auxiliary.frameWidth=a.frameWidth,e.auxiliary.frameHeight=a.frameHeight,t.remoteAuxiliaryTrack.stat.frameWidth=a.frameWidth,t.remoteAuxiliaryTrack.stat.frameHeight=a.frameHeight)),b(a.audioLevel)||(e.audio.audioLevel=a.audioLevel||0,e.audio.totalAudioEnergy=a.totalAudioEnergy||0)}),e.audio.audioLevel===0&&(e.audio.audioLevel=t.remoteAudioTrack.getInternalAudioLevel()||0)}catch(n){this._log.warn(`failed to getStats on receiver connection ${n}`)}return e})}getStats(t,e){return E(this,null,function*(){let r={},n=[];if(this.room.singlePC){let s=this.room.singlePC.getPeerConnection();if(!s)return{senderStats:r,receiverStats:n};let o=yield s.getStats(),a=[],c=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source"]);o.forEach(d=>c.has(d.type)&&a.push(d)),this._spcStats=a}t&&(r=yield this.getSenderStats(t));for(let[s,o]of e){let a=yield this.getReceiverStats(o);n.push(a)}return{senderStats:r,receiverStats:n}})}getDifferenceValue(t,e){if(jt(t))return e;let r=e-t;return r<0?0:r}prepareReport({stats:t,report:e,freezeMap:r}){if(!jt(t.senderStats)){let u={uint32_audio_level:t.senderStats.audio.audioLevel*Vi,uint32_audio_energy:t.senderStats.audio.totalAudioEnergy*1e6,uint32_audio_codec_bitrate:t.senderStats.audio.bytesSent},l=[],h={uint32_video_stream_type:2,uint32_video_codec_fps:t.senderStats.video.framesSent,uint32_video_capture_fps:t.senderStats.video.fpsCapture,uint32_video_width:t.senderStats.video.frameWidth,uint32_video_height:t.senderStats.video.frameHeight,uint32_video_codec_bitrate:t.senderStats.video.bytesSent,uint32_video_enc_fps:t.senderStats.video.framesEncoded};if(l.push(h),t.senderStats.small.bytesSent){let T={uint32_video_stream_type:3,uint32_video_codec_fps:t.senderStats.small.framesSent||0,uint32_video_capture_fps:t.senderStats.small.fpsCapture||0,uint32_video_width:t.senderStats.small.frameWidth||0,uint32_video_height:t.senderStats.small.frameHeight||0,uint32_video_codec_bitrate:t.senderStats.small.bytesSent,uint32_video_enc_fps:t.senderStats.small.framesEncoded||0};l.push(T)}if(t.senderStats.auxiliary.bytesSent){let T={uint32_video_stream_type:7,uint32_video_codec_fps:t.senderStats.auxiliary.framesSent||0,uint32_video_capture_fps:t.senderStats.auxiliary.fpsCapture||0,uint32_video_width:t.senderStats.auxiliary.frameWidth||0,uint32_video_height:t.senderStats.auxiliary.frameHeight||0,uint32_video_codec_bitrate:t.senderStats.auxiliary.bytesSent,uint32_video_enc_fps:t.senderStats.auxiliary.framesEncoded||0};l.push(T)}let I={uint32_bitrate:0,uint32_lost:0,uint32_rtt:t.senderStats.rtt};e.msg_up_stream_info={msg_audio_status:u,msg_video_status:l,msg_network_status:I}}let{statInterval:n}=this;e.msg_down_stream_info=[],t.receiverStats.forEach(u=>{let l={msg_user_info:{str_identifier:u.userId,uint64_tinyid:u.tinyId},msg_network_status:{uint32_rtt:u.rtt,uint32_bitrate:0,uint32_lost:0},msg_audio_status:{},msg_video_status:[]};if(u.hasAudio){let h={uint32_audio_codec_bitrate:u.audio.bytesReceived,uint32_audio_total_bitrate:u.audio.bytesReceived,uint32_audio_level:u.audio.audioLevel*1e8,uint32_audio_energy:u.audio.totalAudioEnergy*1e6,uint32_audio_receive:u.audio.packetsReceived,uint32_audio_origin_lost:u.audio.packetsLost};l.msg_audio_status=h}if(u.hasVideo){let h=r.get(`${u.userId}_${_a}`),I=h?h.duration:0,T={uint32_video_stream_type:2,uint32_video_receive_fps:u.video.framesReceived,uint32_video_width:u.video.frameWidth,uint32_video_height:u.video.frameHeight,uint32_video_codec_bitrate:u.video.bytesReceived,uint32_video_receive:u.video.packetsReceived,uint32_video_origin_lost:u.video.packetsLost,uint32_video_block_time:I,uint32_video_dec_fps:u.video.framesDecoded};l.msg_video_status.push(T)}if(u.hasAuxiliary){let h=r.get(`${u.userId}_${gn}`),I=h?h.duration:0,T={uint32_video_stream_type:7,uint32_video_receive_fps:u.auxiliary.framesReceived,uint32_video_width:u.auxiliary.frameWidth,uint32_video_height:u.auxiliary.frameHeight,uint32_video_codec_bitrate:u.auxiliary.bytesReceived,uint32_video_receive:u.auxiliary.packetsReceived+u.auxiliary.packetsLost,uint32_video_origin_lost:u.auxiliary.packetsLost,uint32_video_block_time:I,uint32_video_dec_fps:u.auxiliary.framesDecoded};l.msg_video_status.push(T)}e.msg_down_stream_info.push(l)});let s=this._prevReport;if(this._prevReport=JSON.parse(JSON.stringify(e)),e.msg_up_stream_info.msg_audio_status&&s.msg_up_stream_info.msg_audio_status){let u=s.msg_up_stream_info.msg_audio_status,l=e.msg_up_stream_info.msg_audio_status,h=this.getDifferenceValue(u.uint32_audio_codec_bitrate,l.uint32_audio_codec_bitrate);l.uint32_audio_codec_bitrate=Math.round(h*8/n),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=l.uint32_audio_codec_bitrate}let o=s.msg_up_stream_info.msg_video_status;e.msg_up_stream_info.msg_video_status.forEach(u=>{let l=o.find($=>$.uint32_video_stream_type===u.uint32_video_stream_type);if(!l||l.uint32_video_codec_bitrate===0){u.uint32_video_codec_bitrate=0,u.uint32_video_enc_fps=0,u.uint32_video_codec_fps=0;return}let h=0,I=0,T=0;l&&u.uint32_video_codec_bitrate>=l.uint32_video_codec_bitrate&&(h=l.uint32_video_codec_bitrate,I=l.uint32_video_enc_fps,T=l.uint32_video_codec_fps);let N=this.getDifferenceValue(h,u.uint32_video_codec_bitrate);u.uint32_video_codec_bitrate=Math.round(N*8/n),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=u.uint32_video_codec_bitrate,u.uint32_video_enc_fps=Math.round(this.getDifferenceValue(I,u.uint32_video_enc_fps)/n),u.uint32_video_codec_fps=Math.round(this.getDifferenceValue(T,u.uint32_video_codec_fps)/n)});let c=e.msg_down_stream_info,d=s.msg_down_stream_info;return c.forEach(u=>{let l=d.find(h=>h.msg_user_info.uint64_tinyid===u.msg_user_info.uint64_tinyid);if(!!l){if(!jt(u.msg_audio_status)&&!jt(l.msg_audio_status)){let h=u.msg_audio_status,I=l.msg_audio_status;h.uint32_audio_origin_lost=this.getDifferenceValue(I.uint32_audio_origin_lost,h.uint32_audio_origin_lost),h.uint32_audio_receive=this.getDifferenceValue(I.uint32_audio_receive,h.uint32_audio_receive),h.uint32_audio_receive+=h.uint32_audio_origin_lost;let T=this.getDifferenceValue(I.uint32_audio_codec_bitrate,h.uint32_audio_codec_bitrate);h.uint32_audio_codec_bitrate=Math.round(T*8/n),h.uint32_audio_total_bitrate=Math.round(T*8/n)}else u.msg_audio_status={};if(u.msg_video_status&&l.msg_video_status){let h=l.msg_video_status;u.msg_video_status=u.msg_video_status.filter(T=>h.find(N=>N.uint32_video_stream_type===T.uint32_video_stream_type)),u.msg_video_status.forEach(T=>{let N=h.find(J=>J.uint32_video_stream_type===T.uint32_video_stream_type),$=N.uint32_video_receive,x=N.uint32_video_origin_lost,F=N.uint32_video_codec_bitrate,ge=N.uint32_video_receive_fps,A=N.uint32_video_dec_fps;T.uint32_video_origin_lost=this.getDifferenceValue(x,T.uint32_video_origin_lost),T.uint32_video_receive=this.getDifferenceValue($,T.uint32_video_receive)+T.uint32_video_origin_lost;let U=this.getDifferenceValue(F,T.uint32_video_codec_bitrate);T.uint32_video_codec_bitrate=Math.round(U*8/n);let y=this.getDifferenceValue(ge,T.uint32_video_receive_fps);T.uint32_video_receive_fps=Math.round(y/n),T.uint32_video_dec_fps=Math.round(this.getDifferenceValue(A,T.uint32_video_dec_fps)/n)})}}}),e}getStatsReport(n){return E(this,arguments,function*({uplinkConnection:t,downlinkConnections:e,freezeMap:r}){let 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},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:0},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},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}}]},o=yield this.getStats(t,e);return JSON.stringify(this._prevReport)==="{}"&&(this._prevReport=JSON.parse(JSON.stringify(s))),this.prepareReport({stats:o,report:s,freezeMap:r}),this._prevReportTime=Date.now(),s})}reset(){this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map}};var rM=_(f());var Wl=_(rt());var td=class extends Wl.default{constructor({signalChannel:e,room:r}){super();p(this,"_room");p(this,"_signalChannel");p(this,"_log");p(this,"_uplinkRTT",0);p(this,"_uplinkLoss",0);p(this,"_downlinkRTT",0);p(this,"_downlinkLoss",0);p(this,"_downlinkPrevStatMap",new Map);p(this,"_downlinkLossAndRTTMap",new Map);p(this,"_interval",-1);p(this,"_uplinkNetworkQuality",0);p(this,"_downlinkNetworkQuality",0);this._room=r,this._signalChannel=e,this._log=O.createLogger({id:"q",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),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){let{rtt:r,loss:n}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._log.info(`downlink network quality change ${this.downlinkNetworkQuality} -> ${e}, rtt: ${r}, loss: ${n}`)}this._downlinkNetworkQuality=e}initialize(){this._signalChannel.on(Q.UPLINK_NETWORK_STATS,e=>{this.handleUplinkNetworkQuality(e)}),this._signalChannel.on(Se.CONNECTION_STATE_CHANGED,this.handleSignalConnectionStateChange.bind(this)),this.start()}handleUplinkNetworkQuality(e){var c,d;if(e.data.code!==0)return;let r=e.data.data;if(r.delay&&this.updateDelay(r.delay),!this._room.uplinkConnection){this.uplinkNetworkQuality=0,this._uplinkLoss=0,this._uplinkRTT=0;return}let n=(d=(c=this._room)==null?void 0:c.uplinkConnection)==null?void 0:d.getPeerConnection();if(n&&this.isPeerConnectionDisconnected(n)){this.uplinkNetworkQuality=6,this._uplinkLoss=0,this._uplinkRTT=0;return}let s=r.expectAudPkg+r.expectVidPkg,o=r.recvAudPkg+r.recvVidPkg,a=s-o;s===0&&o===0||(a<=0?this._uplinkLoss=0:this._uplinkLoss=Math.round(a/s*100),this._uplinkRTT=r.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this._uplinkLoss,this._uplinkRTT))}handleDownlinkNetworkQuality(){return E(this,null,function*(){if(this._room.remotePublishedUserMap.size===0){this.downlinkNetworkQuality=0;return}let e=[...this._room.remotePublishedUserMap.values()],r=e.filter(a=>{var c;return((c=a.getPeerConnection())==null?void 0:c.connectionState)===pe.CONNECTED});if(e.filter(a=>this.isPeerConnectionDisconnected(a.getPeerConnection())).length===e.length){this.downlinkNetworkQuality=6;return}for(let a=0;a<r.length;a++){let c=r[a].getPeerConnection();if(!c)return;let{rtt:d,totalPacketsLost:u,totalPacketsReceived:l}=yield this.getStat(c);if(!this._downlinkPrevStatMap.has(c)){this._downlinkPrevStatMap.set(c,{totalPacketsLost:u,totalPacketsReceived:l});continue}let h=0,I=this._downlinkPrevStatMap.get(c),T=u-I.totalPacketsLost,N=l-I.totalPacketsReceived;T<=0||N<0?h=0:h=Math.round(T/(T+N)*100),this._downlinkPrevStatMap.set(c,{totalPacketsLost:u,totalPacketsReceived:l}),this._downlinkLossAndRTTMap.set(c,{rtt:d,loss:h,userId:r[a].getUserId(),audioDelay:r[a].remoteAudioTrack.stat.end2EndDelay,videoDelay:r[a].remoteVideoTrack.stat.end2EndDelay})}if([...this._downlinkPrevStatMap.keys()].forEach(a=>{this.isPeerConnectionDisconnected(a)&&(this._downlinkPrevStatMap.delete(a),this._downlinkLossAndRTTMap.delete(a))}),this._downlinkLossAndRTTMap.size===0)return;let{rtt:s,loss:o}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._downlinkRTT=s,this._downlinkLoss=o,this.downlinkNetworkQuality=this.getNetworkQuality(o,s)})}getStat(e){return E(this,null,function*(){let r={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!Hi())return r;let n=e.getReceivers();try{for(let s=0;s<n.length;s++)(yield n[s].getStats()).forEach(c=>{c.type==="candidate-pair"&&de(c.currentRoundTripTime)&&(r.rtt=Math.round(c.currentRoundTripTime*1e3)),c.type==="inbound-rtp"&&(c.mediaType===m.AUDIO||c.mediaType===m.VIDEO)&&(r.totalPacketsLost+=c.packetsLost,r.totalPacketsReceived+=c.packetsReceived)});return r}catch(s){return r}})}getAverageLossAndRTT(e){let r={rtt:0,loss:0};return Array.isArray(e)&&e.length>0&&(e.forEach(n=>{r.rtt+=n.rtt,r.loss+=n.loss}),Object.keys(r).forEach(n=>{r[n]=Math.round(r[n]/e.length)})),r}getNetworkQuality(e,r){return e>50||r>500?5:e>30||r>350?4:e>20||r>200?3:e>10||r>100?2:e>=0||r>=0?1:0}handleSignalConnectionStateChange(e){e.state===qe.DISCONNECTED?(this._uplinkRTT=0,this._uplinkLoss=0,this.uplinkNetworkQuality=6):e.state===qe.CONNECTED&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=5)}handleUplinkConnectionStateChange({state:e}){e==="DISCONNECTED"?(this._uplinkLoss=0,this._uplinkRTT=0,this.uplinkNetworkQuality=6):e==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=5)}isPeerConnectionDisconnected(e){return!!(e&&(e.connectionState===pe.DISCONNECTED||e.connectionState===pe.FAILED||e.connectionState===pe.CLOSED))}setUplinkConnection(e){this._room.uplinkConnection=e,this._room.uplinkConnection?this._room.uplinkConnection.on(xu.CONNECTION_STATE_CHANGED,this.handleUplinkConnectionStateChange.bind(this)):(this.uplinkNetworkQuality=0,this._uplinkRTT=0,this._uplinkLoss=0)}start(){if(this._interval!==-1){this._log.info("network quality calculating is already started");return}this._log.debug("start network quality calculating"),this._interval=me.run(vt,()=>{this.handleDownlinkNetworkQuality();let e=[...this._downlinkLossAndRTTMap.values()];C.emit(S.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this._uplinkRTT,loss:this._uplinkLoss},downlinks:e}),this.emit(td.EVENT_NETWORK_QUALITY,{uplinkNetworkQuality:this.uplinkNetworkQuality,downlinkNetworkQuality:this.downlinkNetworkQuality,uplinkRTT:this._uplinkRTT,uplinkLoss:this._uplinkLoss,downlinkRTT:this._downlinkRTT,downlinkLoss:this._downlinkLoss,downlinkInfo:e})},{delay:2e3})}stop(){this._log.info("stop network quality calculating"),this._interval!==-1&&(me.clearTask(this._interval),this._interval=-1),this._downlinkLossAndRTTMap.clear(),this._downlinkPrevStatMap.clear()}updateDelay(e){let{tinyIdToUserIdMap:r}=this._room;e.forEach(({srcTinyId:n,videoDelay:s,audioDelay:o})=>{let a=r.get(n);if(a){let c=this._room.remotePublishedUserMap.get(a);c==null||c.setDelay({videoDelay:s,audioDelay:o})}})}},Qi=td;p(Qi,"EVENT_NETWORK_QUALITY","0");var Mk=_(f(),1);var bM=_(f(),1);var cM=_(f(),1);var ei=new WeakMap;function Xn({settings:i={retries:5,timeout:2e3},onError:t,onRetrying:e,onRetryFailed:r}){return function(n,s,o){let a=Dt({retryFunction:o.value,settings:i,onError(c,d,u){t&&t.call(this,c,()=>{var l;(l=ei.get(n))!=null&&l.has(s)?d():u(c)},u)},onRetrying:(c,d)=>{var u;ce(e)&&e(c,d),(u=ei.get(n))!=null&&u.has(s)&&(ei.get(n).get(s).stopRetry=d)},onRetryFailed:r});return o.value=function(...c){let d=ei.get(n);return d?d.set(s,{args:c}):ei.set(n,new Map([[s,{args:c}]])),a.apply(this,c).finally(()=>{var u;return(u=ei.get(n))==null?void 0:u.delete(s)})},o}}function zn({fnName:i,callback:t,validateArgs:e=!0}){return function(r,n,s){let o=s.value;return s.value=function(...a){var c,d;if((c=ei.get(r))!=null&&c.has(i)){let{stopRetry:u,args:l}=ei.get(r).get(i),h=!0;if(e){for(let I of l)if(!a.find(T=>T===I)){h=!1;break}}h&&(t&&t.apply(this,a),u&&u(),(d=ei.get(r))==null||d.delete(i))}return o.apply(this,a)},s}}function Af({fn:i,context:t}){return function(...e){try{let r=i.apply(t||this,e);return yn(r)?r.catch(n=>O.error(`${i.name}() error observed ${n}`)):r}catch(r){O.error(`${i.name}() error observed ${r}`)}}}var Ro=class{constructor(t){this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0};this._apiSuccessRateMap=new Map;this._eventMap=new Map;this._frameWorkType=t.frameWorkType||30,this._component=t.component||0,this.connectionType=t.connectionType||1,this._language=t.language||0,this._room=t.room,this._keyPrefix="key_point",this._log=O.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(e=>{e.startsWith("handle")&&ce(this[e])&&(this[e]=Af({fn:this[e],context:this}))}),this.initData(),this.installEvents(),this._intervalId=me.run(vt,this.setStorage.bind(this),{delay:2e4})}get _storageKey(){return`${this._keyPrefix}_${this._room.userId}`}initData(){this._firstPublishedUserList=[],this._networkQuality={totalUplinkRTT:0,totalUplinkLoss:0,count:0,totalDownlinkRTTAndLossMap:new Map},this._basicInfo={string_sdk_version:$e,uint32_os_type:15,string_device_name:"",string_http_user_agent:navigator.userAgent,string_os_version:"",uint32_avg_rtt:0,uint32_avg_up_loss:0,uint32_scene:this._room.scene==="live"?1:0,uint32_joining_duration:0,uint32_networkType:oi[Bs()],uint32_framework:this._frameWorkType,uint32_component:this._component,uint32_connection_type:this.connectionType,uint32_caller_coding_language:this._language,string_domain:location.hostname},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._localStreamStat={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._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,this._apiSuccessRateMap.clear()}addEvent(t,e){return this._eventMap.set(t,e),C.on(t,e),this}installEvents(){this._room.once("banned",()=>this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})),this.addEvent(S.JOIN_START,this.handleJoinStart).addEvent(S.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(S.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(S.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(S.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(S.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(S.JOIN_FAILED,this.handleJoinFailed).addEvent(S.LEAVE_START,this.handleLeaveStart).addEvent(S.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(S.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(S.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(S.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(S.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(S.PUBLISH_START,this.handlePublishStart).addEvent(S.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(S.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(S.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(S.PLAY_TRACK_START,this.handlePlayStart).addEvent(S.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(S.PLAYER_STATE_CHANGED,({track:t,state:e,type:r})=>{!ui(t)||!this.hitTest(t.room)||e==="PLAYING"&&(r===m.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))}).addEvent(S.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(S.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(S.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(S.REMOTE_PUBLISH_STATE_CHANGED,({room:t,prevMuteState:e,muteState:r})=>{if(!this.hitTest(t))return;let n=e.hasAudio||e.hasVideo||e.hasSmall,s=e.hasAuxiliary,o=r.hasAudio||r.hasVideo||r.hasSmall,a=r.hasAuxiliary;!n&&o&&this.handleRemoteStreamAdded(r.userId,"main"),!s&&a&&this.handleRemoteStreamAdded(r.userId,"auxiliary")}).addEvent(S.API_SUCCESS_RATE,this.handleAPISuccessRate)}uninstallEvents(){this._eventMap.forEach((t,e)=>C.off(e,t)),this._eventMap.clear()}destroy(){this.uninstallEvents(),me.clearTask(this._intervalId)}handleJoinStart(t){this.hitTest(t.room)&&(this._pathJoinRoom.uint64_start_time===0&&(this._pathJoinRoom.uint64_start_time=Date.now(),this.checkStorage()),t.params&&(b(t.params.frameWorkType)||(this._frameWorkType=t.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),b(t.params.component)||(this._component=t.params.component,this._basicInfo.uint32_component=this._component),b(t.params.language)||(this._language=t.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleSignalConnectionStart({room:t}){this.hitTest(t)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time=Date.now())}handleSignalConnectionEnd({room:t,error:e}){this.hitTest(t)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time=Date.now(),e&&(this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret=e instanceof M?Number(e.getExtraCode()||e.getCode()):v.UNKNOWN,this._pathJoinRoom.int32_end_ret=2))}handleJoinSendCMD(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now())}handleJoinReceivedCMDResponce(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=t.code,t.code!==0&&(this._pathJoinRoom.int32_end_ret=3))}handleJoinSuccess(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_end_time===0&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=t.room.getSignalInfo())}handleJoinFailed({room:t}){this.hitTest(t)&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret===0&&(this._pathJoinRoom.int32_end_ret=3),setTimeout(()=>{this.report()}))}handleReceivedPublishUserList(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_recv_userlist_time===0&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=t.publishedUserList||[])}handleSendFirstVideoFrame({room:t}){!this.hitTest(t)||this._pathJoinRoom.uint64_send_first_video_frame_time===0&&this._pathJoinRoom.uint64_start_time!==0&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now())}handleLeaveStart(t){this.hitTest(t.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(t){this.hitTest(t.room)&&this._pathLeaveRoom.uint64_end_time===0&&(this._pathLeaveRoom.uint64_end_time=Date.now(),this._pathJoinRoom.uint64_end_time!==0?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(t){this.hitTest(t.room)&&(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(t,e){var n;let r=`${t}_${e}`;if(!this._remoteStreamStatMap.has(r)){let s={userId:t,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:ee(w({},Cf),{msg_user_info:new qn({userId:t,tinyId:(n=this._room.remotePublishedUserMap.get(t))==null?void 0:n.tinyId,role:20})})};s.statsToReport.uint32_stream_type=e==="main"?2:7,this._remoteStreamStatMap.set(r,s)}}handleSubscribeStart({room:t,remotePublishedUser:e,streamType:r,subscribeState:n}){if(!this.hitTest(t))return;let{userId:s,tinyId:o,role:a}=e,c=new qn({userId:s,tinyId:o,role:a==="anchor"?20:21}),d=Date.now(),u=`${s}_${r}`,l=this._remoteStreamStatMap.get(u);l&&l.subscribeStartTime===0&&(l.subscribeStartTime=d),r==="main"?(e.muteState.hasVideo&&(n.video||n.smallVideo)&&!this._pathMainVideoMap.has(u)&&this._pathMainVideoMap.set(u,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:s,sendSubscribeCMDTime:d}),e.muteState.hasAudio&&n.audio&&!this._pathMainAudioMap.has(u)&&this._pathMainAudioMap.set(u,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:s,sendSubscribeCMDTime:d})):e.muteState.hasAuxiliary&&n.auxiliary&&!this._pathAuxiliaryMap.has(u)&&this._pathAuxiliaryMap.set(u,{sendSubscribeCMDTime:d})}handleSubscribed({room:t,remotePublishedUser:e,streamType:r}){if(this.hitTest(t)){let n=`${e.userId}_${r}`,s=this._remoteStreamStatMap.get(n);s&&s.subscribedTime===0&&(s.subscribedTime=Date.now())}}handlePlayStart({track:t}){if(!ui(t)||!this.hitTest(t.room))return;let e=`${t.userId}_${t.streamType}`,r=this._remoteStreamStatMap.get(e);(r==null?void 0:r.playStreamTime)===0&&(r.playStreamTime=Date.now())}handleVideoLoadedData({track:t}){if(!ui(t)||!this.hitTest(t.room))return;let e=`${t.userId}_${t.streamType}`,r=this._pathMainVideoMap.get(e);r&&r.statsToReport.uint64_combine_first_frame_time===0&&(r.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(t){let e=`${t.userId}_${t.streamType}`,r=Date.now(),n=this._pathMainVideoMap.get(e),s=this._remoteStreamStatMap.get(e);if(n&&(n.statsToReport.uint64_render_first_frame_time===0&&(n.statsToReport.uint64_render_first_frame_time=r),s)){let{statsToReport:a,playStreamTime:c,subscribedTime:d}=s;a.uint32_video_render_first===0&&c-d<=100&&(a.uint32_video_render_first=r-n.sendSubscribeCMDTime)}let o=this._pathAuxiliaryMap.get(e);if(o&&s){let{statsToReport:a,playStreamTime:c,subscribedTime:d}=s;a.uint32_video_render_first===0&&c-d<=100&&(a.uint32_video_render_first=r-o.sendSubscribeCMDTime)}}handleAudioPlaying(t){let e=`${t.userId}_${t.streamType}`,r=this._pathMainAudioMap.get(e);r&&r.statsToReport.uint64_play_first_frame_time===0&&(r.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(t){this.hitTest(t.room)&&(this._networkQuality.totalUplinkLoss+=t.uplink.loss,this._networkQuality.totalUplinkRTT+=t.uplink.rtt,this._networkQuality.count++,t.downlinks.forEach(({rtt:e,loss:r,userId:n,videoDelay:s,audioDelay:o})=>{let a=this._networkQuality.totalDownlinkRTTAndLossMap.get(n);if(a)a.totalRTT+=e,a.totalLoss+=r,s&&(a.totalVideoDelay=(a.totalVideoDelay||0)+s,a.videoDelayCount=(a.videoDelayCount||0)+1),o&&(a.totalAudioDelay=(a.totalAudioDelay||0)+o,a.audioDelayCount=(a.audioDelayCount||0)+1),a.count++;else{let c,d,u,l;s&&(d=s,u=1),o&&(c=o,l=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(n,{totalRTT:e,totalLoss:r,count:1,totalAudioDelay:c,totalVideoDelay:d,audioDelayCount:l,videoDelayCount:u})}}))}handleHeartbeatStats(t){if(this.hitTest(t.room)){let{msg_up_stream_info:e,msg_down_stream_info:r}=t.report;if(e.msg_video_status[0]){let{uint32_video_codec_bitrate:n,uint32_video_enc_fps:s,uint32_video_width:o,uint32_video_height:a}=e.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=n,this._localStreamStat.totalVideoFPS+=s,this._localStreamStat.totalVideoWidth+=o,this._localStreamStat.totalVideoHeight+=a,this._localStreamStat.videoCount++}if(e.msg_audio_status){let{uint32_audio_level:n}=e.msg_audio_status;Math.floor(n/Vi*100)>0&&(this._localStreamStat.totalAudioLevel+=n/Vi,this._localStreamStat.audioLevelCount++)}r.forEach(n=>{let{msg_user_info:s,msg_audio_status:o,msg_video_status:a}=n,c=s.str_identifier,d=this._room.remotePublishedUserMap.get(c);if(a.forEach(u=>{let l=u.uint32_video_stream_type===2,h=u.uint32_video_stream_type===7,I=`${c}_${l?"main":"auxiliary"}`,T=this._remoteStreamStatMap.get(I);if(!!T&&(l&&(d==null?void 0:d.remoteVideoTrack.isSubscribed)||h&&(d==null?void 0:d.remoteAuxiliaryTrack))){T.totalVideoFPS+=u.uint32_video_receive_fps,T.totalVideoBitrate+=u.uint32_video_codec_bitrate,T.videoCount++,T.statsToReport.uint32_video_width===0&&(T.statsToReport.uint32_video_width=u.uint32_video_width),T.statsToReport.uint32_video_height===0&&(T.statsToReport.uint32_video_height=u.uint32_video_height);let N=l?d.remoteVideoTrack:d.remoteAuxiliaryTrack;N.stat.jitterBufferDelay&&(T.videoJitterBufferDelay=N.stat.jitterBufferDelay),N.stat.framesReceived&&(T.statsToReport.uint32_video_consume_render_rate=Math.floor(N.stat.framesDecoded/N.stat.framesReceived*ss(10,6)))}}),o){let u=`${c}_${"main"}`,l=this._remoteStreamStatMap.get(u);this._remoteStreamStatMap.has(u)&&l&&(d==null?void 0:d.remoteAudioTrack.isSubscribed)&&(l.totalAudioBitrate+=o.uint32_audio_codec_bitrate,l.audioCount++,d.remoteAudioTrack.stat.jitterBufferDelay&&(l.audioJitterBufferDelay=d.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(o.uint32_audio_level/Vi*100)>0&&(l.totalAudioLevel+=o.uint32_audio_level/Vi,l.audioLevelCount++))}})}}handlePublishStart({room:t}){this.hitTest(t)&&this._localStreamStat.publishStartTime===0&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart({track:t}){t.mediaType===1&&this._pathJoinRoom.uint64_init_audio_start_time===0&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),t.mediaType===4&&this._pathJoinRoom.uint64_init_camera_start_time===0&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess({track:t}){t.mediaType===1&&this._pathJoinRoom.uint64_init_audio_end_time===0&&(this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),t.mediaType===4&&this._pathJoinRoom.uint64_init_camera_end_time===0&&(this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed({track:t,error:e}){let r={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5},n=e instanceof M?e.getExtraCode()||e.getCode():r[e.name]||v.UNKNOWN;t.mediaType===1&&this._pathJoinRoom.uint64_init_audio_end_time===0&&(this._pathJoinRoom.int32_init_audio_ret=n,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),t.mediaType===4&&this._pathJoinRoom.uint64_init_camera_end_time===0&&(this._pathJoinRoom.int32_init_camera_ret=n,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleAPISuccessRate({room:t,apiName:e,error:r,cost:n}){if(!this.hitTest(t))return;let s=Kl[e],o={uint32_function_request_type:s,uint32_avg_value:0,uint32_max_value:0,uint32_request_count:1,uint32_success_count:0,msg_error_code:[]};if(r){let c=v.UNKNOWN;r instanceof M&&(c=r.extraCode||r.code),_e.uploadEvent({log:`stat-${e}-failed-${c}`,userId:this._room.userId,error:r});let d={int32_error_code:c,error_count:1};o.msg_error_code.push(d)}else de(n)&&(o.uint32_avg_value=n,o.uint32_max_value=n,o.uint32_success_count=1);let a=this._apiSuccessRateMap.get(s);a?(a.uint32_success_count+o.uint32_success_count>0&&(a.uint32_avg_value=(a.uint32_avg_value*a.uint32_success_count+o.uint32_avg_value)/(a.uint32_success_count+o.uint32_success_count)),a.uint32_max_value=Math.max(a.uint32_max_value,o.uint32_max_value),a.uint32_request_count+=1,a.uint32_success_count=a.uint32_success_count+o.uint32_success_count,o.msg_error_code.forEach(c=>{let d=a.msg_error_code.find(u=>u.int32_error_code===c.int32_error_code);d?d.error_count+=1:a.msg_error_code.push(c)})):this._apiSuccessRateMap.set(s,o)}hasVideoFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&Sr)>=0}hasAudioFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&gr)>=0}hasAuxFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&Tn)>=0}hitTest(t){return t===this._room}checkStorage(){return E(this,null,function*(){try{let t=br.getItem(this._storageKey);t&&(yield this.upload(t),br.deleteItem(this._storageKey))}catch(t){this._log.warn(t)}})}setStorage(){this.prepareReport();let t=this.getReportData();t.msg_path_enter_room.uint64_start_time!==0&&br.setItem(this._storageKey,t)}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._localStreamStat.videoCount>0){this._localStreamStat.statsToReport.uint32_video_big_capture_fps=Math.floor(this._localStreamStat.totalVideoFPS/this._localStreamStat.videoCount),this._localStreamStat.statsToReport.uint32_video_big_bitrate=Math.floor(this._localStreamStat.totalVideoBitrate/this._localStreamStat.videoCount);let t=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),e=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=t<<16|e}this._localStreamStat.audioLevelCount>0&&(this._localStreamStat.statsToReport.uint32_audio_capture_db=Math.floor(this._localStreamStat.totalAudioLevel/this._localStreamStat.audioLevelCount*100)),this._remoteStreamStatMap.forEach((t,e)=>{let{userId:r}=t,n=this._networkQuality.totalDownlinkRTTAndLossMap.get(r);if(n){let{totalLoss:u,count:l,audioDelayCount:h,videoDelayCount:I,totalAudioDelay:T,totalVideoDelay:N}=n;t.statsToReport.uint32_avg_down_loss=Math.floor(u/l),h&&T&&(t.statsToReport.uint32_audio_network_p2p_delay=Math.floor(T/h),t.audioJitterBufferDelay&&(t.statsToReport.uint32_p2p_delay=Math.floor(t.statsToReport.uint32_audio_network_p2p_delay+t.audioJitterBufferDelay))),I&&N&&(t.statsToReport.uint32_video_network_p2p_delay=Math.floor(N/I))}t.videoCount>0&&(t.statsToReport.uint32_video_avg_fps=Math.floor(t.totalVideoFPS/t.videoCount),t.statsToReport.uint32_video_avg_bitrate=Math.floor(t.totalVideoBitrate/t.videoCount)),t.audioCount>0&&(t.statsToReport.uint32_audio_recv_bitrate=t.statsToReport.uint32_audio_bitrate=Math.floor(t.totalAudioBitrate/t.audioCount)),t.audioLevelCount>0&&(t.statsToReport.uint32_audio_play_db=Math.floor(t.totalAudioLevel/t.audioLevelCount*100));let{callDurationCalculator:s}=this._room;s&&(t.statsToReport.uint32_audio_play_time=s.getDuration(e,m.AUDIO),t.statsToReport.uint32_video_play_time=s.getDuration(e,m.VIDEO)),t.statsToReport.uint32_video_render_first=Math.min(t.statsToReport.uint32_video_render_first,Zi);let{badCaseDetector:o}=this._room,{dataFreeze:a,count:c}=o.getDataFreezeDuration(e),{renderFreeze:d}=o.getRenderFreezeDuration(e);t.statsToReport.uint32_video_block_count=c,t.statsToReport.uint32_video_block_time=Math.min(a,t.statsToReport.uint32_video_play_time),t.statsToReport.uint32_video_external_block_time=Math.min(d,t.statsToReport.uint32_video_play_time),o.isBlackStream(e)&&t.statsToReport.uint32_video_avg_fps===0?t.statsToReport.uint32_video_black_screen_subjective=1:t.statsToReport.uint32_video_black_screen_subjective=0,(t.subscribeStartTime===0||t.subscribeStartTime-t.streamAddedTime>100||t.playStreamTime===0)&&(this._pathMainAudioMap.delete(e),this._pathMainVideoMap.delete(e),t.statsToReport.uint32_video_render_first=0)}),this._pathMainAudioMap.forEach((t,e)=>{if(!this.hasAudioFlag(t.userId)){this._pathMainAudioMap.delete(e);return}t.statsToReport.uint64_play_first_frame_time-t.statsToReport.uint64_start_enter_time>Zi&&(t.statsToReport.uint64_play_first_frame_time=t.statsToReport.uint64_start_enter_time+Zi)}),this._pathMainVideoMap.forEach((t,e)=>{if(!this.hasVideoFlag(t.userId)){this._pathMainVideoMap.delete(e);return}t.statsToReport.uint64_render_first_frame_time-t.statsToReport.uint64_start_enter_time>Zi&&(t.statsToReport.uint64_render_first_frame_time=t.statsToReport.uint64_start_enter_time+Zi)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>Zi&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+Zi)}getReportData(){return{uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new qn({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:bn(this._signalInfo.relayIp),uint32_client_ip:bn(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*2147483648),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._remoteStreamStatMap.values()].map(e=>e.statsToReport),str_room_name:String(this._room.roomId||0),msg_path_recv_audio:[...this._pathMainAudioMap.values()].map(e=>e.statsToReport),uint32_info_client_ip:bn(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,msg_function_request_stats:[...this._apiSuccessRateMap.values()]}}report(){return E(this,null,function*(){try{this.prepareReport();let t=this.getReportData();yield this.upload(t),br.deleteItem(this._storageKey),this.initData()}catch(t){this._log.warn(t)}})}upload(t){return E(this,null,function*(){if(mt||t.msg_path_enter_room.uint64_start_time===0||[Ds,ca,da].findIndex(s=>s===location.host)>=0)return;let e=Number(this._room.sdkAppId),r=wi(e,Li.KEY_POINT),n=yield pi({url:r,body:JSON.stringify(t)});if(n.data!=="ok")throw`key point upload failed: ${n.data}`})}setConnectionType(t){this.connectionType=t,this._basicInfo.uint32_connection_type=t}};H([Xn({settings:{timeout:500,retries:3}})],Ro.prototype,"upload",1);var Zi=5e3,Cf={msg_user_info:null,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,uint32_video_consume_render_rate:0},qn=class{constructor(t){this.str_identifier=String(t.userId),this.str_tinyid=String(t.tinyId||0),this.uint32_role=t.role}},Kl=(g=>(g[g.enterRoom=50001]="enterRoom",g[g.exitRoom=50002]="exitRoom",g[g.switchRole=50003]="switchRole",g[g.destroy=50004]="destroy",g[g.startLocalAudio=50005]="startLocalAudio",g[g.updateLocalAudio=50006]="updateLocalAudio",g[g.stopLocalAudio=50007]="stopLocalAudio",g[g.startLocalVideo=50008]="startLocalVideo",g[g.updateLocalVideo=50009]="updateLocalVideo",g[g.stopLocalVideo=50010]="stopLocalVideo",g[g.startScreenShare=50011]="startScreenShare",g[g.updateScreenShare=50012]="updateScreenShare",g[g.stopScreenShare=50013]="stopScreenShare",g[g.enableAudioVolumeEvaluation=50014]="enableAudioVolumeEvaluation",g[g.startRemoteVideo=50015]="startRemoteVideo",g[g.updateRemoteVideo=50016]="updateRemoteVideo",g[g.stopRemoteVideo=50017]="stopRemoteVideo",g[g.muteRemoteAudio=50018]="muteRemoteAudio",g[g.setRemoteAudioVolume=50019]="setRemoteAudioVolume",g[g.startMixTranscode=50020]="startMixTranscode",g[g.stopMixTranscode=50021]="stopMixTranscode",g[g.startPublishCDNStream=50022]="startPublishCDNStream",g[g.stopPublishCDNStream=50023]="stopPublishCDNStream",g[g.PeerConnectionConnect=50024]="PeerConnectionConnect",g[g.PeerConnectionReconnect=50025]="PeerConnectionReconnect",g[g.WebsocketConnect=50026]="WebsocketConnect",g[g.WebsocketReconnect=50027]="WebsocketReconnect",g[g.schedule=50028]="schedule",g[g.SPCConnect=50029]="SPCConnect",g[g.SPCReconnect=50030]="SPCReconnect",g))(Kl||{}),jl=Ro;var HM=_(f(),1);var MM=_(f(),1);var id=class{constructor(){p(this,"_startTime");p(this,"_endTime");this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=z())}stop(){this._endTime===0&&(this._endTime=z())}getDuration(){return this._endTime===0?z()-this._startTime:this._endTime-this._startTime}get endTime(){return this._endTime}},Gr=id;var rd=class{constructor(t){p(this,"_room",null);p(this,"_durationMap");p(this,"_eventMap",new Map);this._room=t.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(S.SUBSCRIBE_SUCCESS,this.handleSubscribed).set(S.UNSUBSCRIBE_SUCCESS,this.handleStreamStopped).set(S.REMOTE_PUBLISH_STATE_CHANGED,({room:t,prevMuteState:e,muteState:r})=>{var o;let{userId:n}=r;if(!this.hitTest(t))return;e.hasAudio&&!r.hasAudio&&this.stopDurationItem(`${n}_${"main"}`,m.AUDIO),e.hasVideo&&!r.hasVideo&&this.stopDurationItem(`${n}_${"main"}`,m.VIDEO),e.hasAuxiliary&&!r.hasAuxiliary&&this.stopDurationItem(`${n}_${"auxiliary"}`,m.VIDEO);let s=(o=this._room)==null?void 0:o.remotePublishedUserMap.get(n);!s||(!e.hasAudio&&r.hasAudio&&s.remoteAudioTrack.isSubscribed&&this.addDuractionItem(n,m.AUDIO,"main"),!e.hasVideo&&r.hasVideo&&s.remoteVideoTrack.isSubscribed&&this.addDuractionItem(n,m.VIDEO,"main"),!e.hasAuxiliary&&r.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(n,m.VIDEO,"auxiliary"))}),this._eventMap.forEach((t,e)=>C.on(e,t,this))}uninstallEvents(){this._eventMap.forEach((t,e)=>C.off(e,t,this)),this._eventMap.clear()}handleSubscribed({room:t,streamType:e,remotePublishedUser:r}){if(!this.hitTest(t))return;let{userId:n}=r,s=`${n}_${e}`;if(r.muteState.hasAudio&&e==="main")if(r.remoteAudioTrack.isSubscribed){let o=new Gr,a=this._durationMap.get(s);a?this.isRecording(a.audio)||a.audio.push(o):this._durationMap.set(s,{userId:n,type:e,audio:[o],video:[]})}else this.stopDurationItem(s,m.AUDIO);if(r.muteState.hasVideo||r.muteState.hasAuxiliary)if(r.remoteVideoTrack.isSubscribed||r.remoteAuxiliaryTrack.isSubscribed){let o=new Gr,a=this._durationMap.get(s);a?this.isRecording(a.video)||a.video.push(o):this._durationMap.set(s,{userId:n,type:e,audio:[],video:[o]})}else this.stopDurationItem(s,m.VIDEO)}handleStreamStopped({room:t,streamType:e,remotePublishedUser:r}){if(!this.hitTest(t))return;let{userId:n}=r,s=`${n}_${e}`;this.stopDurationItem(s,m.AUDIO),this.stopDurationItem(s,m.VIDEO)}isRecording(t){return t.findIndex(e=>e.endTime===0)>=0}addDuractionItem(t,e,r){let n=`${t}_${r}`,s=new Gr,o=this._durationMap.get(n);o?this.isRecording(o[e])||o[e].push(s):this._durationMap.set(n,{userId:t,type:r,audio:e===m.AUDIO?[s]:[],video:e===m.AUDIO?[]:[s]})}stopDurationItem(t,e){if(this._durationMap.has(t)){let n=this._durationMap.get(t)[e].find(s=>s.endTime===0);n&&n.stop()}}hitTest(t){return this._room===t}getDuration(t,e){return this._durationMap.has(t)?this._durationMap.get(t)[e].reduce((n,s)=>n+s.getDuration(),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},Jl=rd;var tL=_(f(),1);var nd=class{constructor(t){p(this,"_room");p(this,"_renderFreezeMap",new Map);p(this,"_isVideoPlayingEventFiredMap",new Map);p(this,"_dataFreezeMap",new Map);p(this,"_monitorFreezeData",new Map);p(this,"_eventMap",new Map);this._room=t.room,this.installEvents()}installEvents(){this._eventMap.set(S.LEAVE_SUCCESS,({room:t})=>{this.hitTest(t)&&this.stop()}).set(S.PLAY_TRACK_START,this.onPlayTrackStart).set(S.UNSUBSCRIBE_SUCCESS,({room:t,streamType:e,remotePublishedUser:r})=>{if(!this.hitTest(t))return;let{userId:n}=r,s=`${n}_${e}`;this.stopDataFreeze({key:s,userId:n,type:e})}).set(S.REMOTE_PUBLISH_STATE_CHANGED,({room:t,prevMuteState:e,muteState:r})=>{if(!this.hitTest(t))return;let{userId:n}=r;if(e.hasVideo&&!r.hasVideo){let s="main",o=`${r.userId}_${s}`;this.stopDataFreeze({key:o,userId:n,type:s})}if(e.hasAuxiliary&&!r.hasAuxiliary){let s="auxiliary",o=`${r.userId}_${s}`;this.stopDataFreeze({key:o,userId:n,type:s})}}).set(S.PLAYER_STATE_CHANGED,({track:t,state:e,reason:r,type:n})=>{if(!(!ui(t)||!this.hitTest(t.room)||n!==m.VIDEO)){if(e==="PLAYING"){let s=`${t.userId}_${t.streamType}`;this._isVideoPlayingEventFiredMap.set(s,!0)}r===m.MUTE?this.onVideoTrackMuted(t):r===m.UNMUTE&&this.onVideoTrackUnmuted(t)}}).set(S.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach((t,e)=>C.on(e,t,this))}uninstallEvents(){this._eventMap.forEach((t,e)=>C.off(e,t,this)),this._eventMap.clear()}stop(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}onVideoTrackMuted(t){if(!t.isSubscribed)return;let{userId:e,streamType:r}=t,n=`${e}_${r}`,s=this._dataFreezeMap.get(n),o=new Gr;s?s.durationItemList.push(o):this._dataFreezeMap.set(n,{userId:e,type:r,durationItemList:[o],isFreezing(){let a=this.durationItemList[this.durationItemList.length-1];return a&&a.endTime===0}})}onVideoTrackUnmuted(t){if(!t.isSubscribed)return;let{userId:e,streamType:r}=t,n=`${e}_${r}`;this.stopDataFreeze({key:n,userId:e,type:r})}onHearBeatReport({room:t,report:e}){!this.hitTest(t)||e.msg_down_stream_info.forEach(r=>{let n=this._room.remotePublishedUserMap.get(r.msg_user_info.str_identifier);if(!n)return;let{userId:s,muteState:o}=n;r.msg_video_status.forEach(a=>{a.uint32_video_stream_type===2&&o.hasVideo&&!o.videoMuted&&n.remoteVideoTrack.isSubscribed&&this.handleRenderFreeze({userId:s,fps:a.uint32_video_dec_fps,type:"main"}),a.uint32_video_stream_type===7&&o.hasAuxiliary&&n.remoteAuxiliaryTrack.isSubscribed&&this.handleRenderFreeze({userId:s,fps:a.uint32_video_dec_fps,type:"auxiliary"})})})}stopDataFreeze({key:t,userId:e,type:r}){let n=this._dataFreezeMap.get(t);if(!n||!n.isFreezing())return;let s=n.durationItemList[n.durationItemList.length-1];s.stop();let o=s.getDuration();o>Us?this._monitorFreezeData.set(t,{userId:e,type:r,duration:o}):n.durationItemList.pop()}getTotalDuration(t){return t.reduce((e,r)=>{let n=r.getDuration();return e+Math.min(n,5e3)},0)}handleRenderFreeze(n){return E(this,arguments,function*({userId:t,fps:e,type:r}){let s=`${t}_${r}`,o=this._renderFreezeMap.get(s);if(e<=2){let a=z();o&&!o.isFreeze&&(o.freezeTimeline.push({startTime:a,endTime:0}),o.isFreeze=!0),o||this._renderFreezeMap.set(s,{userId:t,type:r,isFreeze:!0,freezeTimeline:[{startTime:a,endTime:0}],renderFreezeTotal:0})}else if(o&&o.isFreeze){o.isFreeze=!1;let a=o.freezeTimeline.pop();if(a){a.endTime=z();let c=a.endTime-a.startTime;o.freezeTimeline.push(a),o.renderFreezeTotal+=Math.min(5e3,c)}}})}onPlayTrackStart({track:t}){if(!ui(t)||!this.hitTest(t.room)||t.kind!==m.VIDEO||t.hasFlag)return;let e=`${t.userId}_${t.streamType}`;this._isVideoPlayingEventFiredMap.has(e)||this._isVideoPlayingEventFiredMap.set(e,!1)}getDataFreezeDuration(t){let e={dataFreeze:0,count:0},r=this._dataFreezeMap.get(t);if(r){if(r.isFreezing()){let n=r.durationItemList[r.durationItemList.length-1];n.stop(),n.getDuration()<Us&&r.durationItemList.pop()}e.dataFreeze=this.getTotalDuration(r.durationItemList),e.count=r.durationItemList.length}return e}getRenderFreezeDuration(t){let e=this._renderFreezeMap.get(t),r=0,n=0;if(e)if(!e.isFreeze)r=e.renderFreezeTotal;else{let s=z(),o=e.freezeTimeline[e.freezeTimeline.length-1],a=s-o.startTime;r=e.renderFreezeTotal+Math.min(a,5e3),n=e.freezeTimeline.length}return{renderFreeze:r,count:n}}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(t){return this._isVideoPlayingEventFiredMap.has(t)?!this._isVideoPlayingEventFiredMap.get(t):!1}resetMonitor(){this._monitorFreezeData.clear()}hitTest(t){return t===this._room}destroy(){this.uninstallEvents()}},Yl=nd;var EL=_(f(),1);var zl=_(sd(),1);var od=class{constructor(t){p(this,"_room");p(this,"_log");p(this,"_config",null);p(this,"_data");p(this,"_remoteVideoTrackMap",new Map);this._room=t,this._log=O.createLogger({id:"mix",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this.installEvents()}get isPresetLayoutMode(){return this._config&&this._config.mode===di.MODE.PRESET_LAYOUT}get isMixing(){return!!this._data}installEvents(){C.on(S.REMOTE_TRACK_SUBSCRIBED,this.onSubscribed,this),C.on(S.REMOTE_TRACK_UNSUBSCRIBED,this.onUnSubscribed,this),C.on(S.REMOTE_PUBLISH_STATE_CHANGED,this.onRemotePublishedChanged,this)}uninstallEvents(){C.off(S.REMOTE_TRACK_SUBSCRIBED,this.onSubscribed,this),C.off(S.REMOTE_TRACK_UNSUBSCRIBED,this.onUnSubscribed,this),C.off(S.REMOTE_PUBLISH_STATE_CHANGED,this.onRemotePublishedChanged,this)}reset(){this.uninstallEvents(),this._config=null}onSubscribed({track:t}){t.room!==this._room||t.kind!==m.VIDEO||(this._remoteVideoTrackMap.set(`${t.userId}_${t.streamType}`,!1),this.isMixing&&this.hasAvailablePlaceHolder()&&this._config&&this.startMixTranscode(this._config))}onUnSubscribed({track:t}){t.room!==this._room||t.kind!==m.VIDEO||this.handleRemoteTrackUnavailable(`${t.userId}_${t.streamType}`)}onRemotePublishedChanged({room:t,prevMuteState:e,muteState:r}){t===this._room&&(e.hasVideo&&!r.hasVideo&&this.handleRemoteTrackUnavailable(`${r.userId}_${"main"}`),e.hasAuxiliary&&!r.hasAuxiliary&&this.handleRemoteTrackUnavailable(`${r.userId}_${"auxiliary"}`))}handleRemoteTrackUnavailable(t){if(this._remoteVideoTrackMap.has(t)){let e=this._remoteVideoTrackMap.get(t);this._remoteVideoTrackMap.delete(t),this.isMixing&&this.isPresetLayoutMode&&e&&this._config&&this.startMixTranscode(this._config)}}startMixTranscode(t){return E(this,null,function*(){try{this.resetIsUsedFlag(),this._config=t;let e=this.getInputParam(t),r=this.getOutputParam(t),n=this.getOutputSessionId({config:t,roomId:this._room.roomId,userId:this._room.userId});this.isMixing&&this._data&&n!==this._data.outputSessionId&&(this._log.info("startMixTranscode() streamId changed, stop mixing before start"),yield this.doStopMixTranscode()),yield this.doStartMixTranscode({outputSessionId:n,inputParam:e,outputParam:r})}catch(e){throw this.resetIsUsedFlag(),e}})}doStartMixTranscode(n){return E(this,arguments,function*({outputSessionId:t,inputParam:e,outputParam:r}){let s={roomId:String(this._room.roomId),mcuRequestTime:Date.now(),outputSessionId:t,inputParam:e,outputParam:r};this._log.info(`startMixTranscode: ${JSON.stringify(s)}`);let o=yield this._room.sendStartMixTranscode(s),{code:a}=o.data,{message:c}=o.data;if(a!==0)throw a===-102083&&(c=`Please enable relayed-push in ${En} and try later, refer to ${Mi}tutorial-26-advanced-publish-cdn-stream.html`),this._log.error(`startMixTranscode failed, errCode: ${a} errMsg: ${c}`),new M({code:v.START_MIX_TRANSCODE_FAILED,message:B({key:V.START_MIX_TRANSCODE_FAILED,data:{message:c},link:{className:"Client",fnName:"startMixTranscode"}})});this._data=s})}reStartMixTranscode(){!this.isMixing||this._config&&this.startMixTranscode(this._config)}stopMixTranscode(){return E(this,null,function*(){if(!this.isMixing)throw new M({code:v.INVALID_OPERATION,message:B({key:V.MIX_TRANSCODE_NOT_STARTED})});yield this.doStopMixTranscode(),this.resetIsUsedFlag()})}doStopMixTranscode(){return E(this,null,function*(){let t={mcuRequestTime:Date.now(),outputSessionId:this._data.outputSessionId,streamType:this._data.outputParam.streamType};this._log.info(`stopMixTranscode: ${JSON.stringify(t)}`);let e=yield this._room.sendStopMixTranscode(t),{code:r,message:n}=e.data;if(r===0)this._data=void 0;else throw this._log.error(`stopMixTranscode failed, errCode: ${r} errMsg: ${n}`),new M({code:v.STOP_MIX_TRANSCODE_FAILED,message:B({key:V.STOP_MIX_TRANSCODE_FAILED,data:{message:n},link:{className:"Client",fnName:"stopMixTranscode"}})})})}getOutputSessionId({config:t,userId:e,roomId:r}){return oe(t.streamId)&&t.streamId.length>0?t.streamId:(0,zl.default)(`${r}_${e}_main`)}getInputParam(t){let e=t.mixUsers.map(r=>({userId:r.userId,roomId:String(r.roomId||this._room.roomId),width:r.width||0,height:r.height||0,locationX:r.locationX||0,locationY:r.locationY||0,zOrder:r.zOrder,streamType:!b(r.streamType)&&r.streamType===gn?1:0,inputType:r.pureAudio?di.STREAM_TYPE.IT_PURE_AUDIO:di.STREAM_TYPE.IT_AUDIO_VIDEO,renderMode:r.renderMode||0}));return t.mode===di.MODE.PRESET_LAYOUT&&(e.forEach(r=>{if(r.userId===di.PLACE_HOLDER.REMOTE){let n=[...this._remoteVideoTrackMap.entries()].find(([,s])=>!s);if(n){let[s]=n,o=s.split("_");r.userId=o.slice(0,o.length-1).join("_"),r.streamType=o.splice(-1)[0]==="auxiliary"?1:0,this._remoteVideoTrackMap.set(s,!0)}}}),e=e.filter(r=>r.userId!==di.PLACE_HOLDER.REMOTE)),e}getOutputParam(t){let e=t.streamId||"";return{streamId:e,streamType:e.length>0?1:0,width:b(t.videoWidth)?640:t.videoWidth,height:b(t.videoHeight)?480:t.videoHeight,videoBps:t.videoBitrate||0,fps:t.videoFramerate||15,gop:t.videoGOP||2,audioSampleRate:t.audioSampleRate||48e3,audioBps:t.audioBitrate||64,audioChannels:t.audioChannels||1,backgroundColor:t.backgroundColor||0,backgroundImg:t.backgroundImage||"",extraInfo:"",videoCodec:2,audioCodec:0}}hasAvailablePlaceHolder(){var t,e;return!(!this.isPresetLayoutMode||((t=this._data)==null?void 0:t.inputParam.length)===((e=this._config)==null?void 0:e.mixUsers.length))}resetIsUsedFlag(){this._remoteVideoTrackMap.forEach((t,e)=>{this._remoteVideoTrackMap.set(e,!1)})}},ql=od;var OL=_(f(),1),Co=_(sd(),1);var Qn=class{constructor(t){p(this,"_room");p(this,"_publishTencentMainStreamObj",{params:null,streamId:void 0,isPublishing:!1});p(this,"_publishTencentAuxStreamObj",{params:null,streamId:void 0,isPublishing:!1});p(this,"_publishGivenCDNData",null);p(this,"_isPublishingGivenCDN",!1);this._room=t}get _isPublishingTencentCDN(){return this._publishTencentMainStreamObj.isPublishing||this._publishTencentAuxStreamObj.isPublishing}generatePublishCDNStreamId(t,e){if(!t){let r=`${this._room.roomId}_${this._room.userId}_${this.convertStreamType(e)}`;return/^[A-Za-z\d_-]*$/.test(r)||(r=(0,Co.default)(r)),`${this._room.sdkAppId}_${r}`}return t}convertStreamType(t){return t==="main"?t:"aux"}generatePublishCDNSessionId(t){return(0,Co.default)(`${this._room.roomId}_${this._room.userId}_${this.convertStreamType(t)}`)}startPublishCDN(t){return E(this,null,function*(){let{streamId:e="",streamType:r="main",appId:n,bizId:s,url:o}=t;yield this.startPublishTencentCDN({streamId:e,streamType:r}),n&&s&&o&&(yield this.startPublishGivenCDN({streamType:r,appId:n,bizId:s,url:o}))})}stopPublishCDN(){return E(this,null,function*(){if(!this._isPublishingTencentCDN)throw new M({code:v.INVALID_OPERATION,message:B({key:V.INVALID_OPERATION_STOP_PUBLISH_CDN})});yield this.stopPublishTencentCDN(),this._isPublishingGivenCDN&&(yield this.stopPublishGivenCDN())})}startPublishTencentCDN(t){return E(this,null,function*(){if(t.streamType==="auxiliary"?(this._publishTencentAuxStreamObj.params=t,this._publishTencentAuxStreamObj.isPublishing=!0):(this._publishTencentMainStreamObj.params=t,this._publishTencentMainStreamObj.isPublishing=!0),!this._room.isJoined)return;let e=this.generatePublishCDNStreamId(t.streamId,t.streamType),r=this.generatePublishCDNSessionId(t.streamType),n=t.streamType==="auxiliary"?1:0,s={requestTime:Date.now(),sessionId:r,streamId:e,streamType:n};yield this.doStartPublishTencentCDN(s,t.streamType)})}doStartPublishTencentCDN(t,e){return E(this,null,function*(){try{O.info(`startPublishTencentCDN: ${JSON.stringify(t)}`);let r=yield this._room.sendStartPublishCDN(t,!0),{code:n}=r.data,{message:s}=r.data;if(n===0)e==="auxiliary"?this._publishTencentAuxStreamObj.streamId=t.streamId:this._publishTencentMainStreamObj.streamId=t.streamId;else throw e==="auxiliary"?this._publishTencentAuxStreamObj.isPublishing=!1:this._publishTencentMainStreamObj.isPublishing=!1,n===-102083&&(s=`Please enable relayed-push in ${En} and try later, refer to ${Mi}tutorial-26-advanced-publish-cdn-stream.html`),O.error(`startPublishTencentCDN failed, errCode: ${n}, errMsg: ${s}`),new M({code:v.START_PUBLISH_CDN_FAILED,message:B({key:V.START_PUBLISH_CDN_FAILED,data:{message:s},link:{className:"Client",fnName:"startPublishCDNStream"}})})}catch(r){throw e==="auxiliary"?this._publishTencentAuxStreamObj.isPublishing=!1:this._publishTencentMainStreamObj.isPublishing=!1,r}})}resetPublishTencentParam(t){t==="main"&&(this._publishTencentMainStreamObj={params:null,streamId:void 0,isPublishing:!1}),t==="auxiliary"&&(this._publishTencentAuxStreamObj={params:null,streamId:void 0,isPublishing:!1})}stopPublishTencentCDN(){return E(this,null,function*(){if(!this._room.isJoined){this.resetPublishTencentParam("main"),this.resetPublishTencentParam("auxiliary");return}this._publishTencentMainStreamObj.isPublishing&&(yield this.doStopPublishTencentCDN("main")),this._publishTencentAuxStreamObj.isPublishing&&(yield this.doStopPublishTencentCDN("auxiliary"))})}doStopPublishTencentCDN(t){return E(this,null,function*(){let e={requestTime:Date.now(),sessionId:(0,Co.default)(`${this._room.roomId}_${this._room.userId}_${this.convertStreamType(t)}`)};O.info(`stopPublishTencentCDN: ${JSON.stringify(e)}`);let r=yield this._room.sendStopPublishCDN(e,!0),{code:n,message:s}=r.data;if(n===0)this.resetPublishTencentParam(t);else if(n===-102069)O.warn("stopPublishTencentCDN failed, can not stopPublishTencentCDN in auto relayed-push mode"),this.resetPublishTencentParam(t);else throw O.error(`stopPublishTencentCDN failed, errCode: ${n} errMsg: ${s}`),new M({code:v.STOP_PUBLISH_CDN_FAILED,message:B({key:V.STOP_PUBLISH_CDN_FAILED,data:{message:s},link:{className:"Client",fnName:"stopPublishCDNStream"}})})})}startPublishGivenCDN(t){return E(this,null,function*(){let e=t.streamType==="main"?this._publishTencentMainStreamObj.streamId:this._publishTencentAuxStreamObj.streamId,r={pushRequestTime:Date.now(),pushAppId:t.appId,pushBizId:t.bizId,pushCdnUrl:t.url,pushStreamType:this.convertStreamType(t.streamType),pushStreamId:e};if(O.info(`startPublishGivenCDN: ${JSON.stringify(r)}`),this._publishGivenCDNData=r,this._isPublishingGivenCDN=!0,!!this._room.isJoined)try{let n=yield this._room.sendStartPublishCDN(r,!1),{code:s,message:o}=n.data;if(s!==0)throw O.error(`startPublishGivenCDN failed, errCode: ${s}, errMsg: ${o}`),this._publishGivenCDNData=null,this._isPublishingGivenCDN=!1,new M({code:v.START_PUBLISH_CDN_FAILED,message:B({key:V.START_PUBLISH_CDN_FAILED,data:{message:o},link:{className:"Client",fnName:"startPublishCDNStream"}})})}catch(n){throw this._publishGivenCDNData=null,this._isPublishingGivenCDN=!1,n}})}stopPublishGivenCDN(){return E(this,null,function*(){if(!this._room.isJoined||!this._publishGivenCDNData){this._publishGivenCDNData=null,this._isPublishingGivenCDN=!1;return}let{pushAppId:t,pushBizId:e,pushCdnUrl:r,pushStreamType:n}=this._publishGivenCDNData,s={pushRequestTime:Date.now(),pushAppId:t,pushBizId:e,pushCdnUrl:r,pushStreamType:n};O.info(`stopPublishGivenCDN: ${JSON.stringify(s)}`);let o=yield this._room.sendStopPublishCDN(s,!1),{code:a,message:c}=o.data;if(a===0)this._publishGivenCDNData=null,this._isPublishingGivenCDN=!1;else throw O.error(`stopPublishGivenCDN failed, errCode: ${a} errMsg: ${c}`),new M({code:v.STOP_PUBLISH_CDN_FAILED,message:B({key:V.STOP_PUBLISH_CDN_FAILED,data:{message:c},link:{className:"Client",fnName:"stopPublishCDNStream"}})})})}handleCDNConfigForJoinData(t){let e=t,r;if(this._publishTencentMainStreamObj.isPublishing||this._publishTencentAuxStreamObj.isPublishing){let n={};oe(e)&&(n=JSON.parse(e)),n.Str_uc_params||(n.Str_uc_params={}),this._publishTencentMainStreamObj.isPublishing&&(this._publishTencentMainStreamObj.streamId?n.Str_uc_params.userdefine_streamid_main=this._publishTencentMainStreamObj.streamId:this._publishTencentMainStreamObj.params&&(n.Str_uc_params.userdefine_streamid_main=this.generatePublishCDNStreamId(this._publishTencentMainStreamObj.params.streamId,"main"))),this._publishTencentAuxStreamObj.isPublishing&&(this._publishTencentAuxStreamObj.streamId?n.Str_uc_params.userdefine_streamid_aux=this._publishTencentAuxStreamObj.streamId:this._publishTencentAuxStreamObj.params&&(n.Str_uc_params.userdefine_streamid_aux=this.generatePublishCDNStreamId(this._publishTencentAuxStreamObj.params.streamId,"auxiliary"))),e=JSON.stringify(n)}if(this._isPublishingGivenCDN&&this._publishGivenCDNData){let{pushAppId:n,pushBizId:s,pushCdnUrl:o,pushStreamType:a,pushStreamId:c}=this._publishGivenCDNData;r={pushRequestTime:Date.now(),pushAppId:n,pushBizId:s,pushCdnUrl:o,pushStreamType:a,pushStreamId:c}}return{bussinessInfo:e,pushUserCdnInfo:r}}reset(){this.resetPublishTencentParam("main"),this.resetPublishTencentParam("auxiliary"),this._publishGivenCDNData=null,this._isPublishingGivenCDN=!1}};var GL=_(f(),1);function ep(a){return E(this,arguments,function*({userId:i,sdkAppId:t,useStringRoomId:e,roomId:r,userSig:n,version:s,frameWorkType:o}){let c={delta:0,count:[1,1],msg:[]};try{let d=new FormData;d.append("userId",String(i)),d.append("sdkAppId",String(t)),d.append("isStrGroupId",String(e)),d.append("groupId",String(r)),d.append("sdkVersion",s),d.append("userSig",String(n)),d.append("frameWorkType",String(o));let u=z(),l=yield vf(d,c,t);return c.delta=z()-u,l}catch(d){let u=Oe(d)?d[0]:d,l=de(u.code)?u.code:0,h=`get websocket url failed: ${u.message.includes("timeout")?"timeout":u.message}`,I=new M({code:v.SCHEDULE_FAILED,extraCode:l,message:B({key:V.JOIN_ROOM_FAILED,data:{error:h,code:l}})});throw O.error(I),I}})}function Ql(i,t=m.MAIN){let e;return ws(i)?e=t===m.MAIN?Rr.MAIN_OVERSEA:Rr.BACKUP_OVERSEA:e=t===m.MAIN?Rr.MAIN:Rr.BACKUP,`https://${e}/api/v1/config`}function yf(i,t,e){return new Promise((r,n)=>{pi({url:i,body:t,timeout:e.timeout}).then(s=>{s.data.code===0?r(s.data.data):n({code:s.data.code,message:s.data.msg})}).catch(n)})}var Zl=(i,t)=>Dt({retryFunction:yf,settings:{retries:3,timeout:0},onError:t,onRetrying:i});function vf(i,t,e){return new Promise((r,n)=>{let s=null;Ca([Zl(o=>t.count[0]=o+1,(o,a)=>{t.msg[0]=o.message,s||a()})(Ql(e,m.MAIN),i,{get timeout(){return vr(2+t.count[0])*1e3}}),Zl(o=>t.count[1]=o+1,(o,a)=>{t.msg[1]=o.message,s||a()})(Ql(e,m.BACKUP),i,{get timeout(){return vr(2+t.count[1])*1e3}})]).then(o=>{s=o,r(s)}).catch(n)})}var Nf=0;var yo=class extends he{constructor(e){super("room");this.seq=++Nf;this.role="anchor";this.localTracks=new Set;this.enableAutoPlayDialog=!0;this.autoReceiveAudio=!0;this.autoReceiveVideo=!0;this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null};this._log=O.createLogger({id:`r${this.seq}`});this._joinedTimestamp=0;this._isDestroyed=!1;this.useStringRoomId=!!e.useStringRoomId,Ne(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),Ne(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),Ne(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this.keyPointManager=new jl({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new Jl({room:this}),this.badCaseDetector=new Yl({room:this}),this.mixTranscodeManager=new ql(this),this.publishCDNManager=new Qn(this),this.audioManager=new eo({room:this})}get isMainStreamPublished(){for(let e of this.localTracks)if(e.mediaType&4)return!0;return!1}get isAuxStreamPublished(){for(let e of this.localTracks)if(e.mediaType&2)return!0;return!1}get hasAuxStream(){for(let e of this.remotePublishedUserMap.values())if(e.muteState.hasAuxiliary)return!0;return this.isAuxStreamPublished}getLogger(){return this._log}get isJoined(){return this.state==="joined"}addTrack(e){return E(this,null,function*(){return this.publish(e)})}removeTrack(e){return E(this,null,function*(){return this.unpublish(e)})}replaceTrack(e){return E(this,null,function*(){})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}getRemoteAudioStats(){return E(this,null,function*(){let e={};return this.remotePublishedUserMap.forEach(r=>{e[r.userId]=r.remoteAudioTrack.stat}),e})}getTransportStats(){return E(this,null,function*(){var r;let e={rtt:((r=this.quality)==null?void 0:r.uplinkRTT)||0,downlinksRTT:{}};if(this.quality)for(let n of this.quality.downlinkInfo)e.downlinksRTT[n.userId]=n.rtt;return e})}getRemoteVideoStats(){return E(this,arguments,function*(e="main"){let r={};return this.remotePublishedUserMap.forEach(n=>{let s=e==="auxiliary"?n.remoteAuxiliaryTrack:n.remoteVideoTrack;r[n.userId]=s.stat}),r})}checkDestroy(){if(this._isDestroyed)throw new M({code:v.INVALID_OPERATION,message:B({key:V.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(xe.INVALID_DESTROY),new M({code:v.INVALID_OPERATION,message:B({key:V.INVALID_DESTROY})});this._log.info("destroy room"),this.keyPointManager.destroy(),this.callDurationCalculator.destroy(),this.badCaseDetector.destroy(),this._isDestroyed=!0,C.emit(S.ROOM_DESTROY,{room:this})}startMixTranscode(e){return this.mixTranscodeManager.startMixTranscode(e)}stopMixTranscode(){return this.mixTranscodeManager.stopMixTranscode()}startPublishCDNStream(){return E(this,arguments,function*(e={}){if(this._log.info(`startPublishCDNStream with params: ${JSON.stringify(e)}; isJoined: ${this.isJoined}; hasMainStream: ${this.isMainStreamPublished}; hasAuxStream: ${!!this.isAuxStreamPublished};`),this.isJoined){if(e.streamType==="main"&&!this.isMainStreamPublished)throw new M({code:v.INVALID_OPERATION,message:B({key:V.INVALID_OPERATION_START_PUBLISH_CDN})});if(e.streamType==="auxiliary"&&!this.isAuxStreamPublished)throw new M({code:v.INVALID_OPERATION,message:B({key:V.INVALID_OPERATION_START_PUBLISH_CDN})})}yield this.publishCDNManager.startPublishCDN(e)})}stopPublishCDNStream(){return this.publishCDNManager.stopPublishCDN()}schedule(e,r,n){return E(this,null,function*(){var o,a;let s=z();try{let c=yield ep({userId:this.userId,sdkAppId:this.sdkAppId,roomId:e,useStringRoomId:this.useStringRoomId,version:n,userSig:this.userSig,frameWorkType:r});this._log.info(`schedule: ${JSON.stringify(c)}`),this.scheduleResult=w(w({},this.scheduleResult),c),de((o=c.config)==null?void 0:o.retryCount)&&fa(c.config.retryCount),oe((a=c.config)==null?void 0:a.loggerDomain)&&fn(c.config.loggerDomain),C.emit(S.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult}),C.emit(S.API_SUCCESS_RATE,{room:this,apiName:"schedule",cost:z()-s})}catch(c){throw C.emit(S.API_SUCCESS_RATE,{room:this,apiName:"schedule",error:c}),c}})}};var wk=_(f(),1);var Ri=new WeakMap,kt=new WeakMap;function Zn(){return function(i,t,e){let r=e.value,n=({fn:s,args:o,context:a,resolve:c,reject:d})=>{s.apply(a,o).then(c,d)};return e.value=function(...s){return new Promise((a,c)=>{if(Ri.has(this)){let d=Ri.get(this),{length:u}=d;d.push({fn:r,args:s,context:this,resolve:a,reject:c}),u===0&&n({fn:r,args:s,context:this,resolve:a,reject:c})}else Ri.set(this,[{fn:r,args:s,context:this,resolve:a,reject:c}]),n({fn:r,args:s,context:this,resolve:a,reject:c})}).finally(()=>{let a=Ri.get(this);a&&(a.shift(),a[0]&&n(w({},a[0])))})},e}}function tp(i){return function(t,e,r){let n=r.value;return r.value=function(...s){let o=Ri.get(this);if(o){let a=o.filter((c,d)=>{if(d===0)return!0;let u=!0;return c.args.forEach(l=>{s.find(h=>h===l)||(u=!1)}),u?(c.reject(new M({code:v.API_CALL_ABORTED,message:i})),!1):!0});Ri.set(this,a)}return n.apply(this,s)},r}}function ip(i){return function(t,e,r){let n=r.value;return r.value=function(...s){var a,c;let o=[];return(a=Ri.get(this))==null||a.forEach(d=>o.push(d)),(c=kt.get(this))==null||c.forEach(d=>d.forEach(u=>o.push(u))),o.forEach(d=>{d.reject(new M({code:v.API_CALL_ABORTED,message:i}))}),Ri.delete(this),kt.delete(this),n.apply(this,s)},r}}function ad(i){return function(t,e,r){let n=r.value,s=a=>de(i)?a[i]:i(...a),o=({fn:a,args:c,context:d,resolve:u,reject:l})=>{a.apply(d,c).then(u,l).finally(()=>{if(kt.has(d)&&kt.get(d).has(s(c))){let h=kt.get(d).get(s(c));h&&(h.shift(),h[0]&&o(w({},h[0])))}})};return r.value=function(...a){return new Promise((c,d)=>{if(kt.has(this))if(kt.get(this).has(s(a))){let u=kt.get(this).get(s(a));if(u){let{length:l}=u;u.push({fn:n,args:a,context:this,resolve:c,reject:d}),l===0&&o({fn:n,args:a,context:this,resolve:c,reject:d})}}else kt.get(this).set(s(a),[{fn:n,args:a,context:this,resolve:c,reject:d}]),o({fn:n,args:a,context:this,resolve:c,reject:d});else{let u=new Map;u.set(s(a),[{fn:n,args:a,context:this,resolve:c,reject:d}]),kt.set(this,u),o({fn:n,args:a,context:this,resolve:c,reject:d})}})},r}}var Hk=_(f(),1),np=_(rt(),1);var rp=Symbol("instance"),es=Symbol("abortCtrl"),er=Symbol("cacheResult"),cd=class{constructor(t,e,r){p(this,"oldState");p(this,"newState");p(this,"action");p(this,"error");this.oldState=t,this.newState=e,this.action=r}toString(){return`${this.action}ing`}},ts=class extends Error{constructor(e,r,n){super(r);p(this,"state");p(this,"message");p(this,"cause");this.state=e,this.message=r,this.cause=n}},is=new Map,bf=Object.getPrototypeOf((()=>E(void 0,null,function*(){}))()).constructor;function dd(i,t,e={}){return(r,n,s)=>{let o=e.action||n;if(!e.context){let c=is.get(r)||[];is.has(r)||is.set(r,c),c.push({from:i,to:t,action:o})}let a=s.value;s.value=function(...c){return E(this,null,function*(){var I;let d=this;if(e.context&&(d=et.get(typeof e.context=="function"?e.context.call(this,...c):e.context)),d.state===t)return d[er];let u=null;if(Array.isArray(i)?i.length==0?d[es]&&(d[es].aborted=!0):(typeof d.state!="string"||!i.includes(d.state))&&(u=new ts(d._state,`${d.name} ${o} to ${t} failed: current state ${d._state} not in from config`)):i!==d.state&&(u=new ts(d._state,`${d.name} ${o} to ${t} failed: current state ${d._state} not from ${i}`)),u)if(e.fail)e.fail.call(this,u);else{if(e.ignoreError)return u;throw u}let l=d.state;vo.call(d,new cd(l,t,o));let h={aborted:!1};d[es]=h;try{let T=a.apply(this,c);return T instanceof bf?d[er]=yield T:d[er]=T,h.aborted||(d[es]=void 0,vo.call(d,t),(I=e.success)==null||I.call(this,d[er])),d[er]}catch(T){let N=T instanceof Error?T.message:String(T);if(vo.call(d,l,N),e.fail)e.fail.call(this,new ts(d._state,`action '${o}' failed :${N}`,T instanceof Error?T:new Error(N)));else{if(e.ignoreError)return T;throw T}}})}}}var Df=(()=>typeof window!="undefined"&&window.__AFSM__?(e,r)=>{window.dispatchEvent(new CustomEvent(e,{detail:r}))}:typeof importScripts!="undefined"?(e,r)=>{postMessage({type:e,payload:r})}:()=>{})();function vo(i,t){let e=this._state;this._state=i;let r=i.toString();i&&this.emit(r,e),this.emit(et.STATECHANGED,i,e,t),this.updateDevTools({value:i,old:e,err:t})}var Of,Pf,Ze=class extends np.default{constructor(e,r,n){super();p(this,"name");p(this,"groupName");p(this,"_state",Ze.INIT);p(this,Of);p(this,Pf);this.name=e,this.groupName=r,e||(e=Date.now().toString(36)),n?Object.setPrototypeOf(this,n):n=Object.getPrototypeOf(this),r||(this.groupName=this.constructor.name);let s=n[rp];s?this.name=s.name+"-"+s.count++:n[rp]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),r=is.get(e)||[],n=new Set,s=[],o=[],a=new Set,c=Object.getPrototypeOf(e);is.has(c)&&(c.stateDiagram.forEach(u=>n.add(u)),c.allStates.forEach(u=>a.add(u))),r.forEach(({from:u,to:l,action:h})=>{typeof u=="string"?s.push({from:u,to:l,action:h}):u.length?u.forEach(I=>{s.push({from:I,to:l,action:h})}):o.push({to:l,action:h})}),s.forEach(({from:u,to:l,action:h})=>{a.add(u),a.add(l),a.add(h+"ing"),n.add(`${u} --> ${h}ing : ${h}`),n.add(`${h}ing --> ${l} : ${h} \u{1F7E2}`),n.add(`${h}ing --> ${u} : ${h} \u{1F534}`)}),o.forEach(({to:u,action:l})=>{n.add(`${l}ing --> ${u} : ${l} \u{1F7E2}`),a.forEach(h=>{h!==u&&n.add(`${h} --> ${l}ing : ${l}`)})});let d=[...n];return Object.defineProperty(this,"stateDiagram",{value:d}),d}static get(e){let r;return typeof e=="string"?(r=Ze.instances.get(e),r||Ze.instances.set(e,r=new Ze(e,void 0,Object.create(Ze.prototype)))):(r=Ze.instances2.get(e),r||Ze.instances2.set(e,r=new Ze(e.constructor.name,void 0,Object.create(Ze.prototype)))),r}static getState(e){var r;return(r=Ze.get(e))==null?void 0:r.state}updateDevTools(e={}){Df(Ze.UPDATEAFSM,w({name:this.name,group:this.groupName},e))}get state(){return this._state}set state(e){vo.call(this,e)}},et=Ze;Of=er,Pf=es,p(et,"STATECHANGED","stateChanged"),p(et,"UPDATEAFSM","updateAFSM"),p(et,"INIT","[*]"),p(et,"ON","on"),p(et,"OFF","off"),p(et,"instances",new Map),p(et,"instances2",new WeakMap);var h0=_(f()),up=_(rt());var Yk=_(f());var ud=_(jc()),sp=i=>{let t=Ie(i),e={audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0};return t.media.forEach((r,n)=>{var s;if(r.ssrcs&&!b(r.ssrcs[0].id)){let o=Number(r.ssrcs[0].id),a=Number((s=r.ssrcs.filter(c=>c.attribute==="cname")[1])==null?void 0:s.id);switch(n){case 0:e.audioSsrc=o;break;case 1:e.bigVideoSsrc=o,e.bigVideoRtxSsrc=a;break;case 2:e.smallVideoSsrc=o,e.smallVideoRtxSsrc=a;break;case 3:e.auxVideoSsrc=o,e.auxVideoRtxSsrc=a;break}}}),e},op=(i,t)=>{var a,c;let e=Ie(i),r={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],extensions:[]},useDataChannel:t};r.ice.ufrag=String(e.media[0].iceUfrag),r.ice.password=e.media[0].icePwd||"",e.fingerprint&&(r.dtls.hash=e.fingerprint.type,r.dtls.fingerprint=e.fingerprint.hash,r.dtls.setup=e.setup||""),e.media[0].fingerprint&&(r.dtls.hash=e.media[0].fingerprint.type,r.dtls.fingerprint=e.media[0].fingerprint.hash),r.dtls.setup=e.media[0].setup||"";let n=e.media[0],s=e.media[1];n.ext&&(r.audio.extensions=n.ext.map(d=>({id:d.value,uri:d.uri}))),s.ext&&(r.video.extensions=s.ext.map(d=>({id:d.value,uri:d.uri})));let o={codec:n.rtp[0].codec,fmtp:n.fmtp[0].config,payload:n.fmtp[0].payload,rate:n.rtp[0].rate,channel:n.rtp[0].encoding,rtcpFb:[],rtx:0};(a=n.rtcpFb)==null||a.forEach(({payload:d,type:u,subtype:l})=>{if(d===o.payload){let h={id:u,params:[]};l&&h.params.push(l),o.rtcpFb.push(h)}}),r.audio.codecs.push(o);for(let d=0;d<s.rtp.length;d++){if(["rtx","red","ulpfec"].includes(s.rtp[d].codec))continue;let u=s.fmtp.filter(l=>l.payload===s.rtp[d].payload)[0];r.video.codecs.push({payload:s.rtp[d].payload,codec:s.rtp[d].codec,fmtp:u?u.config:"",rate:s.rtp[d].rate,rtx:((c=s.rtp[d+1])==null?void 0:c.codec)==="rtx"?s.rtp[d+1].payload:0,rtcpFb:((s==null?void 0:s.rtcpFb)||[]).filter(l=>l.payload===s.rtp[d].payload).map(({type:l,subtype:h})=>({id:l,params:h?[h]:[]}))})}return r},ap=({serverAbility:i,clientAbility:t,offerSDP:e,enableCustomMessage:r})=>{let n=Ie(e),s={extmapAllowMixed:"extmap-allow-mixed",groups:n.groups,icelite:"ice-lite",media:[],msidSemantic:{semantic:"",token:"WMS"},name:"-",origin:{address:"127.0.0.1",username:"-",sessionId:String(Date.now()),sessionVersion:1,netType:"IN",ipVer:4},timing:{start:0,stop:0},version:0},o={candidates:i.candidates.map(a=>({component:1,foundation:"1",generation:0,ip:a.ip,port:a.port,priority:a.priority,transport:a.foundation,type:a.type})),connection:{version:4,ip:"0.0.0.0"},direction:m.TRANSCEIVER_DIRECTION_RECVONLY,ext:i.audio.extensions.map(a=>({value:a.id,uri:a.uri})),fingerprint:{type:i.dtls.hash,hash:i.dtls.fingerprint},fmtp:[{payload:i.audio.codecs[0].payload,config:i.audio.codecs[0].fmtp}],icePwd:i.ice.password,iceUfrag:i.ice.ufrag,mid:"0",payloads:String(i.audio.codecs[0].payload),port:n.media[0].port,protocol:n.media[0].protocol,type:m.AUDIO,setup:i.dtls.setup,rtcpFb:i.audio.codecs[0].rtcpfb.map(a=>({payload:i.audio.codecs[0].payload,type:a.id,subtype:a.params[0]})),rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[{payload:i.audio.codecs[0].payload,codec:i.audio.codecs[0].codec,rate:i.audio.codecs[0].rate,encoding:i.audio.codecs[0].channels}]};return s.media.push(o),[1,2,3].forEach(a=>{s.media.push(ld({mid:a,serverAbility:i,clientAbility:t,parsedOffer:n}))}),r&&s.media.push(n.media.find(a=>a.mid==="dc")),ut(s)},ld=({mid:i,serverAbility:t,clientAbility:e,parsedOffer:r,useAllCodec:n=!1})=>{let s={candidates:t.candidates.map(o=>({component:1,foundation:"1",generation:0,ip:o.ip,port:o.port,priority:o.priority,transport:o.foundation,type:o.type})),connection:{version:4,ip:"0.0.0.0"},direction:m.TRANSCEIVER_DIRECTION_RECVONLY,ext:t.video.extensions.map(o=>({value:o.id,uri:o.uri})),fingerprint:{type:t.dtls.hash,hash:t.dtls.fingerprint},fmtp:[],icePwd:t.ice.password,iceUfrag:t.ice.ufrag,mid:String(i),payloads:"",port:r.media[0].port,protocol:r.media[0].protocol,type:m.VIDEO,setup:t.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(t.video.codecs.length>0)if(n)for(let o=0;o<t.video.codecs.length;o++)No(s,t.video.codecs[o]);else{let o=t.video.codecs.findIndex(a=>a.codec.toLowerCase()===(t.useVp8?"vp8":"h264"));No(s,t.video.codecs[o])}else if(n)for(let o=0;o<e.video.codecs.length;o++)No(s,e.video.codecs[o]);else No(s,e.video.codecs[0]);return s.payloads=s.payloads.trim(),s},No=(i,t)=>{i.payloads=`${i.payloads} ${t.payload}`,i.fmtp.push({payload:t.payload,config:t.fmtp}),i.rtcpFb=[...i.rtcpFb||[],...(t.rtcpfb||t.rtcpFb).map(e=>({payload:t.payload,type:e.id,subtype:e.params[0]}))],i.rtp.push({payload:t.payload,codec:t.codec.toUpperCase(),rate:t.rate}),t.rtx&&(i.payloads=`${i.payloads} ${t.rtx}`,i.fmtp.push({payload:t.rtx,config:`apt=${t.payload}`}),i.rtp.push({payload:t.rtx,codec:"rtx",rate:t.rate}))};function Mf(i){let t=new Set(["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.ext&&(i.ext=i.ext.filter(e=>!t.has(e.uri)))}function Lf(i){if(!i.rtcpFb)return;let t=[];i.rtcpFb.forEach((e,r)=>{var n;t.push(e),i.rtcpFb&&((n=i.rtcpFb[r+1])==null?void 0:n.payload)!==e.payload&&e.type!=="rrtr"&&t.push({payload:e.payload,type:"rrtr"})}),i.rtcpFb=t}function kf(i){i.type===m.VIDEO&&i.fmtp&&i.fmtp.forEach(t=>{t.config.includes("apt")||(t.config+=";sps-pps-idr-in-keyframe=1")})}function xf(i){i.type===m.AUDIO&&i.fmtp&&i.fmtp.forEach(t=>{t.config+=";sprop-stereo=1;stereo=1"})}var cp=i=>{let t=ud.default.parse(i);return t.media.forEach(e=>{var r;(e.type===m.AUDIO||e.type===m.VIDEO)&&(Lf(e),kf(e),xf(e),Mf(e)),((r=e.payloads)==null?void 0:r.includes("datachannel"))&&t.groups&&e.mid&&(t.groups[0].mids=t.groups[0].mids.replace(e.mid,"dc"),e.mid="dc")}),ud.default.write(t)};var Ai=(a=>(a.TRACK="track",a.DATA_CHANNEL_MESSAGE="data_channel_msg",a[a.CONNECTION_STATE_CHANGED="connection-state-changed"]="CONNECTION_STATE_CHANGED",a[a.FIREWALL_RESTRICTION="firewall-restriction"]="FIREWALL_RESTRICTION",a.RECONNECTED="spc-reconnected",a.RECONNECT_FAILED="spc-reconnect-failed",a.ERROR="error",a))(Ai||{}),lp=0,pp=!1,Uf=new Set,Vf=i=>lp>2&&!pp&&Uf.size===0&&i,Wr=class extends up.default{constructor({signalChannel:e,room:r,enableCustomMessage:n}){super();p(this,"currentState","DISCONNECTED");p(this,"_room");p(this,"_signalChannel");p(this,"_peerConnection",null);p(this,"_datachannel",null);p(this,"_enableCustomMessage");p(this,"_log");p(this,"_downlinkMIDMap",new Map);p(this,"_reconnectionTimer",-1);p(this,"reconnectionCount",0);p(this,"_clientAbility",null);p(this,"_serverAbility",null);p(this,"addDownlinkQueue",new Set);p(this,"removeDownlinkQueue",new Set);p(this,"_parsedAnswer",null);p(this,"_updateSDPPromise",null);p(this,"_waitForPCConnectedPromise");p(this,"_waitForPCConnectedPromiseReject",null);p(this,"_isSDPLogged",!1);this._room=r,this._enableCustomMessage=n,this._signalChannel=e,this._log=O.createLogger({id:"spc",userId:this._room.userId,sdkAppId:this._room.sdkAppId})}get isH264EncodeSupported(){let e=this._room.checkSystemResult.detail.isH264EncodeSupported;return this._serverAbility&&(e=e&&!!this._serverAbility.video.codecs.find(r=>r.codec.toLowerCase()==="h264")),e}get isVP8EncodeSupported(){let e=this._room.checkSystemResult.detail.isVp8EncodeSupported;return this._serverAbility&&(e=e&&this._serverAbility.useVp8),e}get uplinkSSRC(){return this._peerConnection&&this._peerConnection.localDescription?sp(this._peerConnection.localDescription.sdp):{audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0}}get isReconnecting(){return this.currentState==="RECONNECTING"||this._reconnectionTimer>0}initialize(){return E(this,null,function*(){try{this._peerConnection=new RTCPeerConnection({offerExtmapAllowMixed:!0,iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._room.sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"}),this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this._peerConnection.ontrack=r=>this.emit("track",r),this._enableCustomMessage&&(this._datachannel=this._peerConnection.createDataChannel(`${this._room.userId}dc`),this._datachannel.binaryType="arraybuffer",this._datachannel.onopen=()=>{this._log.info("datachannel open")},this._datachannel.onclose=()=>{this._log.warn("datachannel close")},this._datachannel.onmessage=r=>{let n=new hd(r.data);this.emit("data_channel_msg",{data:n})},this._datachannel.onerror=r=>{this._log.warn("datachannel error",r)}),this._peerConnection.addTransceiver(m.AUDIO,{direction:m.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(m.VIDEO,{direction:m.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(m.VIDEO,{direction:m.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(m.VIDEO,{direction:m.TRANSCEIVER_DIRECTION_SENDONLY});let e=yield this._peerConnection.createOffer();return yield this.setOffer(e),this._clientAbility=op(e.sdp,this._enableCustomMessage),this._clientAbility}catch(e){throw this._log.error(`initialize failed ${e}`),e}})}connect(e,r=!1){return E(this,null,function*(){try{if(this.currentState==="CONNECTED")return;let n=z(),s={type:"answer",sdp:ap({serverAbility:e,clientAbility:this._clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(s),yield this.waitForPeerConnectionConnected(),r||C.emit(S.API_SUCCESS_RATE,{room:this._room,apiName:"SPCConnect",cost:Math.min(z()-n,30*1e3)})}catch(n){let s=n instanceof M&&n.code===v.API_CALL_ABORTED;throw s||this._log.error(`connect failed: ${n} ${e}`),this.reset(),!s&&!this.isReconnecting&&(C.emit(S.API_SUCCESS_RATE,{room:this._room,apiName:"SPCConnect",error:n}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),n}})}reconnect(){return E(this,null,function*(){if(this._reconnectionTimer!==-1){this._log.warn("reconnect() is reconnecting, ignore current reconnection");return}if(!this._signalChannel.isConnected){this._log.warn("reconnect() wait signal channel is connected"),this._signalChannel.once(Se.CONNECTED,this.reconnect,this);return}try{this.reconnectionCount++,this._log.warn(`reconnect() trying [${this.reconnectionCount}]`),this.reset();let e=yield this.initialize(),r=yield this._signalChannel.sendWaitForResponse({command:ne.REBUILD_PEER_CONNECTION,responseCommand:Q.REBUILD_PEER_CONNECTION_RES,data:{ability:e},enableLog:!1});yield this.connect(r.data.data.ability,!0),this._log.warn("reconnect() successfully"),this.stopReconnection(),this.emit("spc-reconnected")}catch(e){if(e)if(e.message.includes("timeout")){let r=ot(this.reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${r/1e3}s`),this._reconnectionTimer=window.setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},r)}else this._log.error(`reconnect() failed ${e}`),C.emit(S.API_SUCCESS_RATE,{room:this._room,apiName:"SPCReconnect",error:e}),this.reconnectionCount>=Bt()&&this._log.warn(`SDK has tried reconnect for ${Bt()} times, but all failed, please check your network`),this.stopReconnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.emit("error")}})}getPeerConnection(){return this._peerConnection}startReconnection(){return E(this,null,function*(){this._log.warn("start reconnect"),this.emitConnectionStateChangedEvent("RECONNECTING");let e=z();yield this.reconnect(),C.emit(S.API_SUCCESS_RATE,{room:this._room,apiName:"SPCReconnect",cost:Math.min(z()-e,30*1e3)})})}stopReconnection(){this._reconnectionTimer!==-1&&(this._log.info("stop reconnect"),this.reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(Se.CONNECTED,this.reconnect,this))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&((e=this._peerConnection)==null?void 0:e.connectionState)===pe.CLOSED&&this.startReconnection()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}onConnectionStateChange(e){let r=this._peerConnection.iceConnectionState,n=this.getDTLSTransportState();if(this._log.info(`connectionState: ${e.target.connectionState}, ICE: ${r}, DTLS: ${n}`),e.target.connectionState===pe.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),e.target.connectionState===pe.FAILED||e.target.connectionState===pe.CLOSED){let s=`ICE/DTLS Transport connection ${e.target.connectionState}. ICE Transport state: ${r}, DTLS Transport state: ${n}`,o=new M({message:s,code:v.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()}(e.target.connectionState===pe.CONNECTED||e.target.connectionState===pe.COMPLETED)&&(this.logSelectedCandidate(),this.emitConnectionStateChangedEvent("CONNECTED"))}getDTLSTransportState(){if(!this._peerConnection)return ft;let e=null;return!Dr()||this._peerConnection.getSenders().length===0?ft:(e=this._peerConnection.getSenders()[0].transport,!Hi()||this._peerConnection.getReceivers().length===0?ft:e?e.state:ft)}emitConnectionStateChangedEvent(e){e!==this.currentState&&(this.currentState==="RECONNECTING"&&e==="CONNECTING"||(this.emit(Ai.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:e}),this.currentState=e))}logSelectedCandidate(){return E(this,null,function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[r,n]of e)if(hi(n)){let s=e.get(n.localCandidateId),o=e.get(n.remoteCandidateId);s&&this._log.info(`local candidate: ${s.candidateType} ${s.protocol}:${s.ip||s.address}:${s.port} ${s.networkType||""} ${s.candidateType==="relay"?`relayProtocol:${s.relayProtocol}`:""}`),o&&this._log.info(`remote candidate: ${o.candidateType} ${o.protocol}:${o.ip||o.address}:${o.port}`);break}})}waitForPeerConnectionConnected(){return this._waitForPCConnectedPromise?this._waitForPCConnectedPromise:(this._waitForPCConnectedPromise=new Promise((e,r)=>{if(this.currentState==="CONNECTED")return e();this._waitForPCConnectedPromiseReject=r;let n=c=>{c.state==="CONNECTED"&&(clearTimeout(a),o(),e())},s=({room:c})=>{c===this._room&&(clearTimeout(a),o(),r(new M({code:v.API_CALL_ABORTED,message:B({key:V.CONNECTION_ABORTED,data:"leave room"})})))},o=()=>{C.off(S.LEAVE_SUCCESS,s,this),this.off(Ai.CONNECTION_STATE_CHANGED,n,this)},a=setTimeout(()=>{o();let c=new M({code:v.API_CALL_TIMEOUT,message:"connection timeout"});lp+=1,Vf(this._signalChannel.isConnected)&&(this._log.warn("firewall restrition"),pp=!0,this.emit(Ai.FIREWALL_RESTRICTION)),r(c)},Rn);C.on(S.LEAVE_SUCCESS,s,this),this.on(Ai.CONNECTION_STATE_CHANGED,n,this)}),this._waitForPCConnectedPromise=this._waitForPCConnectedPromise.finally(()=>{this._waitForPCConnectedPromise=null,this._waitForPCConnectedPromiseReject=null}),this._waitForPCConnectedPromise)}waitForReconnected(){return this.isReconnecting?new Promise((e,r)=>{this.once("spc-reconnected",e),this.once("error",r)}):Promise.resolve()}addDownlink(e){return E(this,null,function*(){if(this._log.info(`addDownlink(${e.userId}) trying`),this.isReconnecting&&(yield this.waitForReconnected()),this.updateLocalAndRemoteSDPConfig(e),this.addDownlinkQueue.size===0)try{yield this.updateSDP({isNeedToCreateOffer:!0}),this._log.info(`addDownlink(${e.userId}) done`)}catch(r){this._log.info(`addDownlink(${e.userId}) failed`),yield this.startReconnection()}})}updateLocalAndRemoteSDPConfig({ssrc:e,tinyId:r}){if(!this._peerConnection)return;this._log.info(`updateLocalAndRemoteSDPConfig ${JSON.stringify(e)} ${r}`);let n=this._peerConnection.getTransceivers().filter(d=>d.direction==="inactive").slice(0,3).map(d=>(d.direction=m.TRANSCEIVER_DIRECTION_RECVONLY,Number(d.mid)));n.length===0&&(this._peerConnection.addTransceiver(m.AUDIO,{direction:m.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(m.VIDEO,{direction:m.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(m.VIDEO,{direction:m.TRANSCEIVER_DIRECTION_RECVONLY})),this._parsedAnswer||(this._parsedAnswer=Ie(this._peerConnection.remoteDescription.sdp));let s,o,a;if(n.length===3)s=this._parsedAnswer.media.find(d=>Number(d.mid)===Number(n[0])),o=this._parsedAnswer.media.find(d=>Number(d.mid)===Number(n[1])),a=this._parsedAnswer.media.find(d=>Number(d.mid)===Number(n[2]));else{s=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let d=ld({mid:1,serverAbility:this._serverAbility,clientAbility:this._clientAbility,parsedOffer:Ie(this._peerConnection.localDescription.sdp),useAllCodec:!0});o=JSON.parse(JSON.stringify(d)),a=JSON.parse(JSON.stringify(d)),s.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(s),o.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(o),a.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(a)}s.direction=m.TRANSCEIVER_DIRECTION_SENDONLY,s.ssrcs=[{id:e.audio,attribute:"cname",value:`${r}`},{id:e.audio,attribute:"msid",value:`${r}-${m.MAIN} ${r}-audio`}],o.direction=m.TRANSCEIVER_DIRECTION_SENDONLY,o.ssrcs=[{id:e.video,attribute:"cname",value:`${r}`},{id:e.video,attribute:"msid",value:`${r}-${m.MAIN} ${r}-bigvideo`},{id:e.videoRtx,attribute:"cname",value:`${r}`},{id:e.videoRtx,attribute:"msid",value:`${r}-${m.MAIN} ${r}-bigvideo`}],o.ssrcGroups=[{semantics:"FID",ssrcs:`${e.video} ${e.videoRtx}`}],a.direction=m.TRANSCEIVER_DIRECTION_SENDONLY;let c=`${r}-aux`;a.ssrcs=[{id:e.auxiliary,attribute:"cname",value:c},{id:e.auxiliary,attribute:"msid",value:`${c} ${r}-aux${m.VIDEO}`},{id:e.auxiliaryRtx,attribute:"cname",value:`${c} ${r}-aux${m.VIDEO}`},{id:e.auxiliaryRtx,attribute:"msid",value:`${c} ${r}-aux${m.VIDEO}`}],a.ssrcGroups=[{semantics:"FID",ssrcs:`${e.auxiliary} ${e.auxiliaryRtx}`}],this._parsedAnswer.groups&&(this._parsedAnswer.groups[0].mids=this._parsedAnswer.media.map(d=>d.mid).join(" ")),this._downlinkMIDMap.set(r,[s.mid,o.mid,a.mid])}removeDownlink(e,r){return E(this,null,function*(){if(!this._downlinkMIDMap.has(e)||!this._peerConnection)return;this._log.info(`removeDownlink(${r}) trying`),this.isReconnecting&&(yield this.waitForReconnected());let n=this._downlinkMIDMap.get(e),s=!1;this._peerConnection.getTransceivers().forEach(o=>{n!=null&&n.includes(Number(o.mid))&&(s=!0,o.direction="inactive")}),this._parsedAnswer||(this._parsedAnswer=Ie(this._peerConnection.remoteDescription.sdp)),this._parsedAnswer.media.forEach(o=>{n!=null&&n.includes(Number(o.mid))&&(s=!0,o.direction="inactive",o.ssrcs=[],o.ssrcGroups=[])}),this.removeDownlinkQueue.size===0&&s&&(yield this.updateSDP({isNeedToCreateOffer:!0,tinyIdRemoving:e})),this._downlinkMIDMap.delete(e),this._log.info(`removeDownlink(${r}) done`)})}getDownlinkMids(e){return this._downlinkMIDMap.get(e)}setBandwidth(e){return E(this,null,function*(){if(!this._peerConnection)return;let{audio:r,bigVideo:n,smallVideo:s,auxVideo:o}=e;try{if(Dn()){let a=this._peerConnection.getSenders().slice(0,4);for(let c=0;c<a.length;c++){let d=a[c],u;c===0&&r?u=r:c===1&&n?u=n:c===2&&s?u=s:c===3&&o&&(u=o),u&&(yield this.setSenderMaxBitrate(d,u))}}else yield this.setBandwidthBySDP(e);Object.keys(e).forEach(a=>{e[a]&&this._log.info(`${a} bandwidth was set to ${e[a]} kbps`)})}catch(a){this._log.error(`failed to set bandwidth${a}`)}})}setSenderMaxBitrate(e,r){let n=e.getParameters();return(!n.encodings||n.encodings.length===0)&&(n.encodings=[{}]),r==="unlimited"?delete n.encodings[0].maxBitrate:n.encodings[0].maxBitrate=r*1e3,e.setParameters(n)}setBandwidthBySDP({audio:e,bigVideo:r,smallVideo:n,auxVideo:s}){if(!this._peerConnection||!this._peerConnection.localDescription)return;let o=Ie(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=Ie(this._peerConnection.remoteDescription.sdp));let a=ue?"TIAS":"AS";e&&(o.media[0].bandwidth=[{type:a,limit:ue?e*1e3:e}],this._parsedAnswer.media[0].bandwidth=[{type:a,limit:ue?e*1e3:e}]),r&&(o.media[1].bandwidth=[{type:a,limit:ue?r*1e3:r}],this._parsedAnswer.media[1].bandwidth=[{type:a,limit:ue?r*1e3:r}]),n&&(o.media[2].bandwidth=[{type:a,limit:ue?n*1e3:n}],this._parsedAnswer.media[2].bandwidth=[{type:a,limit:ue?n*1e3:n}]),s&&(o.media[3].bandwidth=[{type:a,limit:ue?s*1e3:s}],this._parsedAnswer.media[3].bandwidth=[{type:a,limit:ue?s*1e3:s}]);let c={type:"offer",sdp:ut(o)};return this.updateSDP({localDescription:c})}updateSDP({isNeedToCreateOffer:e=!1,localDescription:r,tinyIdRemoving:n}){if(!this._parsedAnswer)return;let s=ut(this._parsedAnswer);return this._updateSDPPromise=new Promise((o,a)=>E(this,null,function*(){var c,d;try{e&&this._peerConnection&&(this._log.info("creating offer"),r=yield this._peerConnection.createOffer()),r&&(yield this.setOffer(r)),yield this.setAnswer({type:"answer",sdp:s}),this._updateSDPPromise=null,o()}catch(u){this._log.error(u),!this._isSDPLogged&&this._peerConnection&&(this._log.warn(`transceivers: ${JSON.stringify(this._peerConnection.getTransceivers().map(({mid:l,currentDirection:h,direction:I,stopped:T})=>({mid:l,currentDirection:h,direction:I,stopped:T})))}`),this._log.warn(`parsedAnswer: ${JSON.stringify(this._parsedAnswer)}`),this._log.warn(`local sdp: ${r==null?void 0:r.sdp}`||((c=this._peerConnection.localDescription)==null?void 0:c.sdp)),this._log.warn(`remote sdp: ${s}`||((d=this._peerConnection.remoteDescription)==null?void 0:d.sdp)),this._isSDPLogged=!0),this._updateSDPPromise=null,a(u)}})),this._updateSDPPromise}setOffer(e){return this._log.info("setting offer"),this._peerConnection.setLocalDescription({type:"offer",sdp:cp(e.sdp)})}setAnswer(e){return this._log.info("setting answer"),this._peerConnection.setRemoteDescription(e)}sendDataChannelMessage(e){var r;(r=this._datachannel)==null||r.send(e)}reset(){var e;(e=this._peerConnection)==null||e.close(),this._waitForPCConnectedPromise=null,this._parsedAnswer=null}close(){this._log.info("close pc"),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners()}};H([Zn()],Wr.prototype,"updateSDP",1);var pd=class{constructor(t){p(this,"tag");p(this,"len");p(this,"data");let e=new DataView(t);this.tag=e.getUint16(),this.len=e.getUint16(2),this.data=new Uint8Array(t).slice(4,2+2+this.len).buffer}},hd=class{constructor(t){p(this,"tinyId");p(this,"data");let e=new DataView(t),r=0,n=[];for(;r<e.byteLength;){let s=e.getUint16(r+2),o=new pd(new Uint8Array(t).slice(r,r+2+2+s).buffer);n.push(o),r+=2+2+s}n.forEach(s=>{s.tag===1?this.tinyId=new TextDecoder().decode(s.data):s.tag===2&&(this.data=s.data)})}},dp=new Set;function tr(){let i=Math.floor(Math.random()*4294967296);return dp.has(i)?tr():(dp.add(i),i)}var j0=_(f());var C0=_(f()),hp=_(rt());var ir=class extends hp.default{constructor(e){super();p(this,"userId");p(this,"tinyId");p(this,"_sdpSemantics");p(this,"_isUplink");p(this,"_room");p(this,"_log");p(this,"_signalChannel");p(this,"_currentState","DISCONNECTED");p(this,"_prevTime",-1);p(this,"_enableSEI");p(this,"_sei");this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=O.createLogger({id:"n",userId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=e.signalChannel,this._enableSEI=e.enableSEI,this._enableSEI&&_i&&(this._sei=new To(this,this._log,this._isUplink))}get _peerConnection(){var e;return((e=this.singlePC)==null?void 0:e.getPeerConnection())||null}get singlePC(){return this._room.singlePC}close(e){this._log.info("close connection"),this.emit("closed",e),this._sei&&(this._sei.destroy(),this._sei=null)}emitConnectionStateChangedEvent(e){return e===this._currentState?!1:(C.emit(S.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:e,remoteUserId:this._isUplink?void 0:this.userId}),this.emit("connection-state-changed",{prevState:this._currentState,state:e}),this._currentState=e,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}getCurrentState(){return this._currentState}get isH264(){var e,r;return!!((r=(e=this._peerConnection)==null?void 0:e.remoteDescription)!=null&&r.sdp.includes("H264"))}};var md=class extends ir{constructor(e){super(ee(w({},e),{isUplink:!0}));p(this,"localMainAudioTrack",null);p(this,"localMainVideoTrack",null);p(this,"localAuxAudioTrack",null);p(this,"localAuxVideoTrack",null);p(this,"_isPublishingAux",!1);p(this,"_publishingLocalAudioTrack");p(this,"_publishingLocalVideoTrack");p(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});p(this,"_smallGenerator");p(this,"_audioManager");this._audioManager=e.audioManager,this._smallGenerator=null,this.initialize()}get ssrc(){if(!this.singlePC)return{audio:0,video:0,videoRtx:0,small:0,smallRtx:0,auxiliary:0,auxiliaryRtx:0};let{audioSsrc:e,bigVideoSsrc:r,bigVideoRtxSsrc:n,smallVideoSsrc:s,smallVideoRtxSsrc:o,auxVideoSsrc:a,auxVideoRtxSsrc:c}=this.singlePC.uplinkSSRC;return{audio:e||0,video:r||0,videoRtx:n||0,small:s||0,smallRtx:o||0,auxiliary:a||0,auxiliaryRtx:c||0}}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}get publishState(){var r,n,s,o;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(at()?(e.audio=!!((r=a[0])!=null&&r.track),e.bigVideo=!!((n=a[1])!=null&&n.track),e.smallVideo=!!((s=a[2])!=null&&s.track),e.auxVideo=!!((o=a[3])!=null&&o.track)):a.forEach(c=>{c.track&&(c.track.kind===m.AUDIO?e.audio=!0:(e.bigVideo=!0,this._smallGenerator&&(e.smallVideo=!0)))}))}return e}initialize(){this.installEvents()}reset(){this.uninstallEvents(),this.localMainVideoTrack&&this.localMainVideoTrack.canvasTrack&&this.localMainVideoTrack.destoryCanvasTrack()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._smallGenerator&&(this._smallGenerator.destroy(),this._smallGenerator=null)}installEvents(){var e;this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||(e=this.singlePC)==null||e.on("spc-reconnected",this.onSinglePCReconnected,this)}uninstallEvents(){var e;this.off("connection-state-changed",this.handleConnectionStateChange,this),(e=this.singlePC)==null||e.off("spc-reconnected",this.onSinglePCReconnected,this)}emitConnectionStateChangedEvent(e,r){var o,a,c;let n=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&n!==e&&(r?r.emit("connection-state-changed",{prevState:n,state:e}):((o=this.localMainVideoTrack)==null||o.emit("connection-state-changed",{prevState:n,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:n,state:e}),(c=this._publishingLocalVideoTrack)==null||c.emit("connection-state-changed",{prevState:n,state:e}))),s}publish(s){return E(this,arguments,function*({localAudioTrack:e,localVideoTrack:r,isAuxiliary:n}){var a,c,d,u,l,h;if(!this.singlePC)return;if(yield this.singlePC.waitForPeerConnectionConnected(),e&&(this._publishingLocalAudioTrack=e),r){if(!this.singlePC.isH264EncodeSupported&&!this.singlePC.isVP8EncodeSupported)throw new M({code:v.NOT_SUPPORTED_H264,message:B({key:V.NOT_SUPPORTED_H264ENCODE})});this._publishingLocalVideoTrack=r}this._isPublishingAux=n;let o;r&&!n&&r.small&&(this._smallGenerator=new Zt(r),yield this._smallGenerator.initialize(),o=this._smallGenerator.generateSmallVideoTrack(r.small)),mi()&&(yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:r,smallTrack:o,isAuxiliary:n})),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,n?(r&&(this.localAuxVideoTrack=r),e&&(this.localAuxAudioTrack=e)):(r&&(this.localMainVideoTrack=r),e&&(this.localMainAudioTrack=e)),yield this.singlePC.setBandwidth({audio:((a=this.localMainAudioTrack)==null?void 0:a.profile.bitrate)||((c=this.localAuxAudioTrack)==null?void 0:c.profile.bitrate),bigVideo:(d=this.localMainVideoTrack)==null?void 0:d.profile.bitrate,smallVideo:(l=(u=this.localMainVideoTrack)==null?void 0:u.small)==null?void 0:l.bitrate,auxVideo:(h=this.localAuxVideoTrack)==null?void 0:h.profile.bitrate}),yield this._signalChannel.sendWaitForResponse({command:ne.SPC_PUBLISH,responseCommand:Q.SPC_PUBLISH_RESULT,data:ee(w({},this.singlePC.uplinkSSRC),{state:this.publishState})}),this.sendMediaSettings(),this.installTrackMuteEvents(e,r),this.sendMutedFlag()})}publishByTransceiver({localAudioTrack:e,localVideoTrack:r,smallTrack:n,isAuxiliary:s}){this._log.info("publish by transceiver");let o=new MediaStream;r&&Ni&&hn&&r.genCanvasTrack();let a=(r==null?void 0:r.canvasTrack)||(r==null?void 0:r.mediaTrack),c=this._audioManager.mediaStreamTrack,d=this._peerConnection.getTransceivers(),u=[];if(c){o.addTrack(c);let l=d[0].sender.replaceTrack(c);u.push(l)}if(a)if(o.addTrack(a),s){let l=d[3].sender.replaceTrack(a);u.push(l)}else{let l=d[1].sender.replaceTrack(a);u.push(l)}if(n){let l=d[2].sender.replaceTrack(n);u.push(l)}return Promise.all(u)}installTrackMuteEvents(...e){e.forEach(r=>{r&&(r==null||r.on("mute",this.sendMutedFlag,this),r==null||r.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(r=>{r&&(r==null||r.off("mute",this.sendMutedFlag,this),r==null||r.off("unmute",this.sendMutedFlag,this))})}unpublish(n){return E(this,arguments,function*({localAudioTrack:e,localVideoTrack:r}){let s=r&&r===this.localAuxVideoTrack,o=e==null?void 0:e.mediaTrack,a=r==null?void 0:r.mediaTrack,c=this._peerConnection.getSenders(),d=[];o&&(this._audioManager.removeAudioTrack(e),this._audioManager.isMixed||(yield c[0].replaceTrack(null),d.push(0),this.localMainAudioTrack=null)),a&&(s?(yield c[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=ee(w({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),d.push(3)):(yield c[1].replaceTrack(null),yield c[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=ee(w({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),d.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.setTransceiverDirection(se.INACTIVE,d),yield this.doPublishChange(!1)):yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,r),r==null||r.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return E(this,null,function*(){let r={state:this.publishState,constraintConfig:this._mediaSettings},n=yield this._signalChannel.sendWaitForResponse({command:ne.PUBLISH_STATE_CHANGE,data:r,responseCommand:Q.PUBLISH_STATE_CHANGE_RESULT,enableLog:e});this.checkPublishResultCode(n.data.code,n.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:ne.UNPUBLISH,commandDesc:"unpublish",responseCommand:Q.UNPUBLISH_RESULT,enableLog:e}).catch(r=>{if(r.getCode()===v.API_CALL_TIMEOUT)return Promise.resolve();throw r})}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:r}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":r&&(this._mediaSettings.videoCodec="VP8");let n=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:s,localAuxVideoTrack:o}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?o=this._publishingLocalVideoTrack:s=this._publishingLocalVideoTrack),Ft){if(n&&n.mediaTrack){let a=n.mediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=n.profile.bitrate*1e3,this._mediaSettings.audioFs=a.sampleRate||0}if(s&&s.mediaTrack){let a=s.mediaTrack.getSettings();this._mediaSettings.videoWidth=a.width||0,this._mediaSettings.videoHeight=a.height||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=s.profile.bitrate*1e3,s.small&&(this._mediaSettings.smallVideoWidth=s.small.width,this._mediaSettings.smallVideoHeight=s.small.height,this._mediaSettings.smallVideoFps=s.small.frameRate,this._mediaSettings.smallVideoBps=s.small.bitrate*1e3)}if(o&&o.mediaTrack){let a=o.mediaTrack.getSettings();this._mediaSettings.auxVideoWidth=a.width||0,this._mediaSettings.auxVideoHeight=a.height||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=o.profile.bitrate*1e3}}else n&&n.mediaTrack&&(this._mediaSettings.audioChannel=n.profile.channelCount,this._mediaSettings.audioBps=n.profile.bitrate*1e3,this._mediaSettings.audioFs=n.profile.sampleRate),s&&s.mediaTrack&&(this._mediaSettings.videoWidth=s.profile.width,this._mediaSettings.videoHeight=s.profile.height,this._mediaSettings.videoFps=s.profile.frameRate,this._mediaSettings.videoBps=s.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:ne.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:Q.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return E(this,null,function*(){var n;if(!this._peerConnection)return;let r=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is adding ${e.kind} track to current published local ${r?m.AUXILIARY:m.MAIN} stream`),(n=this._sei)==null||n.handleEncodedStreams(),at()&&(yield this.addTrackByTransceiver(e,r))})}addTrackByTransceiver(e,r){return E(this,null,function*(){var o;if(!e.mediaTrack)return;let n=this._peerConnection.getTransceivers(),s=e.mediaTrack;if(e.kind===m.AUDIO)this._audioManager.addAudioTrack(e),s=this._audioManager.mediaStreamTrack,yield n[0].sender.replaceTrack(s);else{let a=r?3:1;if(yield n[a].sender.replaceTrack(s),a===1&&((o=this.localMainVideoTrack)==null?void 0:o.small)){this._smallGenerator=new Zt(this.localMainVideoTrack),yield this._smallGenerator.initialize();let c=this._smallGenerator.generateSmallVideoTrack(this.localMainVideoTrack.small);yield n[2].sender.replaceTrack(c)}n[a].direction===se.INACTIVE&&(yield this.setTransceiverDirection(se.SENDONLY,[a]))}this.updateMediaSettings(),yield this.doPublishChange()})}removeTrack(e){return E(this,null,function*(){if(!this._peerConnection)return;let r=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${r?m.AUXILIARY:m.MAIN} stream`),at()&&(yield this.removeTrackByTransceiver(e,r))})}removeTrackByTransceiver(e,r){return E(this,null,function*(){if(!e.mediaTrack)return;let n=this._peerConnection.getTransceivers();if(e.kind===m.AUDIO)this._audioManager.removeAudioTrack(e),this._audioManager.isMixed||(yield n[0].sender.replaceTrack(null));else{let s=r?3:1;yield n[s].sender.replaceTrack(null),s===1&&this._smallGenerator&&(this._smallGenerator.destroy(),this._smallGenerator=null,yield n[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(se.INACTIVE,[s])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,r){return E(this,null,function*(){if(!ue)return;let n=!1,s=!1;this._log.info(`setting transceiver ${r.join(",")} direction to ${e}`);let o=this._peerConnection.getTransceivers();if(r.forEach(d=>{o[d].direction!==e&&(o[d].direction=e,n=!0)}),n){this._log.info("updating offer");let d=yield this._peerConnection.createOffer();yield this._peerConnection.setLocalDescription(d)}let a=-1,c=this._peerConnection.remoteDescription.sdp.split(`\r
102
101
  `).map(d=>{if(d.match(new RegExp(`a=(${se.INACTIVE}|${se.RECVONLY}|${se.SENDONLY})`))&&a++,r.includes(a)){if(e===se.INACTIVE&&d.includes(`a=${se.RECVONLY}`))return s=!0,`a=${e}`;if(e===se.SENDONLY&&d.includes(`a=${se.INACTIVE}`))return s=!0,`a=${se.RECVONLY}`}return d}).join(`\r
103
- `);s&&(this._log.info("updating answer"),yield this._peerConnection.setRemoteDescription({type:"answer",sdp:c}))})}replaceTrack(e){return E(this,null,function*(){var o;let r=(o=this._peerConnection)==null?void 0:o.getSenders();if(!r||r.length===0||!e.mediaTrack)return;let n=e.mediaTrack,s=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;if(this._log.info(`is replacing ${n.kind} track on ${s?m.AUXILIARY:m.MAIN} stream`),n.kind===m.AUDIO&&r[0]&&(this._audioManager.addAudioTrack(e),this._audioManager.isMixed&&(n=this._audioManager.mediaStreamTrack),yield r[0].replaceTrack(n)),n.kind===m.VIDEO){if(!s&&r[1]&&(yield r[1].replaceTrack(n),this._smallGenerator&&r[2])){this._log.info("replacing smallVideo"),this._smallGenerator.destroy(),this._smallGenerator=new Yt(this.localMainVideoTrack),yield this._smallGenerator.initialize();let a=this._smallGenerator.generateSmallVideoTrack(this._room.smallStreamConfig);yield r[2].replaceTrack(a)}s&&r[3]&&(yield r[3].replaceTrack(n))}})}setBandwidth(s){return E(this,arguments,function*({bandwidth:e,type:r,videoType:n}){if(this.singlePC){let o={};r===m.AUDIO?o.audio=e:n==="big"?o.bigVideo=e:n==="small"?o.smallVideo=e:o.auxVideo=e,yield this.singlePC.setBandwidth(o)}})}sendMutedFlag(e){var s,o,a;if(e===this.localAuxAudioTrack||e===this.localAuxVideoTrack)return;let n={audio:!!((s=this.localMainAudioTrack)!=null&&s.muted),bigVideo:!!((o=this.localMainVideoTrack)!=null&&o.muted),auxVideo:!!((a=this.localAuxVideoTrack)!=null&&a.muted)};this._log.info(`send muted state: ${JSON.stringify(n)}`),this._signalChannel.send(ne.UPDATE_MUTE_STAT,n)}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&C.emit(S.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(e=m.VIDEO){if(this._peerConnection){let r=this._peerConnection.getSenders();if(e===m.AUXILIARY&&r[3]&&r[3].track)return r[3].track.id;if(e===m.VIDEO&&r[1]&&r[1].track)return r[1].track.id}if(this.localMainVideoTrack&&e===m.VIDEO){let r=this.localMainVideoTrack.mediaTrack;if(r)return r.id}if(this.localAuxVideoTrack&&e===m.AUXILIARY){let r=this.localAuxVideoTrack.mediaTrack;if(r)return r.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,r){if(e!==0)throw e===qi?(this._log.error(Le.NOT_SUPPORTED_H264ENCODE),new L({code:v.NOT_SUPPORTED_H264,message:$({key:w.NOT_SUPPORTED_H264ENCODE})})):new L({code:v.UNKNOWN,message:$({key:w.SIGNAL_RESPONSE_FAILED,data:{signalResponse:Z.PUBLISH_RESULT,code:e,message:r}})})}sendSEI(e,r){var n;(n=this._sei)==null||n.push(e,r)}onSinglePCReconnected(){return E(this,null,function*(){this.isMainStreamPublished&&(yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0}))})}},Wc=Gc;var l0=_(f());function rf(i){return Object.keys(i).filter(t=>i[t])}var Qs=class extends Gi{constructor(e){super(te(B({},e),{isUplink:!1}));p(this,"_flag",0);p(this,"role","anchor");p(this,"remoteAudioTrack");p(this,"remoteVideoTrack");p(this,"remoteAuxiliaryTrack");p(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0});this.flag=e.flag,this.remoteAudioTrack=new ur(this._room,this),this.remoteVideoTrack=new Mi(this._room,this),this.remoteAuxiliaryTrack=new lr(this._room,this),this.initialize()}get subscribeState(){let e={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(this.remoteVideoTrack.mediaType&8?e.smallVideo=!0:e.video=!0),this.remoteAudioTrack.isSubscribed&&(e.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(e.auxiliary=!0),e}get muteState(){return oi(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var r,n,s;e!==this._flag&&(this._flag=e,(r=this.remoteAudioTrack)==null||r.onFlagChanged(),(n=this.remoteVideoTrack)==null||n.onFlagChanged(),(s=this.remoteAuxiliaryTrack)==null||s.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===m.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents(),this.removeDownlink()}installEvents(){!this.singlePC||(this.listeners("track").includes(this.onTrack)||this.singlePC.on("track",this.onTrack,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||this.singlePC.on("spc-reconnected",this.onSinglePCReconnected,this))}uninstallEvents(){!this.singlePC||(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this))}emitConnectionStateChangedEvent(e){var s,o;let r=this._currentState,n=super.emitConnectionStateChangedEvent(e);return n&&r!==e&&((s=this.remoteVideoTrack)==null||s.emit("connection-state-changed",{prevState:r,state:e}),(o=this.remoteAuxiliaryTrack)==null||o.emit("connection-state-changed",{prevState:r,state:e})),n}onTrack(e){let r=e.streams[0],{track:n}=e;if(r.id.split("-")[0]!==this.tinyId)return;let a=r.id.includes("aux")?"auxiliary":"main";this._log.debug(`ontrack ${a} ${n.kind}`);let c=m.AUDIO;n.kind===m.VIDEO&&(c=a===m.MAIN?m.VIDEO:m.AUXILIARY);let d=this.remoteAudioTrack;c===m.VIDEO?d=this.remoteVideoTrack:c===m.AUXILIARY&&(d=this.remoteAuxiliaryTrack),d.setMediaStream(r),d.setMediaStreamTrack(n)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,r){return E(this,null,function*(){try{if(this.isSubscriptionStateNotChanged(e))return;if(this.hasSSRC){let n="subscribe_change";Object.values(e).find(s=>s===!0)||(n="unsubscribe"),yield this.sendSubscription(n,e)}else yield this.doSubscribe(e)}catch(n){throw this._room.isJoined&&this.isStreamUnpublished(r)?(this._log.warn(`${n.message} ${JSON.stringify(this.muteState)}`),new L({code:v.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):n}})}unsubscribe(n){return E(this,arguments,function*({remoteTracks:e,streamType:r}){var a;if(r==="main"&&!this.isMainStreamSubscribed||r==="auxiliary"&&!this.isAuxStreamSubscribed){this._log.info(`${r} stream already unsubscribed`);return}let s=B({},this.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:s.audio=!1;break;case 4:s.video=!1;break;case 8:s.smallVideo=!1;break;case 2:s.auxiliary=!1;break;default:break}});let o="subscribe_change";Object.values(s).find(c=>c===!0)||(o="unsubscribe"),this._log.info(`${o==="unsubscribe"?o:"subscribe"} ${r} [${rf(s)}]`),o==="unsubscribe"&&((a=this.singlePC)==null||a.removeDownlinkQueue.add(this.tinyId)),yield this.sendSubscription(o,s),o==="unsubscribe"&&(this.remoteAudioTrack.setMediaStreamTrack(null),this.remoteVideoTrack.setMediaStreamTrack(null),this.remoteAuxiliaryTrack.setMediaStreamTrack(null),yield this.removeDownlink())})}sendSubscription(e,r=this.subscribeState){let n={srcTinyId:this.tinyId,srcUserId:this.userId},s=ne.UNSUBSCRIBE,o=Z.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(n={audio:r.audio,bigVideo:r.video,auxVideo:r.auxiliary,smallVideo:r.smallVideo,srcTinyId:this.tinyId},s=ne.SUBSCRIBE_CHANGE,o=Z.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:s,data:n,responseCommand:o,timeout:1e4}).then(({data:a})=>{if(a.code!==0){let c=new L({code:a.code,message:$({key:w.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(c),c}})}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}setDelay({audioDelay:e,videoDelay:r}){this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=r}onSinglePCReconnected(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary)&&this.doSubscribe(this.subscribeState,!1)}get hasSSRC(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}doSubscribe(){return E(this,arguments,function*(e=this.subscribeState,r=!0){if(!!this.singlePC){if(this.singlePC.addDownlinkQueue.add(this.tinyId),yield this.singlePC.waitForPeerConnectionConnected(),r||!this.hasSSRC){let n={audioSsrc:Fi(),bigVideoSsrc:Fi(),bigVideoRtxSsrc:Fi(),auxVideoSsrc:Fi(),auxVideoRtxSsrc:Fi()},{audioSsrc:s,bigVideoSsrc:o,bigVideoRtxSsrc:a,auxVideoSsrc:c,auxVideoRtxSsrc:d}=n;this.ssrc={audio:s,video:o,videoRtx:a,auxiliary:c,auxiliaryRtx:d},this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc});let u=yield this._signalChannel.sendWaitForResponse({command:ne.SPC_SUBSCRIBE,responseCommand:Z.SPC_SUBSCRIBE_RESULT,data:{srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo,customData:!0,ssrc:n}});if(u.data.code!==0)throw yield this.removeDownlink(),new L({code:u.data.code,message:u.data.message});return}this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc})}})}removeDownlink(){return E(this,null,function*(){!this.singlePC||(this.ssrc={audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0},this.singlePC.removeDownlinkQueue.delete(this.tinyId),yield this.singlePC.removeDownlink(this.tinyId,this.userId))})}};F([ce(i=>function(...t){return new Promise((e,r)=>{let n=s=>{this.off("closed",n),r(new L({code:v.API_CALL_ABORTED,message:$({key:w.CONNECTION_ABORTED,data:s})}))};this.on("closed",n),i.apply(this,t).then(e,r).finally(()=>{this.off("closed",n)})})})],Qs.prototype,"subscribe",1);var np=Qs;var{isString:Zs,isPlainObject:nf,isUndefined:zt,getNetworkType:sf,getTerminalType:of,isEmpty:Pn}=Ke,Pt=class extends Xs{constructor(e){super(e);this.privateMapKey="";this._heartbeat=-1;this._lastHeartBeatTime=-1;this._joinTimeout=-1;this._firstPublishedList=null;this._joinReject=null;this._isPublishing=!1;this._isRelayChanged=!1;this.uplinkConnection=null;this.singlePC=null;this._enableSPC=!0;this._changeBigSmallRecords=new Map;this._networkQuality=null;this._networkType=sf();this._turnServers=[];this._syncUserListInterval=-1;this._smallStreamConfig={bitrate:100,frameRate:15,height:120,width:160};this.enableSEI=!1;this._enableAudioVolumeEvaluation=!1;this._audioVolumeIntervalId=null;this._enableMultiAuxStream=!1;this._pureAudioPushMode=!1;this._stats=new Rn(this,this._log),this.userManager=new Us(this.userId,this._log),this._version=We,this.sdpSemantics=Pr,zt(e.sdpSemantics)?Bt.isUnifiedPlanDefault()&&(this.sdpSemantics=gi):this.sdpSemantics=e.sdpSemantics,this._log.info(`sdpSemantics: ${this.sdpSemantics}, netType: ${this._networkType}`),this.audioManager=new Ns({room:this}),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=zt(e.enableMultiAuxStream)?!1:e.enableMultiAuxStream,this.enableSEI=e.enableSEI,!zt(e.enableSPC)&&Ts&&(this._enableSPC=e.enableSPC),this._initBusinessInfo(e)}get isMainStreamPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.isMainStreamPublished)}get isMainAudioPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.localMainAudioTrack)}get isAuxStreamPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.isAuxStreamPublished)}get hasAuxStream(){return[...this.remotePublishedUserMap.values()].findIndex(e=>e.muteState.hasAuxiliary)>=0}get userMap(){return this.userManager.userMap}get remotePublishedUserMap(){return this.userManager.remotePublishedUserMap}get tinyIdToUserIdMap(){return new Map([...this.remotePublishedUserMap.values()].map(e=>[e.tinyId,e.userId]))}join(e,r,n){return E(this,null,function*(){this.userManager.mySelfId=this.userId,this.userManager.on("1",o=>{this.emit("peer-join",o)}),this.userManager.on("2",o=>{this.closeDownLinkConnection(o,"remote user exitRoom"),this.emit("peer-leave",o)}),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",a=>{var o=Zc(a,[]);C.emit(S.REMOTE_PUBLISH_STATE_CHANGED,B({room:this},o)),this.emit("remote-publish-state-changed",B({},o))});let s=String(e.roomId||e.strRoomId);return this._joinOptions=e,new Promise((o,a)=>E(this,null,function*(){this._joinReject=a;try{this.checkDestroy(),yield this.initialize(),yield this.doJoin(e),o(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(c){this.reset(),a(c)}this._joinReject=null}))})}doJoin(e){return new Promise((r,n)=>E(this,null,function*(){var u,l,h;zt(e.role)||(this.role=e.role===20?"anchor":"audience"),zt(e.privateMapKey)||(this.privateMapKey=e.privateMapKey),this._signalChannel.once(ge.SETUP_FAILED,I=>{this.clearJoinTimeout(),C.emit(S.JOIN_SIGNAL_CONNECTION_END,{room:this,error:I}),n(I)}),be((l=(u=this.scheduleResult)==null?void 0:u.config)==null?void 0:l.singlePC)&&Ts&&(this._enableSPC=this.scheduleResult.config.singlePC);let s;if(this._enableSPC&&!this.singlePC){this.singlePC=new Ir({signalChannel:this._signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.once("error",()=>this.fallbackToMPC());try{s=yield this.singlePC.initialize()}catch(I){this.fallbackToMPC()}}this.keyPointManager.setConnectionType(this.singlePC?1:2);let o={roomId:String(e.roomId||e.strRoomId),useStringRoomId:this.useStringRoomId,privateMapKey:this.privateMapKey,trtcRole:this.role==="anchor"?20:21,trtcScene:this.scene==="live"?2:1,sdpSemantics:this.sdpSemantics,version:this._version,ua:navigator&&navigator.userAgent||"",terminalType:of(),netType:Si[this._networkType],bussinessInfo:this._businessInfo,ability:s},{bussinessInfo:a,pushUserCdnInfo:c}=this.publishCDNManager.handleCDNConfigForJoinData(this._businessInfo);Object.assign(o,{bussinessInfo:a,pushUserCdnInfo:c}),this._log.debug(`join room signal data: ${JSON.stringify(o)}`);let d=5e3;((h=this.scheduleResult.config)==null?void 0:h.enterRoomTimeout)&&this.scheduleResult.config.enterRoomTimeout>=1&&(d=this.scheduleResult.config.enterRoomTimeout*1e3),this._joinTimeout=window.setTimeout(()=>{this._log.error("join room timeout observed"),n(new L({code:v.JOIN_ROOM_FAILED,message:$({key:w.JOIN_ROOM_TIMEOUT})}))},d),C.emit(S.JOIN_SEND_CMD,{room:this}),this._signalChannel.send(this.singlePC?ne.SPC_JOIN_ROOM:ne.JOIN_ROOM,o),this._signalChannel.once(Z.JOIN_ROOM_RESULT,I=>{this.clearJoinTimeout();let{code:T,message:N,data:H}=I.data;C.emit(S.JOIN_RECEIVED_CMD_RES,{room:this,code:T}),T===0?(this._log.info("Join room success, start heartbeat"),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=H.publishers,this.singlePC&&this.singlePC.connect(H.ability).catch(()=>{}),r()):(this._log.error(`Join room failed result: ${T} error: ${N}`),n(new L({code:v.JOIN_ROOM_FAILED,extraCode:T,message:$({key:w.JOIN_ROOM_FAILED,data:{error:N,code:T}})})))})}))}reJoin(){return E(this,null,function*(){if(!this.isJoined){this._log.warn("reJoin abort");return}try{this._log.warn(`reJoin pending: ${this._joinOptions.roomId}`),this.singlePC&&(this.singlePC.close(),this.singlePC=null),this._signalChannel.close(),yield this._signalChannel.connect(),yield this.doJoin(te(B({},this._joinOptions),{role:this.role==="anchor"?20:21,privateMapKey:this.privateMapKey})),this._log.warn("reJoin success"),Ee.logSuccessEvent({userId:this.userId,eventType:Lt.REJOIN}),this.singlePC?(yield this.singlePC.waitForPeerConnectionConnected(),this.uplinkConnection instanceof Wc&&this.uplinkConnection.onSinglePCReconnected(),this.remotePublishedUserMap.forEach(e=>{e.installEvents(),e.doSubscribe()})):(this.checkConnectionsToReconnect(),this.uplinkConnection instanceof Ks&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()),this.mixTranscodeManager.reStartMixTranscode()}catch(e){this._log.warn(`reJoin fail ${e}`),this.reset(),Ee.logFailedEvent({userId:this.userId,eventType:Lt.REJOIN,error:e}),this.emit("error",new L({code:v.JOIN_ROOM_FAILED,message:$({key:w.REJOIN_ROOM_FAILED,data:{roomId:this._joinOptions.roomId}})}))}})}initialize(){this._log.info("setup signal channel");let{mainUrl:e,backupUrl:r}=this.getSignalChannelUrl();return this._signalChannel=new En({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:e,backupUrl:r,room:this}),this._networkQuality||(this._networkQuality=new Bi({signalChannel:this._signalChannel,room:this}),this._networkQuality.on(Bi.EVENT_NETWORK_QUALITY,n=>{this.emit("network-quality",n)})),this._signalChannel.on(ge.CONNECTION_STATE_CHANGED,n=>{C.emit(S.SIGNAL_CONNECTION_STATE_CHANGED,B({room:this},n)),this.emit("signal-connection-state-changed",n)}),this._signalChannel.on(ge.RECONNECT_FAILED,n=>{this.reset(),this.emit("error",n)}),this._signalChannel.once(ge.SETUP_SUCCESS,n=>{this.tinyId=n.signalInfo.tinyId,C.emit(S.JOIN_SIGNAL_CONNECTION_END,{room:this})}),this._signalChannel.on(Z.PEER_JOIN,n=>{let{srcTinyId:s,userId:o,role:a}=n.data.data;this.userManager.addUser({userId:o,tinyId:s,role:a})}),this._signalChannel.on(Z.PEER_LEAVE,n=>{let{userId:s,reason:o=0}=n.data.data;this.userManager.deleteUser(s,o)}),this._signalChannel.on(Z.UPDATE_REMOTE_MUTE_STAT,n=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=10*1e3&&this.doHeartbeat(),this.onPublishedUserList(n.data)}),this._signalChannel.on(Z.CLIENT_BANNED,n=>{let s=n.data.data,{reason:o}=s;if(Ee.uploadEvent({log:`stat-banned:${o}`,userId:this.userId}),o==="user_time_out"){this._log.warn(`${o} last heart beat time: ${this._lastHeartBeatTime} interval: ${Date.now()-this._lastHeartBeatTime}, visibility: ${document.visibilityState}`),this.reJoin();return}this._log[o==="kick"?"error":"info"](`user was banned because of [${o}]`),this.reset(),this.emit("banned",{reason:o})}),C.emit(S.JOIN_SIGNAL_CONNECTION_START,{room:this}),this._signalChannel.connect()}leave(){return E(this,null,function*(){try{yield this.doHeartbeat()}catch(e){}C.emit(S.LEAVE_SEND_CMD,{room:this}),this._log.info("leave() => leaving room"),this._signalChannel.send(ne.LEAVE_ROOM),this.reset()})}clearNetworkQuality(){this._networkQuality&&(this._networkQuality.stop(),this._networkQuality=null)}closeConnections(){this.remotePublishedUserMap.forEach(e=>{this.closeDownLinkConnection(e.userId,"you exitRoom")})}clearJoinTimeout(){clearTimeout(this._joinTimeout),this._joinTimeout=-1}startHeartbeat(){this._heartbeat===-1&&(this._heartbeat=me.run(kt,this.doHeartbeat.bind(this),{delay:2e3}))}stopHeartbeat(){this._heartbeat!==-1&&(this._log.info("stopHeartbeat"),me.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return E(this,null,function*(){var a;let e=this.badCaseDetector.getMonitorFreeze(),r=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:e});if(this.badCaseDetector.resetMonitor(),!((a=this._signalChannel)!=null&&a.isConnected))return;let n=this._signalChannel.isConnected?Zu(this.userId):[],s=B({str_sdk_version:ji,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:Si[this._networkType]},msg_event_msg:n,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},r);C.emit(S.HEARTBEAT_REPORT,{room:this,report:s}),this._signalChannel.send(ne.ON_QUALITY_REPORT,s);let o=Date.now();this._lastHeartBeatTime>0&&o-this._lastHeartBeatTime>1e4&&this._log.warn(`heartbeat took ${o-this._lastHeartBeatTime}`),this._signalChannel.isConnected&&(this._lastHeartBeatTime=o),!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)})}onPublishedUserList(e){if(!this.isJoined)return;let r=e.data.userList.map(({userId:n,srcTinyId:s,flag:o})=>{let a=this.remotePublishedUserMap.get(n);return a&&this._changeBigSmallRecords.has(n)&&this.checkSubscribeBigSmallVideo(a),{userId:n,tinyId:s,flag:o}});C.emit(S.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:r}),this.userManager.setRemotePublishedUserList(r)}closeUplink(e="you unpublished"){this.uplinkConnection&&(this.localTracks.size>0&&this.uplinkConnection.doUnpublish(),this.uplinkConnection.close(e),this.uplinkConnection=null),this.localTracks.forEach(r=>r.unpublish()),this.localTracks.clear()}createDownlinkConnection({userId:e,tinyId:r,flag:n}){let s=new(this.singlePC?np:Ac)({userId:e,tinyId:r,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,flag:n});this.userManager.addRemotePublishedUser(s),this.installDownlinkEvents(s,e),this.emit("remote-published",s)}closeDownLinkConnection(e,r="remote user unpublished"){let n=this.remotePublishedUserMap.get(e);n&&(n.close(r),this.emit("remote-unpublished",n))}installDownlinkEvents(e,r){e.on("sei-message",n=>{this.emit("sei-message",n)}),e.on("error",n=>{let s=n.getCode();s!==v.ICE_TRANSPORT_ERROR&&(s===v.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(r),this.emit("error",n))}),e.on("connection-state-changed",n=>{this.emit("media-connection-state-changed",te(B({},n),{userId:e.userId}))}),e.on("firewall-restriction",()=>{this.emit("firewall-restriction")})}startSyncUserListInterval(){this._syncUserListInterval===-1&&(this._syncUserListInterval=me.run(kt,this.syncUserList.bind(this)))}stopSyncUserListInterval(){me.clearTask(this._syncUserListInterval),this._syncUserListInterval=-1}syncUserList(){return this.getUserList().then(e=>{this.userManager.setUserList(e)}).catch(e=>{this._log.debug(`sync user list failed: ${e}`)})}getUserList(){var e;return(e=this._signalChannel)!=null&&e.isConnected?this._signalChannel.sendWaitForResponse({command:ne.GET_USER_LIST,responseCommand:Z.USER_LIST_RES,enableLog:!1,timeout:2e3}).then(({data:r})=>{let{code:n,message:s}=r;if(n===0)return(r.data&&r.data.userList||[]).map(({userId:a,srcTinyId:c,role:d})=>({userId:a,tinyId:c,role:d}));throw $({key:w.SIGNAL_RESPONSE_FAILED,data:{signalResponse:Z.USER_LIST_RES,code:n,message:s}})}):Promise.reject("not connected")}getAllConnections(){let e=[...this.remotePublishedUserMap.values()];return this.uplinkConnection&&e.push(this.uplinkConnection),e}isRelayMaybeFailed(){if(!this._signalChannel.isOnline||!Tc)return!1;if(this.singlePC)return this.singlePC.reconnectionCount>6;let e=this.getAllConnections();if(e.length===0)return!1;for(let r=0;r<e.length;r++)if(e[r].getReconnectionCount()<6)return!1;return!0}checkConnectionsToReconnect(){this.singlePC||this.getAllConnections().forEach(r=>{if(r instanceof Qe&&!r.getIsReconnecting()){let n=r.getPeerConnection();n&&n.connectionState===fe.CLOSED&&(this._log.warn(`[${r.getUserId()}] pc is closed but not reconnect`),r.startReconnection())}})}fallbackToMPC(){return E(this,null,function*(){var e;if(this._log.warn("fallback to multi pc"),Ee.uploadEvent({log:"stat-fallback",userId:this.userId}),this._enableSPC=!1,(e=this.singlePC)==null||e.close(),this.singlePC=null,yield this.reJoin(),this.uplinkConnection){let r=this.uplinkConnection;this.uplinkConnection=new Ks({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}),r.isMainStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:r.localMainAudioTrack,localVideoTrack:r.localMainVideoTrack,isAuxiliary:!1})),r.isAuxStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:r.localAuxAudioTrack,localVideoTrack:r.localAuxVideoTrack,isAuxiliary:!0}))}this.remotePublishedUserMap.forEach(r=>{let n=new Ac({userId:r.userId,tinyId:r.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,flag:r.flag,remoteAudioTrack:r.remoteAudioTrack,remoteVideoTrack:r.remoteVideoTrack,remoteAuxiliaryTrack:r.remoteAuxiliaryTrack});this.installDownlinkEvents(n,r.userId),this.remotePublishedUserMap.set(r.userId,n),r.isMainStreamSubscribed&&n.subscribe(r.subscribeState,"main"),r.isAuxStreamSubscribed&&n.subscribe(r.subscribeState,"auxiliary")})})}destroy(){this._isDestroyed||(super.destroy(),this._joinReject&&(this._joinReject(new L({code:v.INVALID_OPERATION,message:$({key:w.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners())}switchRole(e){return E(this,null,function*(){this.role!==e&&(e==="audience"&&this.uplinkConnection&&this.closeUplink("you switch role to audience"),yield this.doSwitchRole(e))})}doSwitchRole(e){let r={command:ne.SWITCH_ROLE,data:{role:e==="anchor"?20:21,privateMapKey:this.privateMapKey},responseCommand:Z.SWITCH_ROLE_RES,retries:1};return this._log.info(`switchRole signal data: ${JSON.stringify(r.data)}`),this._signalChannel.sendWaitForResponseWithRetry(r).then(n=>{let{code:s,message:o}=n.data;if(s!==0)throw new L({code:v.SWITCH_ROLE_FAILED,message:$({key:w.SWITCH_ROLE_FAILED,data:{message:o,code:s}})});this.role=e}).catch(n=>{throw n instanceof L&&n.getCode()===v.API_CALL_TIMEOUT&&(n=new L({code:v.SWITCH_ROLE_FAILED,message:$({key:w.SWITCH_ROLE_TIMEOUT})})),this._log.error(n),n})}publish(...e){return E(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor")return;C.emit(S.PUBLISH_START,{room:this});let r={},n={};this._isPublishing=!0,e.forEach(s=>{!s.mediaTrack||(s instanceof Gt&&(s instanceof Pi?(n.audio=s,this.audioManager.addScreenAudioTrack(s)):(r.audio=s,this.audioManager.addAudioTrack(s))),s instanceof mt&&(s instanceof bt&&s.mediaType===2?n.video=s:r.video=s),s.setPublishStarting(this))});try{let s=Pn(r),o=Pn(n);(!s||!o)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new Wc({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}):this.uplinkConnection=new Ks({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}),this.uplinkConnection.on("connection-state-changed",c=>{this.emit("media-connection-state-changed",te(B({},c),{userId:this.userId}))}),this.uplinkConnection.on("firewall-restriction",()=>{this.emit("firewall-restriction")}),this.uplinkConnection.on("error",c=>{let d=c.getCode();d!==v.ICE_TRANSPORT_ERROR&&(d===v.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",c))}));let a=e.map(c=>c.kind).join(",");s||(this._log.info(`publish() => main ${a}`),yield this.uplinkConnection.publish({localAudioTrack:r.audio,localVideoTrack:r.video,isAuxiliary:!1}),this._log.info("main is published")),o||(this._log.info(`publish() => aux ${a}`),yield this.uplinkConnection.publish({localAudioTrack:n.audio,localVideoTrack:n.video,isAuxiliary:!0}),this._log.info("aux is published")),this._isPublishing=!1,e.forEach(c=>{!c.mediaTrack||(this.localTracks.add(c),c.publish(this))})}catch(s){throw e.forEach(o=>{let a="error";s.message.includes("timeout")?a="timeout":s.code===v.API_CALL_ABORTED&&(a="api-call"),o.setPublishStopped(a,a==="error"?s:void 0)}),this._isPublishing=!1,s}})}unpublish(...e){return E(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||!this.isMainStreamPublished&&!this.isAuxStreamPublished||!this.uplinkConnection)return;let r={},n={};e.forEach(s=>{!s.mediaTrack||(s instanceof Gt&&(s instanceof Pi?n.audio=s:r.audio=s),s instanceof mt&&(s instanceof bt&&s.mediaType===2?n.video=s:r.video=s))});try{let s=e.map(o=>o.kind).join(",");Pn(r)||(this._log.info(`unpublish() => main ${s}`),yield this.uplinkConnection.unpublish({localAudioTrack:r.audio,localVideoTrack:r.video})),Pn(n)||(this._log.info(`unpublish() => aux ${s}`),yield this.uplinkConnection.unpublish({localAudioTrack:n.audio,localVideoTrack:n.video}))}catch(s){}e.forEach(s=>{!s.mediaTrack||(s.unpublish(),this.localTracks.delete(s))}),this.localTracks.size===0&&!this.audioManager.isMixed&&this.closeUplink("you unpublished")})}addTrack(e){return!this.uplinkConnection||!e.mediaTrack?Promise.resolve():(e.setPublishStarting(this),this.uplinkConnection.addTrack(e).then(r=>(e.publish(this),r)))}removeTrack(e){return!this.uplinkConnection||!e.mediaTrack?Promise.resolve():this.uplinkConnection.removeTrack(e).then(r=>(e.unpublish(),r))}replaceTrack(e){return!this.uplinkConnection||!e.mediaTrack?Promise.resolve():this.uplinkConnection.replaceTrack(e).then(r=>{C.emit(S.LOCAL_TRACK_REPLACED,{track:e})})}setBandWidth(e){return E(this,null,function*(){!this.uplinkConnection||(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())})}subscribe(...e){return E(this,null,function*(){let{userId:r}=e[0],n=this.remotePublishedUserMap.get(r);if(!n)return;let s=e.find(o=>o.mediaType===2)?"auxiliary":"main";try{let o=B({},n.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:o.audio=!0;break;case 4:o.video=!0;break;case 2:o.auxiliary=!0;break}});let a=this._changeBigSmallRecords.get(r);a&&a.options.smallVideo&&n.muteState.hasSmall&&o.video&&(o.video=!1,o.smallVideo=!0),C.emit(S.SUBSCRIBE_START,{room:this,streamType:s,remotePublishedUser:n,subscribeState:o}),this._log.info(`subscribe() => ${r} ${s} [${Ws(o)}] prev: [${Ws(n.subscribeState)}]`),yield n.subscribe(o,s),n.remoteVideoTrack.setMediaType(o.smallVideo?8:4),e.forEach(c=>c.subscribe()),C.emit(S.SUBSCRIBE_SUCCESS,{room:this,streamType:s,remotePublishedUser:n})}catch(o){let a=o instanceof L?o.getCode():v.UNKNOWN,c=o;throw o instanceof L?a===v.REMOTE_STREAM_NOT_EXIST&&(c=new L({code:v.API_CALL_ABORTED,message:$({key:w.API_CALL_ABORTED,data:{message:o.message,userId:r,streamType:s}})}),this._log.warn(c)):(c=new L({code:a,message:$({key:w.SUBSCRIBE_FAILED,data:{message:o.message,userId:r,streamType:s}})}),this._log.error(c)),c}})}unsubscribe(...e){return E(this,null,function*(){let{userId:r}=e[0],n=this.remotePublishedUserMap.get(r);if(!n)return;let s=e.find(o=>o.mediaType===2)?"auxiliary":"main";this._log.info(`unsubscribe() => ${r} ${s}`);try{yield n.unsubscribe({remoteTracks:e,streamType:s})}catch(o){this._log.warn(`unsubscribe() => failed ${o}`)}e.forEach(o=>{o.unsubscribe(),o.mediaType===8&&o.setMediaType(4)}),C.emit(S.UNSUBSCRIBE_SUCCESS,{room:this,streamType:s,remotePublishedUser:n})})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAudioVolumeEvaluation(e=2e3,r){if(e<=0){this._enableAudioVolumeEvaluation=!1,me.clearTask(this._audioVolumeIntervalId),this._audioVolumeIntervalId=null;return}e=Math.floor(Math.max(e,100)),C.emit(S.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&(me.clearTask(this._audioVolumeIntervalId),this._audioVolumeIntervalId=null),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=me.run(ii,()=>{var s,o;let n=[];if((s=this.uplinkConnection)!=null&&s.localMainAudioTrack){let a=Math.floor(this.uplinkConnection.localMainAudioTrack.getAudioLevel()*100);n.push({userId:"",volume:a})}(o=this.remotePublishedUserMap)==null||o.forEach(a=>{if(a.muteState.hasAudio){let c=Math.floor(a.remoteAudioTrack.getAudioLevel()*100);n.push({userId:a.userId,volume:c})}}),this.emit("audio-volume",n)},{fps:1e3/e,backgroundTask:r})}getLocalAudioStats(){return E(this,null,function*(){let e={};if(e[this.userId]={bytesSent:0,packetsSent:0},this.uplinkConnection){let r=yield this._stats.getSenderStats(this.uplinkConnection);e[this.userId]={bytesSent:r.audio.bytesSent,packetsSent:r.audio.packetsSent}}return e})}getLocalVideoStats(){return E(this,null,function*(){let e={};if(e[this.userId]={bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0},this.uplinkConnection){let{video:{bytesSent:r,packetsSent:n,framesEncoded:s,framesSent:o,frameWidth:a,frameHeight:c}}=yield this._stats.getSenderStats(this.uplinkConnection);e[this.userId]={bytesSent:r,packetsSent:n,framesEncoded:s,framesSent:o,frameWidth:a,frameHeight:c}}return e})}getTransportStats(){return E(this,null,function*(){let e={rtt:0,downlinksRTT:{}};if(this.uplinkConnection){let r=yield this._stats.getSenderStats(this.uplinkConnection);e.rtt=r.rtt}for(let[,r]of this.remotePublishedUserMap){let n=yield this._stats.getReceiverStats(r);e.downlinksRTT[n.userId]=n.rtt}return e})}getRemoteVideoStats(e){return E(this,null,function*(){let r={};for(let[n,s]of this.remotePublishedUserMap)e==="main"&&s.muteState.hasVideo&&(r[n]=s.remoteVideoTrack.stat),e==="auxiliary"&&s.muteState.hasAuxiliary&&(r[n]=s.remoteAuxiliaryTrack.stat);return r})}getRemoteAudioStats(){return E(this,null,function*(){let e={};for(let[r,n]of this.remotePublishedUserMap)n.muteState.hasAudio&&(e[r]=n.remoteAudioTrack.stat);return e})}setProxyServer(e){if(Zs(e)){if(!e.startsWith("wss://"))throw new L({code:v.INVALID_PARAMETER,message:"invalid websocket url"});this.proxy_ws=e}else if(nf(e)){let{websocketProxy:r,loggerProxy:n}=e;r&&(this.proxy_ws=r),n&&Hn(n)}}setTurnServer(e,r){this._log.info(`set turn server: ${JSON.stringify(e)} ${r||""}`);let n=[];Array.isArray(e)?e.forEach(s=>n.push(Ke.getTurnServer(s))):Ke.isPlainObject(e)&&n.push(Ke.getTurnServer(e)),this._turnServers=n,r&&(this._iceTransportPolicy=r)}sendStartMixTranscode(e){return this._signalChannel.sendWaitForResponse({command:ne.START_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:Z.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this._signalChannel.sendWaitForResponse({command:ne.STOP_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:Z.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"})}sendStartPublishCDN(e,r=!0){return this._signalChannel.sendWaitForResponse({command:r?ne.START_PUBLISH_TENCENT_CDN:ne.START_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:r?Z.START_PUBLISH_TENCENT_CDN_RES:Z.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"})}sendStopPublishCDN(e,r=!0){return this._signalChannel.sendWaitForResponse({command:r?ne.STOP_PUBLISH_TENCENT_CDN:ne.STOP_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:r?Z.STOP_PUBLISH_TENCENT_CDN_RES:Z.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}getIceServers(){return this._turnServers.length===0&&this.scheduleResult.iceServers?this.scheduleResult.iceServers:this._turnServers}getIceTransportPolicy(){return this._iceTransportPolicy||this.scheduleResult.iceTransportPolicy||"all"}getLogger(){return this._log}enableAIVoice(){throw new Error("Method not implemented.")}getSignalChannelUrl(){let e={mainUrl:"",backupUrl:""},r=Ke.getEnv();return r?(e.mainUrl=`wss://${r}.rtc.qq.com`,e.backupUrl=e.mainUrl):this.proxy_ws?(e.mainUrl=this.proxy_ws,e.backupUrl=e.mainUrl):Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(e.mainUrl=`wss://${this.scheduleResult.domains[0]}`,e.backupUrl=e.mainUrl,this.scheduleResult.domains[1]&&(e.backupUrl=`wss://${this.scheduleResult.domains[1]}`)),e}getSignalInfo(){var e;return((e=this._signalChannel)==null?void 0:e.getSignalInfo())||{}}reset(){this.mixTranscodeManager.reset(),this.publishCDNManager.reset(),this.stopSyncUserListInterval(),this.stopHeartbeat(),this.closeConnections(),this.clearNetworkQuality(),this.closeUplink("you exitRoom"),this._signalChannel&&(this._log.info("destroying SignalChannel"),this._signalChannel.close()),this._stats.reset(),this.userManager.clear(),this.userManager.removeAllListeners(),this.singlePC&&(this.singlePC.close(),this.singlePC=null)}checkSubscribeBigSmallVideo(e){return E(this,null,function*(){let r=e==null?void 0:e.muteState.hasSmall,n=e==null?void 0:e.muteState.hasVideo;if(!r&&!n||!e.isBigStreamSubscribed&&!e.isSmallStreamSubscribed)return;let s=e.getUserId(),o=this._changeBigSmallRecords.get(s)||{},{subscribeState:a}=e,{options:c,isSubscribing:d,reSubscribeCount:u}=o;if(c.video&&a.video||c.smallVideo&&a.smallVideo&&r||d)return;let l={audio:a.audio,auxiliary:a.auxiliary,video:c.video,smallVideo:c.smallVideo};if(r&&e.isBigStreamSubscribed||e.isSmallStreamSubscribed)try{c&&!d&&u>=1&&(o.isSubscribing=!0,o.reSubscribeCount=u-1,!r&&e.isSmallStreamSubscribed&&(l.video=!0,l.smallVideo=!1),yield e==null?void 0:e.subscribe(l,"main"),e.remoteVideoTrack.setMediaType(l.smallVideo?8:4),this._log.info(`change [${s}] to ${l.smallVideo?"small":"big"} video successfully. count ${Lr-o.reSubscribeCount}.`),o.isSubscribing=!1,o.reSubscribeCount=Lr)}catch(h){this._log.info(`change [${s}] to ${l.smallVideo?"small":"big"} video failed. count ${Lr-o.reSubscribeCount}.`),o.isSubscribing=!1,u===0&&this._changeBigSmallRecords.delete(s)}})}changeType(e,r){let s={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:Lr};this._changeBigSmallRecords.set(r.userId,s),this._log.info(`set [${r.userId}] video prefer type: ${e?"small":"big"}`)}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(e){this._businessInfo=e.businessInfo;let r={};if(Zs(e.businessInfo)&&(r=JSON.parse(e.businessInfo)),!zt(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new L({code:v.INVALID_PARAMETER,message:$({key:w.INVALID_PURE_AUDIO})});this._pureAudioPushMode=e.pureAudioPushMode,r.Str_uc_params||(r.Str_uc_params={}),r.Str_uc_params.pure_audio_push_mod=this._pureAudioPushMode}if(!zt(e.streamId))if(Zs(e.streamId)&&String(e.streamId)&&String(e.streamId).length<=64)r.Str_uc_params||(r.Str_uc_params={}),r.Str_uc_params.userdefine_streamid_main=e.streamId;else throw new L({code:v.INVALID_PARAMETER,message:$({key:w.INVALID_STREAMID})});if(!zt(e.userDefineRecordId)){let n=/^[A-Za-z0-9_-]{1,64}$/gi;if(e.userDefineRecordId.match(n)===null)throw new L({code:v.INVALID_PARAMETER,message:$({key:w.INVALID_USER_DEFINE_RECORDID})});r.Str_uc_params||(r.Str_uc_params={}),r.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!zt(e.userDefinePushArgs))if(Zs(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256)r.Str_uc_params||(r.Str_uc_params={}),r.Str_uc_params.userdefine_push_args=e.userDefinePushArgs;else throw new L({code:v.INVALID_PARAMETER,message:$({key:w.INVALID_USER_DEFINE_PUSH_ARGS})});Pn(r)||(this._businessInfo=JSON.stringify(r))}startPlugin(e,r){return E(this,null,function*(){var n,s;e==="AudioMixer"&&(yield this.audioManager.addMusicSource(r),this.isJoined&&((n=this.uplinkConnection)==null?void 0:n.localMainAudioTrack)&&(yield this.replaceTrack((s=this.uplinkConnection)==null?void 0:s.localMainAudioTrack)))})}updatePlugin(e,r){return E(this,null,function*(){e==="AudioMixer"&&(yield this.audioManager.updateMusicSource(r))})}stopPlugin(e,r){return E(this,null,function*(){e==="AudioMixer"&&(yield this.audioManager.removeMusicSource(r))})}sendSEI(e,r){var n;(n=this.uplinkConnection)==null||n.sendSEI(e,r)}};F([wc(["left",et.INIT],"joined"),El()],Pt.prototype,"join",1),F([wc("joined","left",{ignoreError:!0}),Tl(),jl("leave room"),Cn({fnName:"publish",validateArgs:!1}),Cn({fnName:"unsubscribe",validateArgs:!1})],Pt.prototype,"leave",1),F([Nn(),An({settings:{retries:ti,timeout:i=>rt(i)},onError(i,t,e){var r;(r=i.message)!=null&&r.includes("timeout")?(this._log.warn("publish timeout"),t()):(this._log.error(`publish failed: ${i}`),e(i))}})],Pt.prototype,"publish",1),F([Cn({fnName:"publish",callback(...i){var t;this.localTracks.size===0&&((t=this.uplinkConnection)==null||t.close("you unpublished"),this.uplinkConnection=null,i.forEach(e=>e.setPublishStopped("api-call")))}}),Kl("api-call"),Nn()],Pt.prototype,"unpublish",1),F([Uc((...i)=>i[0].userId),An({settings:{retries:ti,timeout:i=>rt(i)},onError(i,t,e){i.message.includes("timeout")?(this._log.warn("subscribe timeout"),t()):(this._log.error(`subscribe failed: ${i}`),e(i))}})],Pt.prototype,"subscribe",1),F([Cn({fnName:"subscribe",callback(...i){this.singlePC||i.forEach(t=>{let e=this.remotePublishedUserMap.get(t.userId);e&&!e.isMainStreamSubscribed&&!e.isAuxStreamSubscribed&&e.close("you unsubscribed")})}}),Uc((...i)=>i[0].userId)],Pt.prototype,"unsubscribe",1);fn.create=fn._create.bind(fn,Pt);var ox=fn;export{ox as default};
102
+ `);s&&(this._log.info("updating answer"),yield this._peerConnection.setRemoteDescription({type:"answer",sdp:c}))})}replaceTrack(e){return E(this,null,function*(){var o;let r=(o=this._peerConnection)==null?void 0:o.getSenders();if(!r||r.length===0||!e.mediaTrack)return;let n=e.mediaTrack,s=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;if(this._log.info(`is replacing ${n.kind} track on ${s?m.AUXILIARY:m.MAIN} stream`),n.kind===m.AUDIO&&r[0]&&(this._audioManager.addAudioTrack(e),this._audioManager.isMixed&&(n=this._audioManager.mediaStreamTrack),yield r[0].replaceTrack(n)),n.kind===m.VIDEO){if(!s&&r[1]&&(yield r[1].replaceTrack(n),this._smallGenerator&&r[2])){this._log.info("replacing smallVideo"),this._smallGenerator.destroy(),this._smallGenerator=new Zt(this.localMainVideoTrack),yield this._smallGenerator.initialize();let a=this._smallGenerator.generateSmallVideoTrack(this._room.smallStreamConfig);yield r[2].replaceTrack(a)}s&&r[3]&&(yield r[3].replaceTrack(n))}})}setBandwidth(s){return E(this,arguments,function*({bandwidth:e,type:r,videoType:n}){if(this.singlePC){let o={};r===m.AUDIO?o.audio=e:n==="big"?o.bigVideo=e:n==="small"?o.smallVideo=e:o.auxVideo=e,yield this.singlePC.setBandwidth(o)}})}sendMutedFlag(e){var s,o,a;if(e===this.localAuxAudioTrack||e===this.localAuxVideoTrack)return;let n={audio:!!((s=this.localMainAudioTrack)!=null&&s.muted),bigVideo:!!((o=this.localMainVideoTrack)!=null&&o.muted),auxVideo:!!((a=this.localAuxVideoTrack)!=null&&a.muted)};this._log.info(`send muted state: ${JSON.stringify(n)}`),this._signalChannel.send(ne.UPDATE_MUTE_STAT,n)}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&C.emit(S.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(e=m.VIDEO){if(this._peerConnection){let r=this._peerConnection.getSenders();if(e===m.AUXILIARY&&r[3]&&r[3].track)return r[3].track.id;if(e===m.VIDEO&&r[1]&&r[1].track)return r[1].track.id}if(this.localMainVideoTrack&&e===m.VIDEO){let r=this.localMainVideoTrack.mediaTrack;if(r)return r.id}if(this.localAuxVideoTrack&&e===m.AUXILIARY){let r=this.localAuxVideoTrack.mediaTrack;if(r)return r.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,r){if(e!==0)throw e===xi?(this._log.error(xe.NOT_SUPPORTED_H264ENCODE),new M({code:v.NOT_SUPPORTED_H264,message:B({key:V.NOT_SUPPORTED_H264ENCODE})})):new M({code:v.UNKNOWN,message:B({key:V.SIGNAL_RESPONSE_FAILED,data:{signalResponse:Q.PUBLISH_RESULT,code:e,message:r}})})}sendSEI(e,r){var n;(n=this._sei)==null||n.push(e,r)}onSinglePCReconnected(){return E(this,null,function*(){this.isMainStreamPublished&&(yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0}))})}},_d=md;var cx=_(f());function wf(i){return Object.keys(i).filter(t=>i[t])}var bo=class extends ir{constructor(e){super(ee(w({},e),{isUplink:!1}));p(this,"_flag",0);p(this,"role","anchor");p(this,"remoteAudioTrack");p(this,"remoteVideoTrack");p(this,"remoteAuxiliaryTrack");p(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0});this.flag=e.flag,this.remoteAudioTrack=new kr(this._room,this),this.remoteVideoTrack=new Ji(this._room,this),this.remoteAuxiliaryTrack=new xr(this._room,this),this.initialize()}get subscribeState(){let e={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(this.remoteVideoTrack.mediaType&8?e.smallVideo=!0:e.video=!0),this.remoteAudioTrack.isSubscribed&&(e.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(e.auxiliary=!0),e}get muteState(){return li(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var r,n,s;e!==this._flag&&(this._flag=e,(r=this.remoteAudioTrack)==null||r.onFlagChanged(),(n=this.remoteVideoTrack)==null||n.onFlagChanged(),(s=this.remoteAuxiliaryTrack)==null||s.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===m.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents(),this.removeDownlink()}installEvents(){!this.singlePC||(this.listeners("track").includes(this.onTrack)||this.singlePC.on("track",this.onTrack,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||this.singlePC.on("spc-reconnected",this.onSinglePCReconnected,this))}uninstallEvents(){!this.singlePC||(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this))}emitConnectionStateChangedEvent(e){var s,o;let r=this._currentState,n=super.emitConnectionStateChangedEvent(e);return n&&r!==e&&((s=this.remoteVideoTrack)==null||s.emit("connection-state-changed",{prevState:r,state:e}),(o=this.remoteAuxiliaryTrack)==null||o.emit("connection-state-changed",{prevState:r,state:e})),n}onTrack(e){let r=e.streams[0],{track:n}=e;if(r.id.split("-")[0]!==this.tinyId)return;let a=r.id.includes("aux")?"auxiliary":"main";this._log.debug(`ontrack ${a} ${n.kind}`);let c=m.AUDIO;n.kind===m.VIDEO&&(c=a===m.MAIN?m.VIDEO:m.AUXILIARY);let d=this.remoteAudioTrack;c===m.VIDEO?d=this.remoteVideoTrack:c===m.AUXILIARY&&(d=this.remoteAuxiliaryTrack),d.setMediaStream(r),d.setMediaStreamTrack(n)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,r){return E(this,null,function*(){try{if(this.isSubscriptionStateNotChanged(e))return;if(this.hasSSRC){let n="subscribe_change";Object.values(e).find(s=>s===!0)||(n="unsubscribe"),yield this.sendSubscription(n,e)}else yield this.doSubscribe(e)}catch(n){throw this._room.isJoined&&this.isStreamUnpublished(r)?(this._log.warn(`${n.message} ${JSON.stringify(this.muteState)}`),new M({code:v.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):n}})}unsubscribe(n){return E(this,arguments,function*({remoteTracks:e,streamType:r}){var a;if(r==="main"&&!this.isMainStreamSubscribed||r==="auxiliary"&&!this.isAuxStreamSubscribed){this._log.info(`${r} stream already unsubscribed`);return}let s=w({},this.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:s.audio=!1;break;case 4:s.video=!1;break;case 8:s.smallVideo=!1;break;case 2:s.auxiliary=!1;break;default:break}});let o="subscribe_change";Object.values(s).find(c=>c===!0)||(o="unsubscribe"),this._log.info(`${o==="unsubscribe"?o:"subscribe"} ${r} [${wf(s)}]`),o==="unsubscribe"&&((a=this.singlePC)==null||a.removeDownlinkQueue.add(this.tinyId)),yield this.sendSubscription(o,s),o==="unsubscribe"&&(this.remoteAudioTrack.setMediaStreamTrack(null),this.remoteVideoTrack.setMediaStreamTrack(null),this.remoteAuxiliaryTrack.setMediaStreamTrack(null),yield this.removeDownlink())})}sendSubscription(e,r=this.subscribeState){let n={srcTinyId:this.tinyId,srcUserId:this.userId},s=ne.UNSUBSCRIBE,o=Q.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(n={audio:r.audio,bigVideo:r.video,auxVideo:r.auxiliary,smallVideo:r.smallVideo,srcTinyId:this.tinyId},s=ne.SUBSCRIBE_CHANGE,o=Q.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:s,data:n,responseCommand:o,timeout:1e4}).then(({data:a})=>{if(a.code!==0){let c=new M({code:a.code,message:B({key:V.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(c),c}})}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}setDelay({audioDelay:e,videoDelay:r}){this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=r}onSinglePCReconnected(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary)&&this.doSubscribe(this.subscribeState,!1)}get hasSSRC(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}doSubscribe(){return E(this,arguments,function*(e=this.subscribeState,r=!0){if(!!this.singlePC){if(this.singlePC.addDownlinkQueue.add(this.tinyId),yield this.singlePC.waitForPeerConnectionConnected(),r||!this.hasSSRC){let n={audioSsrc:tr(),bigVideoSsrc:tr(),bigVideoRtxSsrc:tr(),auxVideoSsrc:tr(),auxVideoRtxSsrc:tr()},{audioSsrc:s,bigVideoSsrc:o,bigVideoRtxSsrc:a,auxVideoSsrc:c,auxVideoRtxSsrc:d}=n;this.ssrc={audio:s,video:o,videoRtx:a,auxiliary:c,auxiliaryRtx:d},this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc});let u=yield this._signalChannel.sendWaitForResponse({command:ne.SPC_SUBSCRIBE,responseCommand:Q.SPC_SUBSCRIBE_RESULT,data:{srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo,customData:!0,ssrc:n}});if(u.data.code!==0)throw yield this.removeDownlink(),new M({code:u.data.code,message:u.data.message});return}this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc})}})}removeDownlink(){return E(this,null,function*(){!this.singlePC||(this.ssrc={audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0},this.singlePC.removeDownlinkQueue.delete(this.tinyId),yield this.singlePC.removeDownlink(this.tinyId,this.userId))})}};H([ae(i=>function(...t){return new Promise((e,r)=>{let n=s=>{this.off("closed",n),r(new M({code:v.API_CALL_ABORTED,message:B({key:V.CONNECTION_ABORTED,data:s})}))};this.on("closed",n),i.apply(this,t).then(e,r).finally(()=>{this.off("closed",n)})})})],bo.prototype,"subscribe",1);var mp=bo;var{isString:Do,isPlainObject:Bf,isUndefined:ti,getNetworkType:$f,getTerminalType:Hf,isEmpty:rs}=ke,xt=class extends yo{constructor(e){super(e);this.privateMapKey="";this._heartbeat=-1;this._lastHeartBeatTime=-1;this._joinTimeout=-1;this._firstPublishedList=null;this._joinReject=null;this._isPublishing=!1;this._isRelayChanged=!1;this.uplinkConnection=null;this.singlePC=null;this._enableSPC=!0;this._changeBigSmallRecords=new Map;this._networkQuality=null;this._networkType=$f();this._turnServers=[];this._syncUserListInterval=-1;this._smallStreamConfig={bitrate:100,frameRate:15,height:120,width:160};this.enableSEI=!1;this._enableAudioVolumeEvaluation=!1;this._audioVolumeIntervalId=null;this._enableMultiAuxStream=!1;this._pureAudioPushMode=!1;this._stats=new Yn(this,this._log),this.userManager=new uo(this.userId,this._log),this._version=$e,this.sdpSemantics=Ir,ti(e.sdpSemantics)?Gt.isUnifiedPlanDefault()&&(this.sdpSemantics=ci):this.sdpSemantics=e.sdpSemantics,this._log.info(`sdpSemantics: ${this.sdpSemantics}, netType: ${this._networkType}`),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=ti(e.enableMultiAuxStream)?!1:e.enableMultiAuxStream,this.enableSEI=e.enableSEI,!ti(e.enableSPC)&&Ks&&(this._enableSPC=e.enableSPC),this._initBusinessInfo(e)}get isMainStreamPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.isMainStreamPublished)}get isMainAudioPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.localMainAudioTrack)}get isAuxStreamPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.isAuxStreamPublished)}get hasAuxStream(){return[...this.remotePublishedUserMap.values()].findIndex(e=>e.muteState.hasAuxiliary)>=0}get userMap(){return this.userManager.userMap}get remotePublishedUserMap(){return this.userManager.remotePublishedUserMap}get tinyIdToUserIdMap(){return new Map([...this.remotePublishedUserMap.values()].map(e=>[e.tinyId,e.userId]))}join(e,r,n){return E(this,null,function*(){this.userManager.mySelfId=this.userId,this.userManager.on("1",o=>{this.emit("peer-join",o)}),this.userManager.on("2",o=>{this.closeDownLinkConnection(o,"remote user exitRoom"),this.emit("peer-leave",o)}),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",a=>{var o=Cd(a,[]);C.emit(S.REMOTE_PUBLISH_STATE_CHANGED,w({room:this},o)),this.emit("remote-publish-state-changed",w({},o))});let s=String(e.roomId||e.strRoomId);return this._joinOptions=e,new Promise((o,a)=>E(this,null,function*(){this._joinReject=a;try{this.checkDestroy(),yield this.initialize(),yield this.doJoin(e),o(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(c){this.reset(),a(c)}this._joinReject=null}))})}doJoin(e){return new Promise((r,n)=>E(this,null,function*(){var u,l,h;ti(e.role)||(this.role=e.role===20?"anchor":"audience"),ti(e.privateMapKey)||(this.privateMapKey=e.privateMapKey),this._signalChannel.once(Se.SETUP_FAILED,I=>{this.clearJoinTimeout(),C.emit(S.JOIN_SIGNAL_CONNECTION_END,{room:this,error:I}),n(I)}),Ne((l=(u=this.scheduleResult)==null?void 0:u.config)==null?void 0:l.singlePC)&&Ks&&(this._enableSPC=this.scheduleResult.config.singlePC);let s;if(this._enableSPC&&!this.singlePC){this.singlePC=new Wr({signalChannel:this._signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.once("error",()=>this.fallbackToMPC());try{s=yield this.singlePC.initialize()}catch(I){this.fallbackToMPC()}}this.keyPointManager.setConnectionType(this.singlePC?1:2);let o={roomId:String(e.roomId||e.strRoomId),useStringRoomId:this.useStringRoomId,privateMapKey:this.privateMapKey,trtcRole:this.role==="anchor"?20:21,trtcScene:this.scene==="live"?2:1,sdpSemantics:this.sdpSemantics,version:this._version,ua:navigator&&navigator.userAgent||"",terminalType:Hf(),netType:oi[this._networkType],bussinessInfo:this._businessInfo,ability:s},{bussinessInfo:a,pushUserCdnInfo:c}=this.publishCDNManager.handleCDNConfigForJoinData(this._businessInfo);Object.assign(o,{bussinessInfo:a,pushUserCdnInfo:c}),this._log.debug(`join room signal data: ${JSON.stringify(o)}`);let d=5e3;((h=this.scheduleResult.config)==null?void 0:h.enterRoomTimeout)&&this.scheduleResult.config.enterRoomTimeout>=1&&(d=this.scheduleResult.config.enterRoomTimeout*1e3),this._joinTimeout=window.setTimeout(()=>{this._log.error("join room timeout observed"),n(new M({code:v.JOIN_ROOM_FAILED,message:B({key:V.JOIN_ROOM_TIMEOUT})}))},d),C.emit(S.JOIN_SEND_CMD,{room:this}),this._signalChannel.send(this.singlePC?ne.SPC_JOIN_ROOM:ne.JOIN_ROOM,o),this._signalChannel.once(Q.JOIN_ROOM_RESULT,I=>{this.clearJoinTimeout();let{code:T,message:N,data:$}=I.data;C.emit(S.JOIN_RECEIVED_CMD_RES,{room:this,code:T}),T===0?(this._log.info("Join room success, start heartbeat"),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=$.publishers,this.singlePC&&this.singlePC.connect($.ability).catch(()=>{}),r()):(this._log.error(`Join room failed result: ${T} error: ${N}`),n(new M({code:v.JOIN_ROOM_FAILED,extraCode:T,message:B({key:V.JOIN_ROOM_FAILED,data:{error:N,code:T}})})))})}))}reJoin(){return E(this,null,function*(){if(!this.isJoined){this._log.warn("reJoin abort");return}try{this._log.warn(`reJoin pending: ${this._joinOptions.roomId}`),this.singlePC&&(this.singlePC.close(),this.singlePC=null),this._signalChannel.close(),yield this._signalChannel.connect(),yield this.doJoin(ee(w({},this._joinOptions),{role:this.role==="anchor"?20:21,privateMapKey:this.privateMapKey})),this._log.warn("reJoin success"),_e.logSuccessEvent({userId:this.userId,eventType:yt.REJOIN}),this.singlePC?(yield this.singlePC.waitForPeerConnectionConnected(),this.uplinkConnection instanceof _d&&this.uplinkConnection.onSinglePCReconnected(),this.remotePublishedUserMap.forEach(e=>{e.installEvents(),e.doSubscribe()})):(this.checkConnectionsToReconnect(),this.uplinkConnection instanceof Io&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()),this.mixTranscodeManager.reStartMixTranscode()}catch(e){this._log.warn(`reJoin fail ${e}`),this.reset(),_e.logFailedEvent({userId:this.userId,eventType:yt.REJOIN,error:e}),this.emit("error",new M({code:v.JOIN_ROOM_FAILED,message:B({key:V.REJOIN_ROOM_FAILED,data:{roomId:this._joinOptions.roomId}})}))}})}initialize(){this._log.info("setup signal channel");let{mainUrl:e,backupUrl:r}=this.getSignalChannelUrl();return this._signalChannel=new Gn({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:e,backupUrl:r,room:this}),this._networkQuality||(this._networkQuality=new Qi({signalChannel:this._signalChannel,room:this}),this._networkQuality.on(Qi.EVENT_NETWORK_QUALITY,n=>{this.emit("network-quality",n)})),this._signalChannel.on(Se.CONNECTION_STATE_CHANGED,n=>{C.emit(S.SIGNAL_CONNECTION_STATE_CHANGED,w({room:this},n)),this.emit("signal-connection-state-changed",n)}),this._signalChannel.on(Se.RECONNECT_FAILED,n=>{this.reset(),this.emit("error",n)}),this._signalChannel.once(Se.SETUP_SUCCESS,n=>{this.tinyId=n.signalInfo.tinyId,C.emit(S.JOIN_SIGNAL_CONNECTION_END,{room:this})}),this._signalChannel.on(Q.PEER_JOIN,n=>{let{srcTinyId:s,userId:o,role:a}=n.data.data;this.userManager.addUser({userId:o,tinyId:s,role:a})}),this._signalChannel.on(Q.PEER_LEAVE,n=>{let{userId:s,reason:o=0}=n.data.data;this.userManager.deleteUser(s,o)}),this._signalChannel.on(Q.UPDATE_REMOTE_MUTE_STAT,n=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=10*1e3&&this.doHeartbeat(),this.onPublishedUserList(n.data)}),this._signalChannel.on(Q.CLIENT_BANNED,n=>{let s=n.data.data,{reason:o}=s;if(_e.uploadEvent({log:`stat-banned:${o}`,userId:this.userId}),o==="user_time_out"){this._log.warn(`${o} last heart beat time: ${this._lastHeartBeatTime} interval: ${Date.now()-this._lastHeartBeatTime}, visibility: ${document.visibilityState}`),this.reJoin();return}this._log[o==="kick"?"error":"info"](`user was banned because of [${o}]`),this.reset(),this.emit("banned",{reason:o})}),C.emit(S.JOIN_SIGNAL_CONNECTION_START,{room:this}),this._signalChannel.connect()}leave(){return E(this,null,function*(){try{yield this.doHeartbeat()}catch(e){}C.emit(S.LEAVE_SEND_CMD,{room:this}),this._log.info("leave() => leaving room"),this._signalChannel.send(ne.LEAVE_ROOM),this.reset()})}clearNetworkQuality(){this._networkQuality&&(this._networkQuality.stop(),this._networkQuality=null)}closeConnections(){this.remotePublishedUserMap.forEach(e=>{this.closeDownLinkConnection(e.userId,"you exitRoom")})}clearJoinTimeout(){clearTimeout(this._joinTimeout),this._joinTimeout=-1}startHeartbeat(){this._heartbeat===-1&&(this._heartbeat=me.run(vt,this.doHeartbeat.bind(this),{delay:2e3}))}stopHeartbeat(){this._heartbeat!==-1&&(this._log.info("stopHeartbeat"),me.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return E(this,null,function*(){var a;let e=this.badCaseDetector.getMonitorFreeze(),r=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:e});if(this.badCaseDetector.resetMonitor(),!((a=this._signalChannel)!=null&&a.isConnected))return;let n=this._signalChannel.isConnected?sl(this.userId):[],s=w({str_sdk_version:Oi,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:oi[this._networkType]},msg_event_msg:n,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},r);C.emit(S.HEARTBEAT_REPORT,{room:this,report:s}),this._signalChannel.send(ne.ON_QUALITY_REPORT,s);let o=Date.now();this._lastHeartBeatTime>0&&o-this._lastHeartBeatTime>1e4&&this._log.warn(`heartbeat took ${o-this._lastHeartBeatTime}`),this._signalChannel.isConnected&&(this._lastHeartBeatTime=o),!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)})}onPublishedUserList(e){if(!this.isJoined)return;let r=e.data.userList.map(({userId:n,srcTinyId:s,flag:o})=>{let a=this.remotePublishedUserMap.get(n);return a&&this._changeBigSmallRecords.has(n)&&this.checkSubscribeBigSmallVideo(a),{userId:n,tinyId:s,flag:o}});C.emit(S.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:r}),this.userManager.setRemotePublishedUserList(r)}closeUplink(e="you unpublished"){this.uplinkConnection&&(this.localTracks.size>0&&this.uplinkConnection.doUnpublish(),this.uplinkConnection.close(e),this.uplinkConnection=null),this.localTracks.forEach(r=>r.unpublish()),this.localTracks.clear()}createDownlinkConnection({userId:e,tinyId:r,flag:n}){let s=new(this.singlePC?mp:Yc)({userId:e,tinyId:r,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,flag:n});this.userManager.addRemotePublishedUser(s),this.installDownlinkEvents(s,e),this.emit("remote-published",s)}closeDownLinkConnection(e,r="remote user unpublished"){let n=this.remotePublishedUserMap.get(e);n&&(n.close(r),this.emit("remote-unpublished",n))}installDownlinkEvents(e,r){e.on("sei-message",n=>{this.emit("sei-message",n)}),e.on("error",n=>{let s=n.getCode();s!==v.ICE_TRANSPORT_ERROR&&(s===v.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(r),this.emit("error",n))}),e.on("connection-state-changed",n=>{this.emit("media-connection-state-changed",ee(w({},n),{userId:e.userId}))}),e.on("firewall-restriction",()=>{this.emit("firewall-restriction")})}startSyncUserListInterval(){this._syncUserListInterval===-1&&(this._syncUserListInterval=me.run(vt,this.syncUserList.bind(this)))}stopSyncUserListInterval(){me.clearTask(this._syncUserListInterval),this._syncUserListInterval=-1}syncUserList(){return this.getUserList().then(e=>{this.userManager.setUserList(e)}).catch(e=>{this._log.debug(`sync user list failed: ${e}`)})}getUserList(){var e;return(e=this._signalChannel)!=null&&e.isConnected?this._signalChannel.sendWaitForResponse({command:ne.GET_USER_LIST,responseCommand:Q.USER_LIST_RES,enableLog:!1,timeout:2e3}).then(({data:r})=>{let{code:n,message:s}=r;if(n===0)return(r.data&&r.data.userList||[]).map(({userId:a,srcTinyId:c,role:d})=>({userId:a,tinyId:c,role:d}));throw B({key:V.SIGNAL_RESPONSE_FAILED,data:{signalResponse:Q.USER_LIST_RES,code:n,message:s}})}):Promise.reject("not connected")}getAllConnections(){let e=[...this.remotePublishedUserMap.values()];return this.uplinkConnection&&e.push(this.uplinkConnection),e}isRelayMaybeFailed(){if(!this._signalChannel.isOnline||!Gc)return!1;if(this.singlePC)return this.singlePC.reconnectionCount>6;let e=this.getAllConnections();if(e.length===0)return!1;for(let r=0;r<e.length;r++)if(e[r].getReconnectionCount()<6)return!1;return!0}checkConnectionsToReconnect(){this.singlePC||this.getAllConnections().forEach(r=>{if(r instanceof Qe&&!r.getIsReconnecting()){let n=r.getPeerConnection();n&&n.connectionState===pe.CLOSED&&(this._log.warn(`[${r.getUserId()}] pc is closed but not reconnect`),r.startReconnection())}})}fallbackToMPC(){return E(this,null,function*(){var e;if(this._log.warn("fallback to multi pc"),_e.uploadEvent({log:"stat-fallback",userId:this.userId}),this._enableSPC=!1,(e=this.singlePC)==null||e.close(),this.singlePC=null,yield this.reJoin(),this.uplinkConnection){let r=this.uplinkConnection;this.uplinkConnection=new Io({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}),r.isMainStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:r.localMainAudioTrack,localVideoTrack:r.localMainVideoTrack,isAuxiliary:!1})),r.isAuxStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:r.localAuxAudioTrack,localVideoTrack:r.localAuxVideoTrack,isAuxiliary:!0}))}this.remotePublishedUserMap.forEach(r=>{let n=new Yc({userId:r.userId,tinyId:r.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,flag:r.flag,remoteAudioTrack:r.remoteAudioTrack,remoteVideoTrack:r.remoteVideoTrack,remoteAuxiliaryTrack:r.remoteAuxiliaryTrack});this.installDownlinkEvents(n,r.userId),this.remotePublishedUserMap.set(r.userId,n),r.isMainStreamSubscribed&&n.subscribe(r.subscribeState,"main"),r.isAuxStreamSubscribed&&n.subscribe(r.subscribeState,"auxiliary")})})}destroy(){this._isDestroyed||(super.destroy(),this._joinReject&&(this._joinReject(new M({code:v.INVALID_OPERATION,message:B({key:V.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners())}switchRole(e){return E(this,null,function*(){this.role!==e&&(e==="audience"&&this.uplinkConnection&&this.closeUplink("you switch role to audience"),yield this.doSwitchRole(e))})}doSwitchRole(e){let r={command:ne.SWITCH_ROLE,data:{role:e==="anchor"?20:21,privateMapKey:this.privateMapKey},responseCommand:Q.SWITCH_ROLE_RES,retries:1};return this._log.info(`switchRole signal data: ${JSON.stringify(r.data)}`),this._signalChannel.sendWaitForResponseWithRetry(r).then(n=>{let{code:s,message:o}=n.data;if(s!==0)throw new M({code:v.SWITCH_ROLE_FAILED,message:B({key:V.SWITCH_ROLE_FAILED,data:{message:o,code:s}})});this.role=e}).catch(n=>{throw n instanceof M&&n.getCode()===v.API_CALL_TIMEOUT&&(n=new M({code:v.SWITCH_ROLE_FAILED,message:B({key:V.SWITCH_ROLE_TIMEOUT})})),this._log.error(n),n})}publish(...e){return E(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor")return;C.emit(S.PUBLISH_START,{room:this});let r={},n={};this._isPublishing=!0,e.forEach(s=>{!s.mediaTrack||(s instanceof Jt&&(s instanceof ji?(n.audio=s,this.audioManager.addScreenAudioTrack(s)):(r.audio=s,this.audioManager.addAudioTrack(s))),s instanceof St&&(s instanceof Mt&&s.mediaType===2?n.video=s:r.video=s),s.setPublishStarting(this))});try{let s=rs(r),o=rs(n);(!s||!o)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new _d({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}):this.uplinkConnection=new Io({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}),this.uplinkConnection.on("connection-state-changed",c=>{this.emit("media-connection-state-changed",ee(w({},c),{userId:this.userId}))}),this.uplinkConnection.on("firewall-restriction",()=>{this.emit("firewall-restriction")}),this.uplinkConnection.on("error",c=>{let d=c.getCode();d!==v.ICE_TRANSPORT_ERROR&&(d===v.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",c))}));let a=e.map(c=>c.kind).join(",");s||(this._log.info(`publish() => main ${a}`),yield this.uplinkConnection.publish({localAudioTrack:r.audio,localVideoTrack:r.video,isAuxiliary:!1}),this._log.info("main is published")),o||(this._log.info(`publish() => aux ${a}`),yield this.uplinkConnection.publish({localAudioTrack:n.audio,localVideoTrack:n.video,isAuxiliary:!0}),this._log.info("aux is published")),this._isPublishing=!1,e.forEach(c=>{!c.mediaTrack||(this.localTracks.add(c),c.publish(this))})}catch(s){throw e.forEach(o=>{let a="error";s.message.includes("timeout")?a="timeout":s.code===v.API_CALL_ABORTED&&(a="api-call"),o.setPublishStopped(a,a==="error"?s:void 0)}),this._isPublishing=!1,s}})}unpublish(...e){return E(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||!this.isMainStreamPublished&&!this.isAuxStreamPublished||!this.uplinkConnection)return;let r={},n={};e.forEach(s=>{!s.mediaTrack||(s instanceof Jt&&(s instanceof ji?n.audio=s:r.audio=s),s instanceof St&&(s instanceof Mt&&s.mediaType===2?n.video=s:r.video=s))});try{let s=e.map(o=>o.kind).join(",");rs(r)||(this._log.info(`unpublish() => main ${s}`),yield this.uplinkConnection.unpublish({localAudioTrack:r.audio,localVideoTrack:r.video})),rs(n)||(this._log.info(`unpublish() => aux ${s}`),yield this.uplinkConnection.unpublish({localAudioTrack:n.audio,localVideoTrack:n.video}))}catch(s){}e.forEach(s=>{!s.mediaTrack||(s.unpublish(),this.localTracks.delete(s))}),this.localTracks.size===0&&!this.audioManager.isMixed&&this.closeUplink("you unpublished")})}addTrack(e){return!this.uplinkConnection||!e.mediaTrack?Promise.resolve():(e.setPublishStarting(this),this.uplinkConnection.addTrack(e).then(r=>(e.publish(this),r)))}removeTrack(e){return!this.uplinkConnection||!e.mediaTrack?Promise.resolve():this.uplinkConnection.removeTrack(e).then(r=>(e.unpublish(),r))}replaceTrack(e){return!this.uplinkConnection||!e.mediaTrack?Promise.resolve():this.uplinkConnection.replaceTrack(e).then(r=>{C.emit(S.LOCAL_TRACK_REPLACED,{track:e})})}setBandWidth(e){return E(this,null,function*(){!this.uplinkConnection||(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())})}subscribe(...e){return E(this,null,function*(){let{userId:r}=e[0],n=this.remotePublishedUserMap.get(r);if(!n)return;let s=e.find(o=>o.mediaType===2)?"auxiliary":"main";try{let o=w({},n.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:o.audio=!0;break;case 4:o.video=!0;break;case 2:o.auxiliary=!0;break}});let a=this._changeBigSmallRecords.get(r);a&&a.options.smallVideo&&n.muteState.hasSmall&&o.video&&(o.video=!1,o.smallVideo=!0),C.emit(S.SUBSCRIBE_START,{room:this,streamType:s,remotePublishedUser:n,subscribeState:o}),this._log.info(`subscribe() => ${r} ${s} [${go(o)}] prev: [${go(n.subscribeState)}]`),yield n.subscribe(o,s),n.remoteVideoTrack.setMediaType(o.smallVideo?8:4),e.forEach(c=>c.subscribe()),C.emit(S.SUBSCRIBE_SUCCESS,{room:this,streamType:s,remotePublishedUser:n})}catch(o){let a=o instanceof M?o.getCode():v.UNKNOWN,c=o;throw o instanceof M?a===v.REMOTE_STREAM_NOT_EXIST&&(c=new M({code:v.API_CALL_ABORTED,message:B({key:V.API_CALL_ABORTED,data:{message:o.message,userId:r,streamType:s}})}),this._log.warn(c)):(c=new M({code:a,message:B({key:V.SUBSCRIBE_FAILED,data:{message:o.message,userId:r,streamType:s}})}),this._log.error(c)),c}})}unsubscribe(...e){return E(this,null,function*(){let{userId:r}=e[0],n=this.remotePublishedUserMap.get(r);if(!n)return;let s=e.find(o=>o.mediaType===2)?"auxiliary":"main";this._log.info(`unsubscribe() => ${r} ${s}`);try{yield n.unsubscribe({remoteTracks:e,streamType:s})}catch(o){this._log.warn(`unsubscribe() => failed ${o}`)}e.forEach(o=>{o.unsubscribe(),o.mediaType===8&&o.setMediaType(4)}),C.emit(S.UNSUBSCRIBE_SUCCESS,{room:this,streamType:s,remotePublishedUser:n})})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAudioVolumeEvaluation(e=2e3,r){if(e<=0){this._enableAudioVolumeEvaluation=!1,me.clearTask(this._audioVolumeIntervalId),this._audioVolumeIntervalId=null;return}e=Math.floor(Math.max(e,100)),C.emit(S.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&(me.clearTask(this._audioVolumeIntervalId),this._audioVolumeIntervalId=null),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=me.run($t,()=>{var s,o;let n=[];if((s=this.uplinkConnection)!=null&&s.localMainAudioTrack){let a=Math.floor(this.uplinkConnection.localMainAudioTrack.getAudioLevel()*100);n.push({userId:"",volume:a})}(o=this.remotePublishedUserMap)==null||o.forEach(a=>{if(a.muteState.hasAudio){let c=Math.floor(a.remoteAudioTrack.getAudioLevel()*100);n.push({userId:a.userId,volume:c})}}),this.emit("audio-volume",n)},{fps:1e3/e,backgroundTask:r})}getLocalAudioStats(){return E(this,null,function*(){let e={};if(e[this.userId]={bytesSent:0,packetsSent:0},this.uplinkConnection){let r=yield this._stats.getSenderStats(this.uplinkConnection);e[this.userId]={bytesSent:r.audio.bytesSent,packetsSent:r.audio.packetsSent}}return e})}getLocalVideoStats(){return E(this,null,function*(){let e={};if(e[this.userId]={bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0},this.uplinkConnection){let{video:{bytesSent:r,packetsSent:n,framesEncoded:s,framesSent:o,frameWidth:a,frameHeight:c}}=yield this._stats.getSenderStats(this.uplinkConnection);e[this.userId]={bytesSent:r,packetsSent:n,framesEncoded:s,framesSent:o,frameWidth:a,frameHeight:c}}return e})}getTransportStats(){return E(this,null,function*(){let e={rtt:0,downlinksRTT:{}};if(this.uplinkConnection){let r=yield this._stats.getSenderStats(this.uplinkConnection);e.rtt=r.rtt}for(let[,r]of this.remotePublishedUserMap){let n=yield this._stats.getReceiverStats(r);e.downlinksRTT[n.userId]=n.rtt}return e})}getRemoteVideoStats(e){return E(this,null,function*(){let r={};for(let[n,s]of this.remotePublishedUserMap)e==="main"&&s.muteState.hasVideo&&(r[n]=s.remoteVideoTrack.stat),e==="auxiliary"&&s.muteState.hasAuxiliary&&(r[n]=s.remoteAuxiliaryTrack.stat);return r})}getRemoteAudioStats(){return E(this,null,function*(){let e={};for(let[r,n]of this.remotePublishedUserMap)n.muteState.hasAudio&&(e[r]=n.remoteAudioTrack.stat);return e})}setProxyServer(e){if(Do(e)){if(!e.startsWith("wss://"))throw new M({code:v.INVALID_PARAMETER,message:"invalid websocket url"});this.proxy_ws=e}else if(Bf(e)){let{websocketProxy:r,loggerProxy:n}=e;r&&(this.proxy_ws=r),n&&fn(n)}}setTurnServer(e,r){this._log.info(`set turn server: ${JSON.stringify(e)} ${r||""}`);let n=[];Array.isArray(e)?e.forEach(s=>n.push(ke.getTurnServer(s))):ke.isPlainObject(e)&&n.push(ke.getTurnServer(e)),this._turnServers=n,r&&(this._iceTransportPolicy=r)}sendStartMixTranscode(e){return this._signalChannel.sendWaitForResponse({command:ne.START_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:Q.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this._signalChannel.sendWaitForResponse({command:ne.STOP_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:Q.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"})}sendStartPublishCDN(e,r=!0){return this._signalChannel.sendWaitForResponse({command:r?ne.START_PUBLISH_TENCENT_CDN:ne.START_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:r?Q.START_PUBLISH_TENCENT_CDN_RES:Q.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"})}sendStopPublishCDN(e,r=!0){return this._signalChannel.sendWaitForResponse({command:r?ne.STOP_PUBLISH_TENCENT_CDN:ne.STOP_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:r?Q.STOP_PUBLISH_TENCENT_CDN_RES:Q.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}getIceServers(){return this._turnServers.length===0&&this.scheduleResult.iceServers?this.scheduleResult.iceServers:this._turnServers}getIceTransportPolicy(){return this._iceTransportPolicy||this.scheduleResult.iceTransportPolicy||"all"}getLogger(){return this._log}enableAIVoice(){throw new Error("Method not implemented.")}getSignalChannelUrl(){let e={mainUrl:"",backupUrl:""},r=ke.getEnv();return r?(e.mainUrl=`wss://${r}.rtc.qq.com`,e.backupUrl=e.mainUrl):this.proxy_ws?(e.mainUrl=this.proxy_ws,e.backupUrl=e.mainUrl):Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(e.mainUrl=`wss://${this.scheduleResult.domains[0]}`,e.backupUrl=e.mainUrl,this.scheduleResult.domains[1]&&(e.backupUrl=`wss://${this.scheduleResult.domains[1]}`)),e}getSignalInfo(){var e;return((e=this._signalChannel)==null?void 0:e.getSignalInfo())||{}}reset(){this.mixTranscodeManager.reset(),this.publishCDNManager.reset(),this.stopSyncUserListInterval(),this.stopHeartbeat(),this.closeConnections(),this.clearNetworkQuality(),this.closeUplink("you exitRoom"),this._signalChannel&&(this._log.info("destroying SignalChannel"),this._signalChannel.close()),this._stats.reset(),this.userManager.clear(),this.userManager.removeAllListeners(),this.singlePC&&(this.singlePC.close(),this.singlePC=null)}checkSubscribeBigSmallVideo(e){return E(this,null,function*(){let r=e==null?void 0:e.muteState.hasSmall,n=e==null?void 0:e.muteState.hasVideo;if(!r&&!n||!e.isBigStreamSubscribed&&!e.isSmallStreamSubscribed)return;let s=e.getUserId(),o=this._changeBigSmallRecords.get(s)||{},{subscribeState:a}=e,{options:c,isSubscribing:d,reSubscribeCount:u}=o;if(c.video&&a.video||c.smallVideo&&a.smallVideo&&r||d)return;let l={audio:a.audio,auxiliary:a.auxiliary,video:c.video,smallVideo:c.smallVideo};if(r&&e.isBigStreamSubscribed||e.isSmallStreamSubscribed)try{c&&!d&&u>=1&&(o.isSubscribing=!0,o.reSubscribeCount=u-1,!r&&e.isSmallStreamSubscribed&&(l.video=!0,l.smallVideo=!1),yield e==null?void 0:e.subscribe(l,"main"),e.remoteVideoTrack.setMediaType(l.smallVideo?8:4),this._log.info(`change [${s}] to ${l.smallVideo?"small":"big"} video successfully. count ${Ar-o.reSubscribeCount}.`),o.isSubscribing=!1,o.reSubscribeCount=Ar)}catch(h){this._log.info(`change [${s}] to ${l.smallVideo?"small":"big"} video failed. count ${Ar-o.reSubscribeCount}.`),o.isSubscribing=!1,u===0&&this._changeBigSmallRecords.delete(s)}})}changeType(e,r){let s={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:Ar};this._changeBigSmallRecords.set(r.userId,s),this._log.info(`set [${r.userId}] video prefer type: ${e?"small":"big"}`)}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(e){this._businessInfo=e.businessInfo;let r={};if(Do(e.businessInfo)&&(r=JSON.parse(e.businessInfo)),!ti(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new M({code:v.INVALID_PARAMETER,message:B({key:V.INVALID_PURE_AUDIO})});this._pureAudioPushMode=e.pureAudioPushMode,r.Str_uc_params||(r.Str_uc_params={}),r.Str_uc_params.pure_audio_push_mod=this._pureAudioPushMode}if(!ti(e.streamId))if(Do(e.streamId)&&String(e.streamId)&&String(e.streamId).length<=64)r.Str_uc_params||(r.Str_uc_params={}),r.Str_uc_params.userdefine_streamid_main=e.streamId;else throw new M({code:v.INVALID_PARAMETER,message:B({key:V.INVALID_STREAMID})});if(!ti(e.userDefineRecordId)){let n=/^[A-Za-z0-9_-]{1,64}$/gi;if(e.userDefineRecordId.match(n)===null)throw new M({code:v.INVALID_PARAMETER,message:B({key:V.INVALID_USER_DEFINE_RECORDID})});r.Str_uc_params||(r.Str_uc_params={}),r.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!ti(e.userDefinePushArgs))if(Do(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256)r.Str_uc_params||(r.Str_uc_params={}),r.Str_uc_params.userdefine_push_args=e.userDefinePushArgs;else throw new M({code:v.INVALID_PARAMETER,message:B({key:V.INVALID_USER_DEFINE_PUSH_ARGS})});rs(r)||(this._businessInfo=JSON.stringify(r))}startPlugin(e,r){return E(this,null,function*(){var n,s;e==="AudioMixer"&&(yield this.audioManager.addMusicSource(r),this.isJoined&&((n=this.uplinkConnection)==null?void 0:n.localMainAudioTrack)&&(yield this.replaceTrack((s=this.uplinkConnection)==null?void 0:s.localMainAudioTrack)))})}updatePlugin(e,r){return E(this,null,function*(){e==="AudioMixer"&&(yield this.audioManager.updateMusicSource(r))})}stopPlugin(e,r){return E(this,null,function*(){e==="AudioMixer"&&(yield this.audioManager.removeMusicSource(r))})}sendSEI(e,r){var n;(n=this.uplinkConnection)==null||n.sendSEI(e,r)}};H([dd(["left",et.INIT],"joined"),Nl()],xt.prototype,"join",1),H([dd("joined","left",{ignoreError:!0}),bl(),ip("leave room"),zn({fnName:"publish",validateArgs:!1}),zn({fnName:"unsubscribe",validateArgs:!1})],xt.prototype,"leave",1),H([Zn(),Xn({settings:{retries:Bt,timeout:i=>ot(i)},onError(i,t,e){var r;(r=i.message)!=null&&r.includes("timeout")?(this._log.warn("publish timeout"),t()):(this._log.error(`publish failed: ${i}`),e(i))}})],xt.prototype,"publish",1),H([zn({fnName:"publish",callback(...i){var t;this.localTracks.size===0&&((t=this.uplinkConnection)==null||t.close("you unpublished"),this.uplinkConnection=null,i.forEach(e=>e.setPublishStopped("api-call")))}}),tp("api-call"),Zn()],xt.prototype,"unpublish",1),H([ad((...i)=>i[0].userId),Xn({settings:{retries:Bt,timeout:i=>ot(i)},onError(i,t,e){i.message.includes("timeout")?(this._log.warn("subscribe timeout"),t()):(this._log.error(`subscribe failed: ${i}`),e(i))}})],xt.prototype,"subscribe",1),H([zn({fnName:"subscribe",callback(...i){this.singlePC||i.forEach(t=>{let e=this.remotePublishedUserMap.get(t.userId);e&&!e.isMainStreamSubscribed&&!e.isAuxStreamSubscribed&&e.close("you unsubscribed")})}}),ad((...i)=>i[0].userId)],xt.prototype,"unsubscribe",1);Fn.create=Fn._create.bind(Fn,xt);var sU=Fn;export{sU as default};