@rongcloud/plugin-rtc 5.2.4 → 5.3.1

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/dist/index.esm.js CHANGED
@@ -1,4 +1,4 @@
1
- import{Logger as e,EventEmitter as t,isNumber as r,ErrorCode as i,ConnectionStatus as n,assert as s,ConversationType as o,RTCApiType as a,validate as c,isArray as d,RTCMode as u,isHttpUrl as l,isBoolean as h,HttpMethod as p,isString as _,notEmptyString as m,RTCJoinType as f,RTCIdentityChangeType as v,VersionManage as g}from"@rongcloud/engine";export{RTCJoinType}from"@rongcloud/engine";
1
+ import{Logger as e,EventEmitter as t,isNumber as r,ErrorCode as i,ConnectionStatus as n,assert as s,ConversationType as o,RTCApiType as a,validate as c,isArray as d,RTCMode as u,isHttpUrl as l,notEmptyString as h,isBoolean as p,isUndefined as _,HttpMethod as m,isString as f,RTCJoinType as v,RTCIdentityChangeType as R,VersionManage as g}from"@rongcloud/engine";export{RTCJoinType}from"@rongcloud/engine";
2
2
  /*! *****************************************************************************
3
3
  Copyright (c) Microsoft Corporation.
4
4
 
@@ -12,4 +12,4 @@ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
12
12
  LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
13
13
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
14
14
  PERFORMANCE OF THIS SOFTWARE.
15
- ***************************************************************************** */function R(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))}const S=new e("RCRTC");var T,C;!function(e){e[e.SUCCESS=1e4]="SUCCESS",e[e.SIGNAL_DISCONNECTED=5e4]="SIGNAL_DISCONNECTED",e[e.PARAMS_ERROR=50001]="PARAMS_ERROR",e[e.REPERT_JOIN_ROOM=50002]="REPERT_JOIN_ROOM",e[e.NOT_IN_ROOM=50003]="NOT_IN_ROOM",e[e.SERVICE_INVALID=50004]="SERVICE_INVALID",e[e.RTC_TOKEN_INVALID=50006]="RTC_TOKEN_INVALID",e[e.SIGNAL_ERROR=53001]="SIGNAL_ERROR",e[e.CREATE_OFFER_FAILED=53003]="CREATE_OFFER_FAILED",e[e.REQUEST_FAILED=53004]="REQUEST_FAILED",e[e.MCU_SERVER_NOT_FOUND=53005]="MCU_SERVER_NOT_FOUND",e[e.BROADCAST_SUB_LIST_NOT_EMPTY=53007]="BROADCAST_SUB_LIST_NOT_EMPTY",e[e.ROOM_HAS_BEEN_DESTROYED=53008]="ROOM_HAS_BEEN_DESTROYED",e[e.NOT_OPEN_VIDEO_AUDIO_SERVER=53009]="NOT_OPEN_VIDEO_AUDIO_SERVER",e[e.GET_USER_MEDIA_FAILED=53010]="GET_USER_MEDIA_FAILED",e[e.GET_DISPLAY_MEDIA_FAILED=53011]="GET_DISPLAY_MEDIA_FAILED",e[e.PERMISSION_DENIED=53012]="PERMISSION_DENIED",e[e.CREATE_CUSTOM_TRACK_FAILED=53013]="CREATE_CUSTOM_TRACK_FAILED",e[e.INVALID_TAGS=53014]="INVALID_TAGS",e[e.INVALID_USER_ID=53015]="INVALID_USER_ID",e[e.CREATE_FILE_TRACK_FAILED=53016]="CREATE_FILE_TRACK_FAILED",e[e.INVALID_FILE_INSTANCE=53017]="INVALID_FILE_INSTANCE",e[e.SET_REMOTE_DESCRIPTION_FAILED=53018]="SET_REMOTE_DESCRIPTION_FAILED",e[e.BROWSER_NOT_SUPPORT=53019]="BROWSER_NOT_SUPPORT",e[e.TRACK_NOT_READY=53020]="TRACK_NOT_READY",e[e.VIDEO_TRACK_MISS_MEDIA_ELEMENT=53021]="VIDEO_TRACK_MISS_MEDIA_ELEMENT",e[e.TRACK_PLAY_ERROR=53022]="TRACK_PLAY_ERROR",e[e.SIGNAL_AUDIENCE_JOIN_ROOM_FAILED=53023]="SIGNAL_AUDIENCE_JOIN_ROOM_FAILED",e[e.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED=53024]="SIGNAL_ROOM_CHANGE_IDENTITY_FAILED",e[e.PACKAGE_ENVIRONMENT_ERROR=53025]="PACKAGE_ENVIRONMENT_ERROR",e[e.PUBLISH_TRACK_LIMIT_EXCEEDED=53026]="PUBLISH_TRACK_LIMIT_EXCEEDED",e[e.CDN_RESOURCE_IS_EMPTY=53027]="CDN_RESOURCE_IS_EMPTY",e[e.SIGNAL_JOIN_RTC_ROOM_REFUSED=53028]="SIGNAL_JOIN_RTC_ROOM_REFUSED",e[e.NO_PERMISSION_TO_USE_REQUESTED_DEVICE=53029]="NO_PERMISSION_TO_USE_REQUESTED_DEVICE"}(T||(T={})),function(e){e[e.JOIN_REFUSED=40032]="JOIN_REFUSED"}(C||(C={}));class E{constructor(){this.queue=[],this.locked=!1}checkToStart(){return R(this,void 0,void 0,(function*(){if(0===this.queue.length||this.locked)return;this.locked=!0;const{resolve:e,task:t,reject:r}=this.queue.shift();let i;try{i=yield t(),e(i)}catch(e){r(e)}this.locked=!1,this.checkToStart()}))}push(e){const t=new Promise(((t,r)=>{this.queue.push({resolve:t,task:e,reject:r})}));return this.checkToStart(),t}}const y=new E,I=e=>y.push(e);let k=!0,b=!0;function P(e,t,r){const i=e.match(t);return i&&i.length>=r&&parseInt(i[r],10)}function O(e,t,r){if(!e.RTCPeerConnection)return;const i=e.RTCPeerConnection.prototype,n=i.addEventListener;i.addEventListener=function(e,i){if(e!==t)return n.apply(this,arguments);const s=e=>{const t=r(e);t&&(i.handleEvent?i.handleEvent(t):i(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(i,s),n.apply(this,[e,s])};const s=i.removeEventListener;i.removeEventListener=function(e,r){if(e!==t||!this._eventMap||!this._eventMap[t])return s.apply(this,arguments);if(!this._eventMap[t].has(r))return s.apply(this,arguments);const i=this._eventMap[t].get(r);return this._eventMap[t].delete(r),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,s.apply(this,[e,i])},Object.defineProperty(i,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function L(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(k=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function D(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(b=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function N(){if("object"==typeof window){if(k)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function A(e,t){b&&console.warn(e+" is deprecated, please use "+t+" instead.")}function M(e){return"[object Object]"===Object.prototype.toString.call(e)}function x(e){return M(e)?Object.keys(e).reduce((function(t,r){const i=M(e[r]),n=i?x(e[r]):e[r],s=i&&!Object.keys(n).length;return void 0===n||s?t:Object.assign(t,{[r]:n})}),{}):e}function w(e,t,r){t&&!r.has(t.id)&&(r.set(t.id,t),Object.keys(t).forEach((i=>{i.endsWith("Id")?w(e,e.get(t[i]),r):i.endsWith("Ids")&&t[i].forEach((t=>{w(e,e.get(t),r)}))})))}function U(e,t,r){const i=r?"outbound-rtp":"inbound-rtp",n=new Map;if(null===t)return n;const s=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&s.push(e)})),s.forEach((t=>{e.forEach((r=>{r.type===i&&r.trackId===t.id&&w(e,r,n)}))})),n}const $=N;function j(e,t){const r=e&&e.navigator;if(!r.mediaDevices)return;const i=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((r=>{if("require"===r||"advanced"===r||"mediaSource"===r)return;const i="object"==typeof e[r]?e[r]:{ideal:e[r]};void 0!==i.exact&&"number"==typeof i.exact&&(i.min=i.max=i.exact);const n=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==i.ideal){t.optional=t.optional||[];let e={};"number"==typeof i.ideal?(e[n("min",r)]=i.ideal,t.optional.push(e),e={},e[n("max",r)]=i.ideal,t.optional.push(e)):(e[n("",r)]=i.ideal,t.optional.push(e))}void 0!==i.exact&&"number"!=typeof i.exact?(t.mandatory=t.mandatory||{},t.mandatory[n("",r)]=i.exact):["min","max"].forEach((e=>{void 0!==i[e]&&(t.mandatory=t.mandatory||{},t.mandatory[n(e,r)]=i[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},n=function(e,n){if(t.version>=61)return n(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=i(e.audio)}if(e&&"object"==typeof e.video){let s=e.video.facingMode;s=s&&("object"==typeof s?s:{ideal:s});const o=t.version<66;if(s&&("user"===s.exact||"environment"===s.exact||"user"===s.ideal||"environment"===s.ideal)&&(!r.mediaDevices.getSupportedConstraints||!r.mediaDevices.getSupportedConstraints().facingMode||o)){let t;if(delete e.video.facingMode,"environment"===s.exact||"environment"===s.ideal?t=["back","rear"]:"user"!==s.exact&&"user"!==s.ideal||(t=["front"]),t)return r.mediaDevices.enumerateDevices().then((r=>{let o=(r=r.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!o&&r.length&&t.includes("back")&&(o=r[r.length-1]),o&&(e.video.deviceId=s.exact?{exact:o.deviceId}:{ideal:o.deviceId}),e.video=i(e.video),$("chrome: "+JSON.stringify(e)),n(e)}))}e.video=i(e.video)}return $("chrome: "+JSON.stringify(e)),n(e)},s=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(r.getUserMedia=function(e,t,i){n(e,(e=>{r.webkitGetUserMedia(e,t,(e=>{i&&i(s(e))}))}))}.bind(r),r.mediaDevices.getUserMedia){const e=r.mediaDevices.getUserMedia.bind(r.mediaDevices);r.mediaDevices.getUserMedia=function(t){return n(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException("","NotFoundError");return e}),(e=>Promise.reject(s(e))))))}}}function V(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function B(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",(r=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===r.track.id)):{track:r.track};const n=new Event("track");n.track=r.track,n.receiver=i,n.transceiver={receiver:i},n.streams=[t.stream],this.dispatchEvent(n)})),t.stream.getTracks().forEach((r=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===r.id)):{track:r};const n=new Event("track");n.track=r,n.receiver=i,n.transceiver={receiver:i},n.streams=[t.stream],this.dispatchEvent(n)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else O(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function F(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const r=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){let n=r.apply(this,arguments);return n||(n=t(this,e),this._senders.push(n)),n};const i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){i.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],r.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function H(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,r,i]=arguments;if(arguments.length>0&&"function"==typeof e)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof e))return t.apply(this,[]);const n=function(e){const t={};return e.result().forEach((e=>{const r={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach((t=>{r[t]=e.stat(t)})),t[r.id]=r})),t},s=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const i=function(e){r(s(n(e)))};return t.apply(this,[i,e])}return new Promise(((e,r)=>{t.apply(this,[function(t){e(s(n(t)))},r])})).then(r,i)}}function G(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=r.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>U(t,e.track,!0)))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),O(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>U(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,r,i;return this.getSenders().forEach((r=>{r.track===e&&(t?i=!0:t=r)})),this.getReceivers().forEach((t=>(t.track===e&&(r?i=!0:r=t),t.track===e))),i||t&&r?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():r?r.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function J(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,r){if(!r)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const i=t.apply(this,arguments);return this._shimmedLocalStreams[r.id]?-1===this._shimmedLocalStreams[r.id].indexOf(i)&&this._shimmedLocalStreams[r.id].push(i):this._shimmedLocalStreams[r.id]=[r,i],i};const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();r.apply(this,arguments);const i=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(i)};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],i.apply(this,arguments)};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const r=this._shimmedLocalStreams[t].indexOf(e);-1!==r&&this._shimmedLocalStreams[t].splice(r,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),n.apply(this,arguments)}}function W(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return J(e);const r=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=r.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const r=new e.MediaStream(t.getTracks());this._streams[t.id]=r,this._reverseStreams[r.id]=t,t=r}i.apply(this,[t])};const n=e.RTCPeerConnection.prototype.removeStream;function s(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],n=e._streams[i.id];r=r.replace(new RegExp(n.id,"g"),i.id)})),new RTCSessionDescription({type:t.type,sdp:r})}function o(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],n=e._streams[i.id];r=r.replace(new RegExp(i.id,"g"),n.id)})),new RTCSessionDescription({type:t.type,sdp:r})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},n.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,r){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const i=[].slice.call(arguments,1);if(1!==i.length||!i[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");const n=this.getSenders().find((e=>e.track===t));if(n)throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const s=this._streams[r.id];if(s)s.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const i=new e.MediaStream([t]);this._streams[r.id]=i,this._reverseStreams[i.id]=r,this.addStream(i)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?r.apply(this,[t=>{const r=s(this,t);e[0].apply(null,[r])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):r.apply(this,arguments).then((e=>s(this,e)))}};e.RTCPeerConnection.prototype[t]=i[t]}));const a=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=o(this,arguments[0]),a.apply(this,arguments)):a.apply(this,arguments)};const c=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=c.get.apply(this);return""===e.type?e:s(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((r=>{this._streams[r].getTracks().find((t=>e.track===t))&&(t=this._streams[r])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Y(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]}))}function K(e,t){O(e,"negotiationneeded",(e=>{const r=e.target;if(!(t.version<72||r.getConfiguration&&"plan-b"===r.getConfiguration().sdpSemantics)||"stable"===r.signalingState)return e}))}var q=Object.freeze({__proto__:null,shimMediaStream:V,shimOnTrack:B,shimGetSendersWithDtmf:F,shimGetStats:H,shimSenderReceiverGetStats:G,shimAddTrackRemoveTrackWithNative:J,shimAddTrackRemoveTrack:W,shimPeerConnection:Y,fixNegotiationNeeded:K,shimGetUserMedia:j,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(r){return t(r).then((t=>{const i=r.video&&r.video.width,n=r.video&&r.video.height,s=r.video&&r.video.frameRate;return r.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:s||3}},i&&(r.video.mandatory.maxWidth=i),n&&(r.video.mandatory.maxHeight=n),e.navigator.mediaDevices.getUserMedia(r)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}});var z,Q,X=(z=function(e){var t={generateIdentifier:function(){return Math.random().toString(36).substr(2,10)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((function(e){return e.trim()}))},t.splitSections=function(e){return e.split("\nm=").map((function(e,t){return(t>0?"m="+e:e).trim()+"\r\n"}))},t.getDescription=function(e){var r=t.splitSections(e);return r&&r[0]},t.getMediaSections=function(e){var r=t.splitSections(e);return r.shift(),r},t.matchPrefix=function(e,r){return t.splitLines(e).filter((function(e){return 0===e.indexOf(r)}))},t.parseCandidate=function(e){for(var t,r={foundation:(t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" "))[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]},i=8;i<t.length;i+=2)switch(t[i]){case"raddr":r.relatedAddress=t[i+1];break;case"rport":r.relatedPort=parseInt(t[i+1],10);break;case"tcptype":r.tcpType=t[i+1];break;case"ufrag":r.ufrag=t[i+1],r.usernameFragment=t[i+1];break;default:r[t[i]]=t[i+1]}return r},t.writeCandidate=function(e){var t=[];t.push(e.foundation),t.push(e.component),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);var r=e.type;return t.push("typ"),t.push(r),"host"!==r&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substr(14).split(" ")},t.parseRtpMap=function(e){var t=e.substr(9).split(" "),r={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),r.name=t[0],r.clockRate=parseInt(t[1],10),r.channels=3===t.length?parseInt(t[2],10):1,r.numChannels=r.channels,r},t.writeRtpMap=function(e){var t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);var r=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==r?"/"+r:"")+"\r\n"},t.parseExtmap=function(e){var t=e.substr(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1]}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+"\r\n"},t.parseFmtp=function(e){for(var t,r={},i=e.substr(e.indexOf(" ")+1).split(";"),n=0;n<i.length;n++)r[(t=i[n].trim().split("="))[0].trim()]=t[1];return r},t.writeFmtp=function(e){var t="",r=e.payloadType;if(void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){var i=[];Object.keys(e.parameters).forEach((function(t){e.parameters[t]?i.push(t+"="+e.parameters[t]):i.push(t)})),t+="a=fmtp:"+r+" "+i.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){var t=e.substr(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){var t="",r=e.payloadType;return void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((function(e){t+="a=rtcp-fb:"+r+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){var t=e.indexOf(" "),r={ssrc:parseInt(e.substr(7,t-7),10)},i=e.indexOf(":",t);return i>-1?(r.attribute=e.substr(t+1,i-t-1),r.value=e.substr(i+1)):r.attribute=e.substr(t+1),r},t.parseSsrcGroup=function(e){var t=e.substr(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((function(e){return parseInt(e,10)}))}},t.getMid=function(e){var r=t.matchPrefix(e,"a=mid:")[0];if(r)return r.substr(6)},t.parseFingerprint=function(e){var t=e.substr(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1]}},t.getDtlsParameters=function(e,r){return{role:"auto",fingerprints:t.matchPrefix(e+r,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){var r="a=setup:"+t+"\r\n";return e.fingerprints.forEach((function(e){r+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),r},t.parseCryptoLine=function(e){var t=e.substr(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;var t=e.substr(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,r){return t.matchPrefix(e+r,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,r){var i=t.matchPrefix(e+r,"a=ice-ufrag:")[0],n=t.matchPrefix(e+r,"a=ice-pwd:")[0];return i&&n?{usernameFragment:i.substr(12),password:n.substr(10)}:null},t.writeIceParameters=function(e){return"a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n"},t.parseRtpParameters=function(e){for(var r={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},i=t.splitLines(e)[0].split(" "),n=3;n<i.length;n++){var s=i[n],o=t.matchPrefix(e,"a=rtpmap:"+s+" ")[0];if(o){var a=t.parseRtpMap(o),c=t.matchPrefix(e,"a=fmtp:"+s+" ");switch(a.parameters=c.length?t.parseFmtp(c[0]):{},a.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+s+" ").map(t.parseRtcpFb),r.codecs.push(a),a.name.toUpperCase()){case"RED":case"ULPFEC":r.fecMechanisms.push(a.name.toUpperCase())}}}return t.matchPrefix(e,"a=extmap:").forEach((function(e){r.headerExtensions.push(t.parseExtmap(e))})),r},t.writeRtpDescription=function(e,r){var i="";i+="m="+e+" ",i+=r.codecs.length>0?"9":"0",i+=" UDP/TLS/RTP/SAVPF ",i+=r.codecs.map((function(e){return void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType})).join(" ")+"\r\n",i+="c=IN IP4 0.0.0.0\r\n",i+="a=rtcp:9 IN IP4 0.0.0.0\r\n",r.codecs.forEach((function(e){i+=t.writeRtpMap(e),i+=t.writeFmtp(e),i+=t.writeRtcpFb(e)}));var n=0;return r.codecs.forEach((function(e){e.maxptime>n&&(n=e.maxptime)})),n>0&&(i+="a=maxptime:"+n+"\r\n"),i+="a=rtcp-mux\r\n",r.headerExtensions&&r.headerExtensions.forEach((function(e){i+=t.writeExtmap(e)})),i},t.parseRtpEncodingParameters=function(e){var r,i=[],n=t.parseRtpParameters(e),s=-1!==n.fecMechanisms.indexOf("RED"),o=-1!==n.fecMechanisms.indexOf("ULPFEC"),a=t.matchPrefix(e,"a=ssrc:").map((function(e){return t.parseSsrcMedia(e)})).filter((function(e){return"cname"===e.attribute})),c=a.length>0&&a[0].ssrc,d=t.matchPrefix(e,"a=ssrc-group:FID").map((function(e){return e.substr(17).split(" ").map((function(e){return parseInt(e,10)}))}));d.length>0&&d[0].length>1&&d[0][0]===c&&(r=d[0][1]),n.codecs.forEach((function(e){if("RTX"===e.name.toUpperCase()&&e.parameters.apt){var t={ssrc:c,codecPayloadType:parseInt(e.parameters.apt,10)};c&&r&&(t.rtx={ssrc:r}),i.push(t),s&&((t=JSON.parse(JSON.stringify(t))).fec={ssrc:c,mechanism:o?"red+ulpfec":"red"},i.push(t))}})),0===i.length&&c&&i.push({ssrc:c});var u=t.matchPrefix(e,"b=");return u.length&&(u=0===u[0].indexOf("b=TIAS:")?parseInt(u[0].substr(7),10):0===u[0].indexOf("b=AS:")?1e3*parseInt(u[0].substr(5),10)*.95-16e3:void 0,i.forEach((function(e){e.maxBitrate=u}))),i},t.parseRtcpParameters=function(e){var r={},i=t.matchPrefix(e,"a=ssrc:").map((function(e){return t.parseSsrcMedia(e)})).filter((function(e){return"cname"===e.attribute}))[0];i&&(r.cname=i.value,r.ssrc=i.ssrc);var n=t.matchPrefix(e,"a=rtcp-rsize");r.reducedSize=n.length>0,r.compound=0===n.length;var s=t.matchPrefix(e,"a=rtcp-mux");return r.mux=s.length>0,r},t.parseMsid=function(e){var r,i=t.matchPrefix(e,"a=msid:");if(1===i.length)return{stream:(r=i[0].substr(7).split(" "))[0],track:r[1]};var n=t.matchPrefix(e,"a=ssrc:").map((function(e){return t.parseSsrcMedia(e)})).filter((function(e){return"msid"===e.attribute}));return n.length>0?{stream:(r=n[0].value.split(" "))[0],track:r[1]}:void 0},t.parseSctpDescription=function(e){var r,i=t.parseMLine(e),n=t.matchPrefix(e,"a=max-message-size:");n.length>0&&(r=parseInt(n[0].substr(19),10)),isNaN(r)&&(r=65536);var s=t.matchPrefix(e,"a=sctp-port:");if(s.length>0)return{port:parseInt(s[0].substr(12),10),protocol:i.fmt,maxMessageSize:r};if(t.matchPrefix(e,"a=sctpmap:").length>0){var o=t.matchPrefix(e,"a=sctpmap:")[0].substr(10).split(" ");return{port:parseInt(o[0],10),protocol:o[1],maxMessageSize:r}}},t.writeSctpDescription=function(e,t){var r=[];return r="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&r.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),r.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,21)},t.writeSessionBoilerplate=function(e,r,i){var n=void 0!==r?r:2;return"v=0\r\no="+(i||"thisisadapterortc")+" "+(e||t.generateSessionId())+" "+n+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.writeMediaSection=function(e,r,i,n){var s=t.writeRtpDescription(e.kind,r);if(s+=t.writeIceParameters(e.iceGatherer.getLocalParameters()),s+=t.writeDtlsParameters(e.dtlsTransport.getLocalParameters(),"offer"===i?"actpass":"active"),s+="a=mid:"+e.mid+"\r\n",e.direction?s+="a="+e.direction+"\r\n":e.rtpSender&&e.rtpReceiver?s+="a=sendrecv\r\n":e.rtpSender?s+="a=sendonly\r\n":e.rtpReceiver?s+="a=recvonly\r\n":s+="a=inactive\r\n",e.rtpSender){var o="msid:"+n.id+" "+e.rtpSender.track.id+"\r\n";s+="a="+o,s+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" "+o,e.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" "+o,s+="a=ssrc-group:FID "+e.sendEncodingParameters[0].ssrc+" "+e.sendEncodingParameters[0].rtx.ssrc+"\r\n")}return s+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" cname:"+t.localCName+"\r\n",e.rtpSender&&e.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" cname:"+t.localCName+"\r\n"),s},t.getDirection=function(e,r){for(var i=t.splitLines(e),n=0;n<i.length;n++)switch(i[n]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return i[n].substr(2)}return r?t.getDirection(r):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substr(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){var r=t.splitLines(e)[0].substr(2).split(" ");return{kind:r[0],port:parseInt(r[1],10),protocol:r[2],fmt:r.slice(3).join(" ")}},t.parseOLine=function(e){var r=t.matchPrefix(e,"o=")[0].substr(2).split(" ");return{username:r[0],sessionId:r[1],sessionVersion:parseInt(r[2],10),netType:r[3],addressType:r[4],address:r[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;for(var r=t.splitLines(e),i=0;i<r.length;i++)if(r[i].length<2||"="!==r[i].charAt(1))return!1;return!0},e.exports=t},z(Q={exports:{}},Q.exports),Q.exports);function Z(e,t,r,i,n){var s=X.writeRtpDescription(e.kind,t);if(s+=X.writeIceParameters(e.iceGatherer.getLocalParameters()),s+=X.writeDtlsParameters(e.dtlsTransport.getLocalParameters(),"offer"===r?"actpass":n||"active"),s+="a=mid:"+e.mid+"\r\n",e.rtpSender&&e.rtpReceiver?s+="a=sendrecv\r\n":e.rtpSender?s+="a=sendonly\r\n":e.rtpReceiver?s+="a=recvonly\r\n":s+="a=inactive\r\n",e.rtpSender){var o=e.rtpSender._initialTrackId||e.rtpSender.track.id;e.rtpSender._initialTrackId=o;var a="msid:"+(i?i.id:"-")+" "+o+"\r\n";s+="a="+a,s+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" "+a,e.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" "+a,s+="a=ssrc-group:FID "+e.sendEncodingParameters[0].ssrc+" "+e.sendEncodingParameters[0].rtx.ssrc+"\r\n")}return s+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" cname:"+X.localCName+"\r\n",e.rtpSender&&e.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" cname:"+X.localCName+"\r\n"),s}function ee(e,t){var r={codecs:[],headerExtensions:[],fecMechanisms:[]},i=function(e,t){e=parseInt(e,10);for(var r=0;r<t.length;r++)if(t[r].payloadType===e||t[r].preferredPayloadType===e)return t[r]},n=function(e,t,r,n){var s=i(e.parameters.apt,r),o=i(t.parameters.apt,n);return s&&o&&s.name.toLowerCase()===o.name.toLowerCase()};return e.codecs.forEach((function(i){for(var s=0;s<t.codecs.length;s++){var o=t.codecs[s];if(i.name.toLowerCase()===o.name.toLowerCase()&&i.clockRate===o.clockRate){if("rtx"===i.name.toLowerCase()&&i.parameters&&o.parameters.apt&&!n(i,o,e.codecs,t.codecs))continue;(o=JSON.parse(JSON.stringify(o))).numChannels=Math.min(i.numChannels,o.numChannels),r.codecs.push(o),o.rtcpFeedback=o.rtcpFeedback.filter((function(e){for(var t=0;t<i.rtcpFeedback.length;t++)if(i.rtcpFeedback[t].type===e.type&&i.rtcpFeedback[t].parameter===e.parameter)return!0;return!1}));break}}})),e.headerExtensions.forEach((function(e){for(var i=0;i<t.headerExtensions.length;i++){var n=t.headerExtensions[i];if(e.uri===n.uri){r.headerExtensions.push(n);break}}})),r}function te(e,t,r){return-1!=={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][e].indexOf(r)}function re(e,t){var r=e.getRemoteCandidates().find((function(e){return t.foundation===e.foundation&&t.ip===e.ip&&t.port===e.port&&t.priority===e.priority&&t.protocol===e.protocol&&t.type===e.type}));return r||e.addRemoteCandidate(t),!r}function ie(e,t){var r=new Error(t);return r.name=e,r.code={NotSupportedError:9,InvalidStateError:11,InvalidAccessError:15,TypeError:void 0,OperationError:void 0}[e],r}var ne=function(e,t){function r(t,r){r.addTrack(t),r.dispatchEvent(new e.MediaStreamTrackEvent("addtrack",{track:t}))}function i(t,r,i,n){var s=new Event("track");s.track=r,s.receiver=i,s.transceiver={receiver:i},s.streams=n,e.setTimeout((function(){t._dispatchEvent("track",s)}))}var n=function(r){var i=this,n=document.createDocumentFragment();if(["addEventListener","removeEventListener","dispatchEvent"].forEach((function(e){i[e]=n[e].bind(n)})),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",r=JSON.parse(JSON.stringify(r||{})),this.usingBundle="max-bundle"===r.bundlePolicy,"negotiate"===r.rtcpMuxPolicy)throw ie("NotSupportedError","rtcpMuxPolicy 'negotiate' is not supported");switch(r.rtcpMuxPolicy||(r.rtcpMuxPolicy="require"),r.iceTransportPolicy){case"all":case"relay":break;default:r.iceTransportPolicy="all"}switch(r.bundlePolicy){case"balanced":case"max-compat":case"max-bundle":break;default:r.bundlePolicy="balanced"}if(r.iceServers=function(e,t){var r=!1;return(e=JSON.parse(JSON.stringify(e))).filter((function(e){if(e&&(e.urls||e.url)){var i=e.urls||e.url;e.url&&!e.urls&&console.warn("RTCIceServer.url is deprecated! Use urls instead.");var n="string"==typeof i;return n&&(i=[i]),i=i.filter((function(e){return 0!==e.indexOf("turn:")||-1===e.indexOf("transport=udp")||-1!==e.indexOf("turn:[")||r?0===e.indexOf("stun:")&&t>=14393&&-1===e.indexOf("?transport=udp"):(r=!0,!0)})),delete e.url,e.urls=n?i[0]:i,!!i.length}}))}(r.iceServers||[],t),this._iceGatherers=[],r.iceCandidatePoolSize)for(var s=r.iceCandidatePoolSize;s>0;s--)this._iceGatherers.push(new e.RTCIceGatherer({iceServers:r.iceServers,gatherPolicy:r.iceTransportPolicy}));else r.iceCandidatePoolSize=0;this._config=r,this.transceivers=[],this._sdpSessionId=X.generateSessionId(),this._sdpSessionVersion=0,this._dtlsRole=void 0,this._isClosed=!1};Object.defineProperty(n.prototype,"localDescription",{configurable:!0,get:function(){return this._localDescription}}),Object.defineProperty(n.prototype,"remoteDescription",{configurable:!0,get:function(){return this._remoteDescription}}),n.prototype.onicecandidate=null,n.prototype.onaddstream=null,n.prototype.ontrack=null,n.prototype.onremovestream=null,n.prototype.onsignalingstatechange=null,n.prototype.oniceconnectionstatechange=null,n.prototype.onconnectionstatechange=null,n.prototype.onicegatheringstatechange=null,n.prototype.onnegotiationneeded=null,n.prototype.ondatachannel=null,n.prototype._dispatchEvent=function(e,t){this._isClosed||(this.dispatchEvent(t),"function"==typeof this["on"+e]&&this["on"+e](t))},n.prototype._emitGatheringStateChange=function(){var e=new Event("icegatheringstatechange");this._dispatchEvent("icegatheringstatechange",e)},n.prototype.getConfiguration=function(){return this._config},n.prototype.getLocalStreams=function(){return this.localStreams},n.prototype.getRemoteStreams=function(){return this.remoteStreams},n.prototype._createTransceiver=function(e,t){var r=this.transceivers.length>0,i={track:null,iceGatherer:null,iceTransport:null,dtlsTransport:null,localCapabilities:null,remoteCapabilities:null,rtpSender:null,rtpReceiver:null,kind:e,mid:null,sendEncodingParameters:null,recvEncodingParameters:null,stream:null,associatedRemoteMediaStreams:[],wantReceive:!0};if(this.usingBundle&&r)i.iceTransport=this.transceivers[0].iceTransport,i.dtlsTransport=this.transceivers[0].dtlsTransport;else{var n=this._createIceAndDtlsTransports();i.iceTransport=n.iceTransport,i.dtlsTransport=n.dtlsTransport}return t||this.transceivers.push(i),i},n.prototype.addTrack=function(t,r){if(this._isClosed)throw ie("InvalidStateError","Attempted to call addTrack on a closed peerconnection.");var i;if(this.transceivers.find((function(e){return e.track===t})))throw ie("InvalidAccessError","Track already exists.");for(var n=0;n<this.transceivers.length;n++)this.transceivers[n].track||this.transceivers[n].kind!==t.kind||(i=this.transceivers[n]);return i||(i=this._createTransceiver(t.kind)),this._maybeFireNegotiationNeeded(),-1===this.localStreams.indexOf(r)&&this.localStreams.push(r),i.track=t,i.stream=r,i.rtpSender=new e.RTCRtpSender(t,i.dtlsTransport),i.rtpSender},n.prototype.addStream=function(e){var r=this;if(t>=15025)e.getTracks().forEach((function(t){r.addTrack(t,e)}));else{var i=e.clone();e.getTracks().forEach((function(e,t){var r=i.getTracks()[t];e.addEventListener("enabled",(function(e){r.enabled=e.enabled}))})),i.getTracks().forEach((function(e){r.addTrack(e,i)}))}},n.prototype.removeTrack=function(t){if(this._isClosed)throw ie("InvalidStateError","Attempted to call removeTrack on a closed peerconnection.");if(!(t instanceof e.RTCRtpSender))throw new TypeError("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.");var r=this.transceivers.find((function(e){return e.rtpSender===t}));if(!r)throw ie("InvalidAccessError","Sender was not created by this connection.");var i=r.stream;r.rtpSender.stop(),r.rtpSender=null,r.track=null,r.stream=null,-1===this.transceivers.map((function(e){return e.stream})).indexOf(i)&&this.localStreams.indexOf(i)>-1&&this.localStreams.splice(this.localStreams.indexOf(i),1),this._maybeFireNegotiationNeeded()},n.prototype.removeStream=function(e){var t=this;e.getTracks().forEach((function(e){var r=t.getSenders().find((function(t){return t.track===e}));r&&t.removeTrack(r)}))},n.prototype.getSenders=function(){return this.transceivers.filter((function(e){return!!e.rtpSender})).map((function(e){return e.rtpSender}))},n.prototype.getReceivers=function(){return this.transceivers.filter((function(e){return!!e.rtpReceiver})).map((function(e){return e.rtpReceiver}))},n.prototype._createIceGatherer=function(t,r){var i=this;if(r&&t>0)return this.transceivers[0].iceGatherer;if(this._iceGatherers.length)return this._iceGatherers.shift();var n=new e.RTCIceGatherer({iceServers:this._config.iceServers,gatherPolicy:this._config.iceTransportPolicy});return Object.defineProperty(n,"state",{value:"new",writable:!0}),this.transceivers[t].bufferedCandidateEvents=[],this.transceivers[t].bufferCandidates=function(e){var r=!e.candidate||0===Object.keys(e.candidate).length;n.state=r?"completed":"gathering",null!==i.transceivers[t].bufferedCandidateEvents&&i.transceivers[t].bufferedCandidateEvents.push(e)},n.addEventListener("localcandidate",this.transceivers[t].bufferCandidates),n},n.prototype._gather=function(t,r){var i=this,n=this.transceivers[r].iceGatherer;if(!n.onlocalcandidate){var s=this.transceivers[r].bufferedCandidateEvents;this.transceivers[r].bufferedCandidateEvents=null,n.removeEventListener("localcandidate",this.transceivers[r].bufferCandidates),n.onlocalcandidate=function(e){if(!(i.usingBundle&&r>0)){var s=new Event("icecandidate");s.candidate={sdpMid:t,sdpMLineIndex:r};var o=e.candidate,a=!o||0===Object.keys(o).length;if(a)"new"!==n.state&&"gathering"!==n.state||(n.state="completed");else{"new"===n.state&&(n.state="gathering"),o.component=1,o.ufrag=n.getLocalParameters().usernameFragment;var c=X.writeCandidate(o);s.candidate=Object.assign(s.candidate,X.parseCandidate(c)),s.candidate.candidate=c,s.candidate.toJSON=function(){return{candidate:s.candidate.candidate,sdpMid:s.candidate.sdpMid,sdpMLineIndex:s.candidate.sdpMLineIndex,usernameFragment:s.candidate.usernameFragment}}}var d=X.getMediaSections(i._localDescription.sdp);d[s.candidate.sdpMLineIndex]+=a?"a=end-of-candidates\r\n":"a="+s.candidate.candidate+"\r\n",i._localDescription.sdp=X.getDescription(i._localDescription.sdp)+d.join("");var u=i.transceivers.every((function(e){return e.iceGatherer&&"completed"===e.iceGatherer.state}));"gathering"!==i.iceGatheringState&&(i.iceGatheringState="gathering",i._emitGatheringStateChange()),a||i._dispatchEvent("icecandidate",s),u&&(i._dispatchEvent("icecandidate",new Event("icecandidate")),i.iceGatheringState="complete",i._emitGatheringStateChange())}},e.setTimeout((function(){s.forEach((function(e){n.onlocalcandidate(e)}))}),0)}},n.prototype._createIceAndDtlsTransports=function(){var t=this,r=new e.RTCIceTransport(null);r.onicestatechange=function(){t._updateIceConnectionState(),t._updateConnectionState()};var i=new e.RTCDtlsTransport(r);return i.ondtlsstatechange=function(){t._updateConnectionState()},i.onerror=function(){Object.defineProperty(i,"state",{value:"failed",writable:!0}),t._updateConnectionState()},{iceTransport:r,dtlsTransport:i}},n.prototype._disposeIceAndDtlsTransports=function(e){var t=this.transceivers[e].iceGatherer;t&&(delete t.onlocalcandidate,delete this.transceivers[e].iceGatherer);var r=this.transceivers[e].iceTransport;r&&(delete r.onicestatechange,delete this.transceivers[e].iceTransport);var i=this.transceivers[e].dtlsTransport;i&&(delete i.ondtlsstatechange,delete i.onerror,delete this.transceivers[e].dtlsTransport)},n.prototype._transceive=function(e,r,i){var n=ee(e.localCapabilities,e.remoteCapabilities);r&&e.rtpSender&&(n.encodings=e.sendEncodingParameters,n.rtcp={cname:X.localCName,compound:e.rtcpParameters.compound},e.recvEncodingParameters.length&&(n.rtcp.ssrc=e.recvEncodingParameters[0].ssrc),e.rtpSender.send(n)),i&&e.rtpReceiver&&n.codecs.length>0&&("video"===e.kind&&e.recvEncodingParameters&&t<15019&&e.recvEncodingParameters.forEach((function(e){delete e.rtx})),e.recvEncodingParameters.length?n.encodings=e.recvEncodingParameters:n.encodings=[{}],n.rtcp={compound:e.rtcpParameters.compound},e.rtcpParameters.cname&&(n.rtcp.cname=e.rtcpParameters.cname),e.sendEncodingParameters.length&&(n.rtcp.ssrc=e.sendEncodingParameters[0].ssrc),e.rtpReceiver.receive(n))},n.prototype.setLocalDescription=function(e){var t,r,i=this;if(-1===["offer","answer"].indexOf(e.type))return Promise.reject(ie("TypeError",'Unsupported type "'+e.type+'"'));if(!te("setLocalDescription",e.type,i.signalingState)||i._isClosed)return Promise.reject(ie("InvalidStateError","Can not set local "+e.type+" in state "+i.signalingState));if("offer"===e.type)t=X.splitSections(e.sdp),r=t.shift(),t.forEach((function(e,t){var r=X.parseRtpParameters(e);i.transceivers[t].localCapabilities=r})),i.transceivers.forEach((function(e,t){i._gather(e.mid,t)}));else if("answer"===e.type){t=X.splitSections(i._remoteDescription.sdp),r=t.shift();var n=X.matchPrefix(r,"a=ice-lite").length>0;t.forEach((function(e,t){var s=i.transceivers[t],o=s.iceGatherer,a=s.iceTransport,c=s.dtlsTransport,d=s.localCapabilities,u=s.remoteCapabilities;if(!(X.isRejected(e)&&0===X.matchPrefix(e,"a=bundle-only").length)&&!s.rejected){var l=X.getIceParameters(e,r),h=X.getDtlsParameters(e,r);n&&(h.role="server"),i.usingBundle&&0!==t||(i._gather(s.mid,t),"new"===a.state&&a.start(o,l,n?"controlling":"controlled"),"new"===c.state&&c.start(h));var p=ee(d,u);i._transceive(s,p.codecs.length>0,!1)}}))}return i._localDescription={type:e.type,sdp:e.sdp},"offer"===e.type?i._updateSignalingState("have-local-offer"):i._updateSignalingState("stable"),Promise.resolve()},n.prototype.setRemoteDescription=function(n){var s=this;if(-1===["offer","answer"].indexOf(n.type))return Promise.reject(ie("TypeError",'Unsupported type "'+n.type+'"'));if(!te("setRemoteDescription",n.type,s.signalingState)||s._isClosed)return Promise.reject(ie("InvalidStateError","Can not set remote "+n.type+" in state "+s.signalingState));var o={};s.remoteStreams.forEach((function(e){o[e.id]=e}));var a=[],c=X.splitSections(n.sdp),d=c.shift(),u=X.matchPrefix(d,"a=ice-lite").length>0,l=X.matchPrefix(d,"a=group:BUNDLE ").length>0;s.usingBundle=l;var h=X.matchPrefix(d,"a=ice-options:")[0];return s.canTrickleIceCandidates=!!h&&h.substr(14).split(" ").indexOf("trickle")>=0,c.forEach((function(i,c){var h=X.splitLines(i),p=X.getKind(i),_=X.isRejected(i)&&0===X.matchPrefix(i,"a=bundle-only").length,m=h[0].substr(2).split(" ")[2],f=X.getDirection(i,d),v=X.parseMsid(i),g=X.getMid(i)||X.generateIdentifier();if(_||"application"===p&&("DTLS/SCTP"===m||"UDP/DTLS/SCTP"===m))s.transceivers[c]={mid:g,kind:p,protocol:m,rejected:!0};else{var R,S,T,C,E,y,I,k,b;!_&&s.transceivers[c]&&s.transceivers[c].rejected&&(s.transceivers[c]=s._createTransceiver(p,!0));var P,O,L=X.parseRtpParameters(i);_||(P=X.getIceParameters(i,d),(O=X.getDtlsParameters(i,d)).role="client"),I=X.parseRtpEncodingParameters(i);var D=X.parseRtcpParameters(i),N=X.matchPrefix(i,"a=end-of-candidates",d).length>0,A=X.matchPrefix(i,"a=candidate:").map((function(e){return X.parseCandidate(e)})).filter((function(e){return 1===e.component}));if(("offer"===n.type||"answer"===n.type)&&!_&&l&&c>0&&s.transceivers[c]&&(s._disposeIceAndDtlsTransports(c),s.transceivers[c].iceGatherer=s.transceivers[0].iceGatherer,s.transceivers[c].iceTransport=s.transceivers[0].iceTransport,s.transceivers[c].dtlsTransport=s.transceivers[0].dtlsTransport,s.transceivers[c].rtpSender&&s.transceivers[c].rtpSender.setTransport(s.transceivers[0].dtlsTransport),s.transceivers[c].rtpReceiver&&s.transceivers[c].rtpReceiver.setTransport(s.transceivers[0].dtlsTransport)),"offer"!==n.type||_){if("answer"===n.type&&!_){S=(R=s.transceivers[c]).iceGatherer,T=R.iceTransport,C=R.dtlsTransport,E=R.rtpReceiver,y=R.sendEncodingParameters,k=R.localCapabilities,s.transceivers[c].recvEncodingParameters=I,s.transceivers[c].remoteCapabilities=L,s.transceivers[c].rtcpParameters=D,A.length&&"new"===T.state&&(!u&&!N||l&&0!==c?A.forEach((function(e){re(R.iceTransport,e)})):T.setRemoteCandidates(A)),l&&0!==c||("new"===T.state&&T.start(S,P,"controlling"),"new"===C.state&&C.start(O)),!ee(R.localCapabilities,R.remoteCapabilities).codecs.filter((function(e){return"rtx"===e.name.toLowerCase()})).length&&R.sendEncodingParameters[0].rtx&&delete R.sendEncodingParameters[0].rtx,s._transceive(R,"sendrecv"===f||"recvonly"===f,"sendrecv"===f||"sendonly"===f),!E||"sendrecv"!==f&&"sendonly"!==f?delete R.rtpReceiver:(b=E.track,v?(o[v.stream]||(o[v.stream]=new e.MediaStream),r(b,o[v.stream]),a.push([b,E,o[v.stream]])):(o.default||(o.default=new e.MediaStream),r(b,o.default),a.push([b,E,o.default])))}}else{(R=s.transceivers[c]||s._createTransceiver(p)).mid=g,R.iceGatherer||(R.iceGatherer=s._createIceGatherer(c,l)),A.length&&"new"===R.iceTransport.state&&(!N||l&&0!==c?A.forEach((function(e){re(R.iceTransport,e)})):R.iceTransport.setRemoteCandidates(A)),k=e.RTCRtpReceiver.getCapabilities(p),t<15019&&(k.codecs=k.codecs.filter((function(e){return"rtx"!==e.name}))),y=R.sendEncodingParameters||[{ssrc:1001*(2*c+2)}];var M,x=!1;if("sendrecv"===f||"sendonly"===f){if(x=!R.rtpReceiver,E=R.rtpReceiver||new e.RTCRtpReceiver(R.dtlsTransport,p),x)b=E.track,v&&"-"===v.stream||(v?(o[v.stream]||(o[v.stream]=new e.MediaStream,Object.defineProperty(o[v.stream],"id",{get:function(){return v.stream}})),Object.defineProperty(b,"id",{get:function(){return v.track}}),M=o[v.stream]):(o.default||(o.default=new e.MediaStream),M=o.default)),M&&(r(b,M),R.associatedRemoteMediaStreams.push(M)),a.push([b,E,M])}else R.rtpReceiver&&R.rtpReceiver.track&&(R.associatedRemoteMediaStreams.forEach((function(t){var r=t.getTracks().find((function(e){return e.id===R.rtpReceiver.track.id}));r&&function(t,r){r.removeTrack(t),r.dispatchEvent(new e.MediaStreamTrackEvent("removetrack",{track:t}))}(r,t)})),R.associatedRemoteMediaStreams=[]);R.localCapabilities=k,R.remoteCapabilities=L,R.rtpReceiver=E,R.rtcpParameters=D,R.sendEncodingParameters=y,R.recvEncodingParameters=I,s._transceive(s.transceivers[c],!1,x)}}})),void 0===s._dtlsRole&&(s._dtlsRole="offer"===n.type?"active":"passive"),s._remoteDescription={type:n.type,sdp:n.sdp},"offer"===n.type?s._updateSignalingState("have-remote-offer"):s._updateSignalingState("stable"),Object.keys(o).forEach((function(t){var r=o[t];if(r.getTracks().length){if(-1===s.remoteStreams.indexOf(r)){s.remoteStreams.push(r);var n=new Event("addstream");n.stream=r,e.setTimeout((function(){s._dispatchEvent("addstream",n)}))}a.forEach((function(e){var t=e[0],n=e[1];r.id===e[2].id&&i(s,t,n,[r])}))}})),a.forEach((function(e){e[2]||i(s,e[0],e[1],[])})),e.setTimeout((function(){s&&s.transceivers&&s.transceivers.forEach((function(e){e.iceTransport&&"new"===e.iceTransport.state&&e.iceTransport.getRemoteCandidates().length>0&&(console.warn("Timeout for addRemoteCandidate. Consider sending an end-of-candidates notification"),e.iceTransport.addRemoteCandidate({}))}))}),4e3),Promise.resolve()},n.prototype.close=function(){this.transceivers.forEach((function(e){e.iceTransport&&e.iceTransport.stop(),e.dtlsTransport&&e.dtlsTransport.stop(),e.rtpSender&&e.rtpSender.stop(),e.rtpReceiver&&e.rtpReceiver.stop()})),this._isClosed=!0,this._updateSignalingState("closed")},n.prototype._updateSignalingState=function(e){this.signalingState=e;var t=new Event("signalingstatechange");this._dispatchEvent("signalingstatechange",t)},n.prototype._maybeFireNegotiationNeeded=function(){var t=this;"stable"===this.signalingState&&!0!==this.needNegotiation&&(this.needNegotiation=!0,e.setTimeout((function(){if(t.needNegotiation){t.needNegotiation=!1;var e=new Event("negotiationneeded");t._dispatchEvent("negotiationneeded",e)}}),0))},n.prototype._updateIceConnectionState=function(){var e,t={new:0,closed:0,checking:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach((function(e){e.iceTransport&&!e.rejected&&t[e.iceTransport.state]++})),e="new",t.failed>0?e="failed":t.checking>0?e="checking":t.disconnected>0?e="disconnected":t.new>0?e="new":t.connected>0?e="connected":t.completed>0&&(e="completed"),e!==this.iceConnectionState){this.iceConnectionState=e;var r=new Event("iceconnectionstatechange");this._dispatchEvent("iceconnectionstatechange",r)}},n.prototype._updateConnectionState=function(){var e,t={new:0,closed:0,connecting:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach((function(e){e.iceTransport&&e.dtlsTransport&&!e.rejected&&(t[e.iceTransport.state]++,t[e.dtlsTransport.state]++)})),t.connected+=t.completed,e="new",t.failed>0?e="failed":t.connecting>0?e="connecting":t.disconnected>0?e="disconnected":t.new>0?e="new":t.connected>0&&(e="connected"),e!==this.connectionState){this.connectionState=e;var r=new Event("connectionstatechange");this._dispatchEvent("connectionstatechange",r)}},n.prototype.createOffer=function(){var r=this;if(r._isClosed)return Promise.reject(ie("InvalidStateError","Can not call createOffer after close"));var i=r.transceivers.filter((function(e){return"audio"===e.kind})).length,n=r.transceivers.filter((function(e){return"video"===e.kind})).length,s=arguments[0];if(s){if(s.mandatory||s.optional)throw new TypeError("Legacy mandatory/optional constraints not supported.");void 0!==s.offerToReceiveAudio&&(i=!0===s.offerToReceiveAudio?1:!1===s.offerToReceiveAudio?0:s.offerToReceiveAudio),void 0!==s.offerToReceiveVideo&&(n=!0===s.offerToReceiveVideo?1:!1===s.offerToReceiveVideo?0:s.offerToReceiveVideo)}for(r.transceivers.forEach((function(e){"audio"===e.kind?--i<0&&(e.wantReceive=!1):"video"===e.kind&&--n<0&&(e.wantReceive=!1)}));i>0||n>0;)i>0&&(r._createTransceiver("audio"),i--),n>0&&(r._createTransceiver("video"),n--);var o=X.writeSessionBoilerplate(r._sdpSessionId,r._sdpSessionVersion++);r.transceivers.forEach((function(i,n){var s=i.track,o=i.kind,a=i.mid||X.generateIdentifier();i.mid=a,i.iceGatherer||(i.iceGatherer=r._createIceGatherer(n,r.usingBundle));var c=e.RTCRtpSender.getCapabilities(o);t<15019&&(c.codecs=c.codecs.filter((function(e){return"rtx"!==e.name}))),c.codecs.forEach((function(e){"H264"===e.name&&void 0===e.parameters["level-asymmetry-allowed"]&&(e.parameters["level-asymmetry-allowed"]="1"),i.remoteCapabilities&&i.remoteCapabilities.codecs&&i.remoteCapabilities.codecs.forEach((function(t){e.name.toLowerCase()===t.name.toLowerCase()&&e.clockRate===t.clockRate&&(e.preferredPayloadType=t.payloadType)}))})),c.headerExtensions.forEach((function(e){(i.remoteCapabilities&&i.remoteCapabilities.headerExtensions||[]).forEach((function(t){e.uri===t.uri&&(e.id=t.id)}))}));var d=i.sendEncodingParameters||[{ssrc:1001*(2*n+1)}];s&&t>=15019&&"video"===o&&!d[0].rtx&&(d[0].rtx={ssrc:d[0].ssrc+1}),i.wantReceive&&(i.rtpReceiver=new e.RTCRtpReceiver(i.dtlsTransport,o)),i.localCapabilities=c,i.sendEncodingParameters=d})),"max-compat"!==r._config.bundlePolicy&&(o+="a=group:BUNDLE "+r.transceivers.map((function(e){return e.mid})).join(" ")+"\r\n"),o+="a=ice-options:trickle\r\n",r.transceivers.forEach((function(e,t){o+=Z(e,e.localCapabilities,"offer",e.stream,r._dtlsRole),o+="a=rtcp-rsize\r\n",!e.iceGatherer||"new"===r.iceGatheringState||0!==t&&r.usingBundle||(e.iceGatherer.getLocalCandidates().forEach((function(e){e.component=1,o+="a="+X.writeCandidate(e)+"\r\n"})),"completed"===e.iceGatherer.state&&(o+="a=end-of-candidates\r\n"))}));var a=new e.RTCSessionDescription({type:"offer",sdp:o});return Promise.resolve(a)},n.prototype.createAnswer=function(){var r=this;if(r._isClosed)return Promise.reject(ie("InvalidStateError","Can not call createAnswer after close"));if("have-remote-offer"!==r.signalingState&&"have-local-pranswer"!==r.signalingState)return Promise.reject(ie("InvalidStateError","Can not call createAnswer in signalingState "+r.signalingState));var i=X.writeSessionBoilerplate(r._sdpSessionId,r._sdpSessionVersion++);r.usingBundle&&(i+="a=group:BUNDLE "+r.transceivers.map((function(e){return e.mid})).join(" ")+"\r\n"),i+="a=ice-options:trickle\r\n";var n=X.getMediaSections(r._remoteDescription.sdp).length;r.transceivers.forEach((function(e,s){if(!(s+1>n)){if(e.rejected)return"application"===e.kind?"DTLS/SCTP"===e.protocol?i+="m=application 0 DTLS/SCTP 5000\r\n":i+="m=application 0 "+e.protocol+" webrtc-datachannel\r\n":"audio"===e.kind?i+="m=audio 0 UDP/TLS/RTP/SAVPF 0\r\na=rtpmap:0 PCMU/8000\r\n":"video"===e.kind&&(i+="m=video 0 UDP/TLS/RTP/SAVPF 120\r\na=rtpmap:120 VP8/90000\r\n"),void(i+="c=IN IP4 0.0.0.0\r\na=inactive\r\na=mid:"+e.mid+"\r\n");var o;if(e.stream)"audio"===e.kind?o=e.stream.getAudioTracks()[0]:"video"===e.kind&&(o=e.stream.getVideoTracks()[0]),o&&t>=15019&&"video"===e.kind&&!e.sendEncodingParameters[0].rtx&&(e.sendEncodingParameters[0].rtx={ssrc:e.sendEncodingParameters[0].ssrc+1});var a=ee(e.localCapabilities,e.remoteCapabilities);!a.codecs.filter((function(e){return"rtx"===e.name.toLowerCase()})).length&&e.sendEncodingParameters[0].rtx&&delete e.sendEncodingParameters[0].rtx,i+=Z(e,a,"answer",e.stream,r._dtlsRole),e.rtcpParameters&&e.rtcpParameters.reducedSize&&(i+="a=rtcp-rsize\r\n")}}));var s=new e.RTCSessionDescription({type:"answer",sdp:i});return Promise.resolve(s)},n.prototype.addIceCandidate=function(e){var t,r=this;return e&&void 0===e.sdpMLineIndex&&!e.sdpMid?Promise.reject(new TypeError("sdpMLineIndex or sdpMid required")):new Promise((function(i,n){if(!r._remoteDescription)return n(ie("InvalidStateError","Can not add ICE candidate without a remote description"));if(e&&""!==e.candidate){var s=e.sdpMLineIndex;if(e.sdpMid)for(var o=0;o<r.transceivers.length;o++)if(r.transceivers[o].mid===e.sdpMid){s=o;break}var a=r.transceivers[s];if(!a)return n(ie("OperationError","Can not add ICE candidate"));if(a.rejected)return i();var c=Object.keys(e.candidate).length>0?X.parseCandidate(e.candidate):{};if("tcp"===c.protocol&&(0===c.port||9===c.port))return i();if(c.component&&1!==c.component)return i();if((0===s||s>0&&a.iceTransport!==r.transceivers[0].iceTransport)&&!re(a.iceTransport,c))return n(ie("OperationError","Can not add ICE candidate"));var d=e.candidate.trim();0===d.indexOf("a=")&&(d=d.substr(2)),(t=X.getMediaSections(r._remoteDescription.sdp))[s]+="a="+(c.type?d:"end-of-candidates")+"\r\n",r._remoteDescription.sdp=X.getDescription(r._remoteDescription.sdp)+t.join("")}else for(var u=0;u<r.transceivers.length&&(r.transceivers[u].rejected||(r.transceivers[u].iceTransport.addRemoteCandidate({}),(t=X.getMediaSections(r._remoteDescription.sdp))[u]+="a=end-of-candidates\r\n",r._remoteDescription.sdp=X.getDescription(r._remoteDescription.sdp)+t.join(""),!r.usingBundle));u++);i()}))},n.prototype.getStats=function(t){if(t&&t instanceof e.MediaStreamTrack){var r=null;if(this.transceivers.forEach((function(e){e.rtpSender&&e.rtpSender.track===t?r=e.rtpSender:e.rtpReceiver&&e.rtpReceiver.track===t&&(r=e.rtpReceiver)})),!r)throw ie("InvalidAccessError","Invalid selector.");return r.getStats()}var i=[];return this.transceivers.forEach((function(e){["rtpSender","rtpReceiver","iceGatherer","iceTransport","dtlsTransport"].forEach((function(t){e[t]&&i.push(e[t].getStats())}))})),Promise.all(i).then((function(e){var t=new Map;return e.forEach((function(e){e.forEach((function(e){t.set(e.id,e)}))})),t}))};["RTCRtpSender","RTCRtpReceiver","RTCIceGatherer","RTCIceTransport","RTCDtlsTransport"].forEach((function(t){var r=e[t];if(r&&r.prototype&&r.prototype.getStats){var i=r.prototype.getStats;r.prototype.getStats=function(){return i.apply(this).then((function(e){var t=new Map;return Object.keys(e).forEach((function(r){var i;e[r].type={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[(i=e[r]).type]||i.type,t.set(r,e[r])})),t}))}}}));var s=["createOffer","createAnswer"];return s.forEach((function(e){var t=n.prototype[e];n.prototype[e]=function(){var e=arguments;return"function"==typeof e[0]||"function"==typeof e[1]?t.apply(this,[arguments[2]]).then((function(t){"function"==typeof e[0]&&e[0].apply(null,[t])}),(function(t){"function"==typeof e[1]&&e[1].apply(null,[t])})):t.apply(this,arguments)}})),(s=["setLocalDescription","setRemoteDescription","addIceCandidate"]).forEach((function(e){var t=n.prototype[e];n.prototype[e]=function(){var e=arguments;return"function"==typeof e[1]||"function"==typeof e[2]?t.apply(this,arguments).then((function(){"function"==typeof e[1]&&e[1].apply(null)}),(function(t){"function"==typeof e[2]&&e[2].apply(null,[t])})):t.apply(this,arguments)}})),["getStats"].forEach((function(e){var t=n.prototype[e];n.prototype[e]=function(){var e=arguments;return"function"==typeof e[1]?t.apply(this,arguments).then((function(){"function"==typeof e[1]&&e[1].apply(null)})):t.apply(this,arguments)}})),n};function se(e){const t=e&&e.navigator,r=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(e){return r(e).catch((e=>Promise.reject(function(e){return{name:{PermissionDeniedError:"NotAllowedError"}[e.name]||e.name,message:e.message,constraint:e.constraint,toString(){return this.name}}}(e))))}}function oe(e){"getDisplayMedia"in e.navigator&&e.navigator.mediaDevices&&(e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||(e.navigator.mediaDevices.getDisplayMedia=e.navigator.getDisplayMedia.bind(e.navigator)))}function ae(e,t){if(e.RTCIceGatherer&&(e.RTCIceCandidate||(e.RTCIceCandidate=function(e){return e}),e.RTCSessionDescription||(e.RTCSessionDescription=function(e){return e}),t.version<15025)){const t=Object.getOwnPropertyDescriptor(e.MediaStreamTrack.prototype,"enabled");Object.defineProperty(e.MediaStreamTrack.prototype,"enabled",{set(e){t.set.call(this,e);const r=new Event("enabled");r.enabled=e,this.dispatchEvent(r)}})}e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)&&Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=new e.RTCDtmfSender(this):"video"===this.track.kind&&(this._dtmf=null)),this._dtmf}}),e.RTCDtmfSender&&!e.RTCDTMFSender&&(e.RTCDTMFSender=e.RTCDtmfSender);const r=ne(e,t.version);e.RTCPeerConnection=function(e){return e&&e.iceServers&&(e.iceServers=function(e,t){let r=!1;return(e=JSON.parse(JSON.stringify(e))).filter((e=>{if(e&&(e.urls||e.url)){let t=e.urls||e.url;e.url&&!e.urls&&A("RTCIceServer.url","RTCIceServer.urls");const i="string"==typeof t;return i&&(t=[t]),t=t.filter((e=>{if(0===e.indexOf("stun:"))return!1;const t=e.startsWith("turn")&&!e.startsWith("turn:[")&&e.includes("transport=udp");return t&&!r?(r=!0,!0):t&&!r})),delete e.url,e.urls=i?t[0]:t,!!t.length}}))}(e.iceServers,t.version),N("ICE servers after filtering:",e.iceServers)),new r(e)},e.RTCPeerConnection.prototype=r.prototype}function ce(e){e.RTCRtpSender&&!("replaceTrack"in e.RTCRtpSender.prototype)&&(e.RTCRtpSender.prototype.replaceTrack=e.RTCRtpSender.prototype.setTrack)}var de=Object.freeze({__proto__:null,shimPeerConnection:ae,shimReplaceTrack:ce,shimGetUserMedia:se,shimGetDisplayMedia:oe});function ue(e,t){const r=e&&e.navigator,i=e&&e.MediaStreamTrack;if(r.getUserMedia=function(e,t,i){A("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),r.mediaDevices.getUserMedia(e).then(t,i)},!(t.version>55&&"autoGainControl"in r.mediaDevices.getSupportedConstraints())){const e=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])},t=r.mediaDevices.getUserMedia.bind(r.mediaDevices);if(r.mediaDevices.getUserMedia=function(r){return"object"==typeof r&&"object"==typeof r.audio&&(r=JSON.parse(JSON.stringify(r)),e(r.audio,"autoGainControl","mozAutoGainControl"),e(r.audio,"noiseSuppression","mozNoiseSuppression")),t(r)},i&&i.prototype.getSettings){const t=i.prototype.getSettings;i.prototype.getSettings=function(){const r=t.apply(this,arguments);return e(r,"mozAutoGainControl","autoGainControl"),e(r,"mozNoiseSuppression","noiseSuppression"),r}}if(i&&i.prototype.applyConstraints){const t=i.prototype.applyConstraints;i.prototype.applyConstraints=function(r){return"audio"===this.kind&&"object"==typeof r&&(r=JSON.parse(JSON.stringify(r)),e(r,"autoGainControl","mozAutoGainControl"),e(r,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[r])}}}}function le(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function he(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]}));const r={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,n,s]=arguments;return i.apply(this,[e||null]).then((e=>{if(t.version<53&&!n)try{e.forEach((e=>{e.type=r[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach(((t,i)=>{e.set(i,Object.assign({},t,{type:r[t.type]||t.type}))}))}return e})).then(n,s)}}function pe(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=r.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function _e(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),O(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function me(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){A("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function fe(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function ve(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];const e=arguments[1],r=e&&"sendEncodings"in e;r&&e.sendEncodings.forEach((e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const i=t.apply(this,arguments);if(r){const{sender:t}=i,r=t.getParameters();(!("encodings"in r)||1===r.encodings.length&&0===Object.keys(r.encodings[0]).length)&&(r.encodings=e.sendEncodings,t.sendEncodings=e.sendEncodings,this.setParametersPromises.push(t.setParameters(r).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return i})}function ge(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function Re(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}function Se(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}var Te=Object.freeze({__proto__:null,shimOnTrack:le,shimPeerConnection:he,shimSenderGetStats:pe,shimReceiverGetStats:_e,shimRemoveStream:me,shimRTCDataChannel:fe,shimAddTransceiver:ve,shimGetParameters:ge,shimCreateOffer:Re,shimCreateAnswer:Se,shimGetUserMedia:ue,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(r){if(!r||!r.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===r.video?r.video={mediaSource:t}:r.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(r)})}});function Ce(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((r=>t.call(this,r,e))),e.getVideoTracks().forEach((r=>t.call(this,r,e)))},e.RTCPeerConnection.prototype.addTrack=function(e,...r){return r&&r.forEach((e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const r=e.getTracks();this.getSenders().forEach((e=>{r.includes(e.track)&&this.removeTrack(e)}))})}}function Ee(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach((e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const r=new Event("addstream");r.stream=t,e.dispatchEvent(r)}))}),t.apply(e,arguments)}}}function ye(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,r=t.createOffer,i=t.createAnswer,n=t.setLocalDescription,s=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],n=r.apply(this,[i]);return t?(n.then(e,t),Promise.resolve()):n},t.createAnswer=function(e,t){const r=arguments.length>=2?arguments[2]:arguments[0],n=i.apply(this,[r]);return t?(n.then(e,t),Promise.resolve()):n};let a=function(e,t,r){const i=n.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i};t.setLocalDescription=a,a=function(e,t,r){const i=s.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i},t.setRemoteDescription=a,a=function(e,t,r){const i=o.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i},t.addIceCandidate=a}function Ie(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,r=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>r(ke(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,r,i){t.mediaDevices.getUserMedia(e).then(r,i)}.bind(t))}function ke(e){return e&&void 0!==e.video?Object.assign({},e,{video:x(e.video)}):e}function be(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,r){if(e&&e.iceServers){const t=[];for(let r=0;r<e.iceServers.length;r++){let i=e.iceServers[r];!i.hasOwnProperty("urls")&&i.hasOwnProperty("url")?(A("RTCIceServer.url","RTCIceServer.urls"),i=JSON.parse(JSON.stringify(i)),i.urls=i.url,delete i.url,t.push(i)):t.push(e.iceServers[r])}e.iceServers=t}return new t(e,r)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function Pe(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Oe(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find((e=>"audio"===e.receiver.track.kind));!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio"),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const r=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&r?"sendrecv"===r.direction?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":"recvonly"===r.direction&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):!0!==e.offerToReceiveVideo||r||this.addTransceiver("video")}return t.apply(this,arguments)}}function Le(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var De=Object.freeze({__proto__:null,shimLocalStreamsAPI:Ce,shimRemoteStreamsAPI:Ee,shimCallbacksAPI:ye,shimGetUserMedia:Ie,shimConstraints:ke,shimRTCIceServerUrls:be,shimTrackEventTransceiver:Pe,shimCreateOfferLegacy:Oe,shimAudioContext:Le});function Ne(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substr(2)),e.candidate&&e.candidate.length){const r=new t(e),i=X.parseCandidate(e.candidate),n=Object.assign(r,i);return n.toJSON=function(){return{candidate:n.candidate,sdpMid:n.sdpMid,sdpMLineIndex:n.sdpMLineIndex,usernameFragment:n.usernameFragment}},n}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,O(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function Ae(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const r=function(e){if(!e||!e.sdp)return!1;const t=X.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=X.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))},i=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const r=parseInt(t[1],10);return r!=r?-1:r},n=function(e){let r=65536;return"firefox"===t.browser&&(r=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),r},s=function(e,r){let i=65536;"firefox"===t.browser&&57===t.version&&(i=65535);const n=X.matchPrefix(e.sdp,"a=max-message-size:");return n.length>0?i=parseInt(n[0].substr(19),10):"firefox"===t.browser&&-1!==r&&(i=2147483637),i},o=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(r(arguments[0])){const e=i(arguments[0]),t=n(e),r=s(arguments[0],e);let o;o=0===t&&0===r?Number.POSITIVE_INFINITY:0===t||0===r?Math.max(t,r):Math.min(t,r);const a={};Object.defineProperty(a,"maxMessageSize",{get:()=>o}),this._sctp=a}return o.apply(this,arguments)}}function Me(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const r=e.send;e.send=function(){const i=arguments[0],n=i.length||i.size||i.byteLength;if("open"===e.readyState&&t.sctp&&n>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return r.apply(e,arguments)}}const r=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=r.apply(this,arguments);return t(e,this),e},O(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function xe(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach((e=>{const r=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const r=new Event("connectionstatechange",e);t.dispatchEvent(r)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),r.apply(this,arguments)}}))}function we(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const r=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const r=t.sdp.split("\n").filter((e=>"a=extmap-allow-mixed"!==e.trim())).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:r}):t.sdp=r}return r.apply(this,arguments)}}function Ue(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const r=e.RTCPeerConnection.prototype.addIceCandidate;r&&0!==r.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():r.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}var $e=Object.freeze({__proto__:null,shimRTCIceCandidate:Ne,shimMaxMessageSize:Ae,shimSendThrowTypeError:Me,shimConnectionState:xe,removeExtmapAllowMixed:we,shimAddIceCandidateNullOrEmpty:Ue});const je=function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimEdge:!0,shimSafari:!0}){const r=N,i=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator)return t.browser="Not a browser.",t;const{navigator:r}=e;if(r.mozGetUserMedia)t.browser="firefox",t.version=P(r.userAgent,/Firefox\/(\d+)\./,1);else if(r.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection&&!e.RTCIceGatherer)t.browser="chrome",t.version=P(r.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(r.mediaDevices&&r.userAgent.match(/Edge\/(\d+).(\d+)$/))t.browser="edge",t.version=P(r.userAgent,/Edge\/(\d+).(\d+)$/,2);else{if(!e.RTCPeerConnection||!r.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=P(r.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),n={browserDetails:i,commonShim:$e,extractVersion:P,disableLog:L,disableWarnings:D};switch(i.browser){case"chrome":if(!q||!Y||!t.shimChrome)return r("Chrome shim is not included in this adapter release."),n;if(null===i.version)return r("Chrome shim can not determine version, not shimming."),n;r("adapter.js shimming chrome."),n.browserShim=q,Ue(e,i),j(e,i),V(e),Y(e,i),B(e),W(e,i),F(e),H(e),G(e),K(e,i),Ne(e),xe(e),Ae(e,i),Me(e),we(e,i);break;case"firefox":if(!Te||!he||!t.shimFirefox)return r("Firefox shim is not included in this adapter release."),n;r("adapter.js shimming firefox."),n.browserShim=Te,Ue(e,i),ue(e,i),he(e,i),le(e),me(e),pe(e),_e(e),fe(e),ve(e),ge(e),Re(e),Se(e),Ne(e),xe(e),Ae(e,i),Me(e);break;case"edge":if(!de||!ae||!t.shimEdge)return r("MS edge shim is not included in this adapter release."),n;r("adapter.js shimming edge."),n.browserShim=de,se(e),oe(e),ae(e,i),ce(e),Ae(e,i),Me(e);break;case"safari":if(!De||!t.shimSafari)return r("Safari shim is not included in this adapter release."),n;r("adapter.js shimming safari."),n.browserShim=De,Ue(e,i),be(e),Oe(e),ye(e),Ce(e),Ee(e),Pe(e),Ie(e),Le(e),Ne(e),Ae(e,i),Me(e),we(e,i);break;default:r("Unsupported browser!")}return n}({window:"undefined"==typeof window?void 0:window});var Ve,Be,Fe;!function(e){e.FPS_10="FPS_10",e.FPS_15="FPS_15",e.FPS_24="FPS_24",e.FPS_30="FPS_30"}(Ve||(Ve={})),function(e){e.W176_H132="W176_H132",e.W176_H144="W176_H144",e.W256_H144="W256_H144",e.W320_H180="W320_H180",e.W240_H240="W240_H240",e.W320_H240="W320_H240",e.W480_H360="W480_H360",e.W640_H360="W640_H360",e.W480_H480="W480_H480",e.W640_H480="W640_H480",e.W720_H480="W720_H480",e.W1280_H720="W1280_H720",e.W1920_H1080="W1920_H1080"}(Be||(Be={})),function(e){e[e.AUDIO_ONLY=0]="AUDIO_ONLY",e[e.VIDEO_ONLY=1]="VIDEO_ONLY",e[e.AUDIO_VIDEO=2]="AUDIO_VIDEO"}(Fe||(Fe={}));const He={[Be.W176_H132]:{width:176,height:132,maxBitrate:150,minBitrate:80},[Be.W176_H144]:{width:176,height:144,maxBitrate:160,minBitrate:80},[Be.W256_H144]:{width:256,height:144,maxBitrate:240,minBitrate:120},[Be.W320_H180]:{width:320,height:180,maxBitrate:280,minBitrate:120},[Be.W240_H240]:{width:240,height:240,maxBitrate:280,minBitrate:120},[Be.W320_H240]:{width:320,height:240,maxBitrate:400,minBitrate:120},[Be.W480_H360]:{width:480,height:360,maxBitrate:650,minBitrate:150},[Be.W640_H360]:{width:640,height:360,maxBitrate:800,minBitrate:180},[Be.W480_H480]:{width:480,height:480,maxBitrate:800,minBitrate:180},[Be.W640_H480]:{width:640,height:480,maxBitrate:900,minBitrate:200},[Be.W720_H480]:{width:720,height:480,maxBitrate:1e3,minBitrate:200},[Be.W1280_H720]:{width:1280,height:720,maxBitrate:2200,minBitrate:250},[Be.W1920_H1080]:{width:1920,height:1080,maxBitrate:4e3,minBitrate:400}},Ge=(e,t)=>{const r=e*t;let i=Number.MAX_VALUE,n=null;for(const e in He){const t=He[e],s=Math.abs(t.width*t.height-r);s<i&&(n=t,i=s)}return n},Je={10:1,15:1,24:1.5,30:1.5},We=e=>{let t=Number.MAX_VALUE,r=1;for(const i in Je){const n=Math.abs(e-parseInt(i));n<t&&(t=n,r=Je[i])}return r},Ye={getCameras:()=>R(void 0,void 0,void 0,(function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"videoinput"===e.kind))})),getMicrophones:()=>R(void 0,void 0,void 0,(function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"audioinput"===e.kind))})),getSpeakers:()=>R(void 0,void 0,void 0,(function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"audiooutput"===e.kind))}))};class Ke extends t{constructor(e,t,r,i,n){super(),this._tag=e,this._userId=t,this._kind=r,this._isLocalTrack=i,this._roomId=n,this._localMuted=!1,this._remoteMuted=!1,this._streamId=[this._userId||this._roomId,this._tag].join("_"),this._id=[this._streamId,this.isAudioTrack()?0:1].join("_")}getStreamId(){return this._streamId}getTrackId(){return this._id}getUserId(){return this._userId}__innerGetMediaStreamTrack(){return this._msTrack}getTag(){return this._tag}isLocalTrack(){return this._isLocalTrack}isVideoTrack(){return"video"===this._kind}isAudioTrack(){return"audio"===this._kind}isReady(){var e;return"live"===(null===(e=this._msTrack)||void 0===e?void 0:e.readyState)}__innerSetMediaStreamTrack(e){this._msTrack=e,this._setLocalMuted(this._localMuted);const t=this._msStream=this._msStream||new MediaStream,r=t.getTracks()[0];r&&t.removeTrack(r),e?t.addTrack(e):this._element&&(this._element.pause(),this._element.srcObject=null)}_setLocalMuted(e){this._msTrack&&(this._msTrack.enabled=!e),this._localMuted=e}mute(){S.info(`set ${this._id} enabled: false`),this._setLocalMuted(!0)}unmute(){S.info(`set ${this._id} enabled: true`),this._setLocalMuted(!1)}isLocalMuted(){return this._localMuted}isMCUTrack(){return Boolean(this._roomId)}isOwnerMuted(){return this._remoteMuted}play(e,t){return R(this,void 0,void 0,(function*(){if(!this._msTrack)return S.warn(`the track is not ready to play -> id: ${this._id}`),{code:T.TRACK_NOT_READY};if("ended"===this._msTrack.readyState&&S.warn(`the track's readyState is 'ended' -> id: ${this._id}`),null==t?void 0:t.volume){if(!r(null==t?void 0:t.volume))return S.error(`${null==t?void 0:t.volume} is not a number, the valid range of options.volume is 0-100`),{code:T.PARAMS_ERROR};(null==t?void 0:t.volume)<0&&(t.volume=0,S.warn("the valid range of options.volume is 0-100, the value of volume has been set 0")),(null==t?void 0:t.volume)>100&&(t.volume=100,S.warn("the valid range of options.volume is 0-100, the value of volume has been set 100"))}if(null==t?void 0:t.audioDeviceId){if(!(yield Ye.getSpeakers()).map((e=>e.deviceId)).includes(t.audioDeviceId))return S.error(`the options.audioDeviceId is invalid --\x3e ${t.audioDeviceId}`),{code:T.PARAMS_ERROR}}const i=this.isVideoTrack();if(i&&(!e||!(e instanceof HTMLVideoElement)))return S.error(`the video track need an <video> to play -> id: ${this._id}`),{code:T.VIDEO_TRACK_MISS_MEDIA_ELEMENT};this._element=i?e:this._element||new Audio,this._localMuted&&this._setLocalMuted(!1),this._element.srcObject&&this._element.srcObject===this._msStream||this._element.pause(),this._element.onloadstart=e=>{var t;S.debug(`HTMLMediaElement onloadstart -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`)},this._element.ondurationchange=e=>{var t;S.debug(`HTMLMediaElement ondurationchange -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`)},this._element.onloadedmetadata=e=>{var t;S.debug(`HTMLMediaElement onloadedmetadata -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`)},this._element.onloadeddata=e=>{var t;S.debug(`HTMLMediaElement onloadeddata -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`)},this._element.onabort=e=>{var t;S.info(`HTMLMediaElement onabort -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`)},this._element.oncanplay=e=>{var t;S.info(`HTMLMediaElement oncanplay -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`)},this._element.onvolumechange=e=>{var t;const r=Math.floor(100*(null===(t=e.target)||void 0===t?void 0:t.volume));S.info(`HTMLMediaElement onvolumechange -> volume: ${r}, trackId: ${this._id}`)},this._element.srcObject=this._msStream,this._element.autoplay=!0,i&&(this._element.playsInline=!0,this._element.x5PlaysInline=!0,this._element.webkitPlaysInline=!0),i||!(null==t?void 0:t.volume)&&0!==(null==t?void 0:t.volume)||(this._element.volume=(null==t?void 0:t.volume)/100);try{(null==t?void 0:t.audioDeviceId)&&!i?yield this._element.setSinkId(t.audioDeviceId):this._element.play()}catch(e){return"No permission to use requested device"===e.message?(S.error(`setSinkId failed -> ${e.message}`),{code:T.NO_PERMISSION_TO_USE_REQUESTED_DEVICE}):(S.error(e),{code:T.TRACK_PLAY_ERROR})}return{code:T.SUCCESS}}))}__innerDestroy(){this.__innerSetMediaStreamTrack(void 0)}__releaseMediaElement(){this._element&&(this._element.remove(),this._element.srcObject=null)}}class qe extends Ke{constructor(e,t,r,i){super(e,t,r,!0),this._isPublished=!1,this.__innerSetMediaStreamTrack(i),i.onended=()=>{i.onended=null,this.emit(qe.EVENT_LOCAL_TRACK_END,this),this.removeAll(qe.EVENT_LOCAL_TRACK_END)}}_setLocalMuted(e){const t=this._localMuted!==e;super._setLocalMuted(e),this._remoteMuted=this._localMuted,t&&this.emit(qe.__INNER_EVENT_MUTED_CHANGE__,this)}__innerSetPublished(e){this._isPublished=e}isPublished(){return this._isPublished}destroy(){var e;S.info(`track is destroyed -> trackId: ${this.getTrackId()}`),null===(e=this._msTrack)||void 0===e||e.stop(),super.__innerDestroy(),this.isAudioTrack()&&super.__releaseMediaElement(),this.emit(qe.__INNER_EVENT_DESTROY__,this)}setBitrate(e=0,t=0,i=0){!r(e)||!r(t)||!r(i)||e<=0||t<=0||e<t?S.error("setBitrate params error ->"):this._bitrateInfo={max:e,min:t,start:i}}getBitrate(){var e,t;const{min:r,max:i}=this._msTrack?pt(this._msTrack):{min:0,max:0};return{min:(null===(e=this._bitrateInfo)||void 0===e?void 0:e.min)||r,max:(null===(t=this._bitrateInfo)||void 0===t?void 0:t.max)||i}}}qe.EVENT_LOCAL_TRACK_END="local-track-end",qe.__INNER_EVENT_MUTED_CHANGE__="inner-muted-change",qe.__INNER_EVENT_DESTROY__="inner-destroy";class ze extends qe{constructor(e,t,r){super(e,t,"audio",r)}setBitrate(e,t,r){S.warn("`setBitrate` invalid for audio track")}getBitrate(){return{start:32,max:32,min:32}}}class Qe extends qe{constructor(e,t,r,i=!1){super(e,t,"video",r),this._isTiny=i}__isTiny(){return this._isTiny}getStreamId(){const e=super.getStreamId();return this._isTiny?`${e}_tiny`:e}getTrackId(){const e=super.getTrackId();return this._isTiny?`${e}_tiny`:e}}class Xe extends qe{constructor(e,t,r,i,n){super(e,t,r,i),this._resource=n,Xe.__innerSetMapping(this.getTrackId(),n)}static __innerSetMapping(e,t){const r=this._mapping.get(t)||[];r.push(e),this._mapping.set(t,r)}static __innerRemoveMapping(e,t){var r,i;const n=null===(r=this._mapping.get(t))||void 0===r?void 0:r.filter((t=>t!==e));n&&n.length>0?this._mapping.set(t,n):(this._mapping.delete(t),t.pause(),t.src="",null===(i=t.parentNode)||void 0===i||i.removeChild(t))}destroy(){this.isAudioTrack()&&this.mute(),Xe.__innerRemoveMapping(this.getTrackId(),this._resource),super.destroy()}}Xe._mapping=new Map;class Ze extends Xe{constructor(e,t,r,i){super(e,t,"video",r,i)}}class et extends Xe{constructor(e,t,r,i){super(e,t,"audio",r,i)}_setLocalMuted(e){this._resource&&(this._resource.muted=e),super._setLocalMuted(e)}play(){return this._setLocalMuted(!1),Promise.resolve({code:T.SUCCESS})}}class tt extends ze{}class rt extends Qe{}class it extends Qe{}class nt extends Ke{constructor(e,t,r,i){super(e,t,r,!1,i),this._isSubscribed=!1}__innerSetRemoteMuted(e){this._remoteMuted=e}__innerSetSubscribed(e){this._isSubscribed=e}isSubscribed(){return this._isSubscribed}}class st extends nt{constructor(e,t,r){super(e,t,"audio",r)}}class ot extends nt{constructor(e,t,r){super(e,t,"video",r)}}const at=(e,t)=>({name:e,content:JSON.stringify({uris:t,ignore:!0})}),ct=e=>JSON.stringify(e),dt=e=>/^[a-zA-Z\d-=]+$/g.test(e),ut="http:"!==location.protocol||["localhost","127.0.0.1"].includes(location.hostname),lt=e=>{if(void 0===e)return 0;if(r(e))return e;const t=e;return t.exact||t.ideal||t.max||0},ht=e=>{const t=e.getConstraints();return{width:lt(t.width),height:lt(t.height),frameRate:lt(t.frameRate)}},pt=e=>{const{width:t,height:r,frameRate:i}=ht(e),n=Ge(t,r),s=We(i);return{min:n.minBitrate*s,max:n.maxBitrate*s}},_t=e=>[e.msid,e.mediaType].join("_"),mt=e=>{const t=e.split("_");return{mediaType:parseInt(t.pop()),tag:t.pop(),userId:t.join("_")}},ft=(e,t)=>[e,t].join("_"),vt=e=>e.map((e=>Object.assign({},e))),gt=(e,t,r=!1)=>{e=e.slice();const i=[],n=[],s=[];return t.forEach((t=>{const n=_t(t);let o=e.findIndex((e=>_t(e)===n));if(r&&(o=e.findIndex((e=>e.uri===t.uri))),-1===o)return void i.push(t);const a=e[o];a.uri!==t.uri?i.push(t):a.state!==t.state&&s.push(t),e.splice(o,1)})),n.push(...e),{publishedList:i,unpublishedList:n,modifiedList:s}},Rt=()=>{let e="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}));return e=e.replace(/-/g,"")+"0",e=parseInt(e,16),e=(e=>{const t="0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ+/".split(""),r=t.length+1;let i=+e;const n=[];do{const e=i%r;i=(i-e)/r,n.unshift(t[e])}while(i);return n.join("")})(e),e.length>22&&(e=e.slice(0,22)),e},St=e=>{const[t,r]=e.split("_").map((e=>parseInt(e.replace(/[^\d]/g,""))));return{width:t,height:r}},Tt=e=>!!Be[e],Ct=e=>!!Ve[e],Et=e=>parseInt(e.replace("FPS_","")),yt=(()=>{const{browser:e,version:t,supportsUnifiedPlan:r}=je.browserDetails;return{browser:e,version:t,supportsUnifiedPlan:!1!==r}})();function It(){return"captureStream"in HTMLMediaElement.prototype||"mozCaptureStream"in HTMLMediaElement.prototype}function kt(){return"mediaDevices"in navigator&&"getDisplayMedia"in navigator.mediaDevices}const bt=e=>"[object Null]"===Object.prototype.toString.call(e),Pt=e=>1===e.type,Ot=e=>{const t={},r=Object.keys(e.users);return r.length&&r.forEach((r=>{const i=[],n=e.users[r];if(n.uris)try{i.push(...JSON.parse(n.uris))}catch(e){S.warn(`invalid user data -> userId: ${r}, userData: ${n}`)}t[r]=i})),t};var Lt,Dt;!function(e){e.PUBLISH="RCRTC:PublishResource",e.UNPUBLISH="RCRTC:UnpublishResource",e.MODIFY="RCRTC:ModifyResource",e.TOTAL_CONTENT_RESOURCE="RCRTC:TotalContentResources",e.STATE="RCRTC:state",e.ROOM_NOTIFY="RCRTC:RoomNtf",e.USER_NOTIFY="RCRTC:UserNtf",e.KICK="RCRTC:kick"}(Lt||(Lt={})),function(e){e.SUCCESS="Success",e.FAIL="Fail"}(Dt||(Dt={}));class Nt{constructor(e,t,r,i=1e4){this._roomId=e,this._roomMode=t,this._context=r,this._gap=i,this._latestTimestamp=Date.now(),this._timer=null}start(){return R(this,void 0,void 0,(function*(){this._timer||(this._timer=setInterval(this._loop.bind(this),this._gap))}))}_loop(){var e,t,r;return R(this,void 0,void 0,(function*(){const n=yield new Promise((e=>{this._context.rtcPing(this._roomId,this._roomMode).then(e).catch((t=>{S.error(`rtcping receive unknown error -> ${t}`),e(i.UNKNOWN)})),setTimeout(e,1e4,i.TIMEOUT)})),s=Date.now();if(n===i.SUCCESS)return this._latestTimestamp=s,void(null===(e=this.onPingResult)||void 0===e||e.call(this,Dt.SUCCESS));null===(t=this.onPingResult)||void 0===t||t.call(this,Dt.FAIL),S.warn(`rtcping failed -> code: ${n}`),(40003===n||s-this._latestTimestamp>6e4)&&(this.stop(),null===(r=this.onFailed)||void 0===r||r.call(this,40003===n))}))}stop(){this._timer&&(clearInterval(this._timer),this._timer=null)}}var At;!function(e){e[e.NORMAL=1]="NORMAL",e[e.TINY=2]="TINY"}(At||(At={}));const Mt=(e,t)=>Math.round(8*t/e),xt=(e,t=2)=>{const r=10**t;return Math.round(e*r)/r},wt=(e,t=2)=>{e>1&&(e/=32767);const r=10**t;return Math.ceil(e*r)},Ut=(e,t,r,i)=>{if(0===t)return 0;if(!r||!i)return xt(e/t,3);const n=t-i;if(0===n)return 0;const s=e-r;return s<0||n<0?0:xt(s/n,3)},$t=e=>{const{jitter:t,rtt:r,packetsLostRate:i}=e;return!bt(t)||!bt(r)||0!==i};class jt{constructor(e,t){this._rtcPeerConn=e,this._sdpSemantics=t,this._latestPacketsSent={},this._latestBytesSent={},this._latestBytesRecv={},this._latestPacketsRecv={}}updateBytesSent(e,t,r){let i,n;if(this._latestBytesSent[e]&&t<this._latestBytesSent[e].bytesSent&&this.clearLatestpacketsSent([e]),this._latestBytesSent[e]){const{bytesSent:s,timestamp:o}=this._latestBytesSent[e];i=t-s,n=r-o,this._latestBytesSent[e]={bytesSent:t,timestamp:r}}else i=t,n=1e3,this._latestBytesSent[e]={bytesSent:t,timestamp:r};return Mt(n,i)}updateBytesRecv(e,t,r){let i,n;if(this._latestBytesRecv[e]&&t<this._latestBytesRecv[e].bytesRecv&&this.clearLatestPacketsRecv([e]),this._latestBytesRecv[e]){const{bytesRecv:s,timestamp:o}=this._latestBytesRecv[e];i=t-s,n=r-o,this._latestBytesRecv[e]={bytesRecv:t,timestamp:r}}else i=t,n=1e3,this._latestBytesRecv[e]={bytesRecv:t,timestamp:r};return Mt(n,i)}updateSenderPacketsLost(e,t,r){let i;if(Object.prototype.hasOwnProperty.call(this._latestPacketsSent[e],"packetsSent")){const{packetsLost:n,packetsSent:s}=this._latestPacketsSent[e];i=Ut(t,r,n,s),this._latestPacketsSent[e].packetsLost=t,this._latestPacketsSent[e].packetsSent=n===t?s:r}else i=Ut(t,r),this._latestPacketsSent[e].packetsLost=t,this._latestPacketsSent[e].packetsSent=r;return i}updateReceiverPacketsLost(e,t,r){let i;if(this._latestPacketsRecv[e]){const{packetsLost:n,packetsRecv:s}=this._latestPacketsRecv[e];i=Ut(t,r+t,n,s+n)}else i=Ut(t,r);return this._latestPacketsRecv[e]={packetsLost:t,packetsRecv:r},i}clearLatestpacketsSent(e){e.forEach((e=>{if(parseInt(e.split("_").pop())===Fe.VIDEO_ONLY){const t=`${e}_tiny`;delete this._latestPacketsSent[t],delete this._latestBytesSent[t]}delete this._latestPacketsSent[e],delete this._latestBytesSent[e]}))}clearLatestPacketsRecv(e){e.forEach((e=>{delete this._latestPacketsRecv[e],delete this._latestBytesRecv[e]}))}parseRTCStatsReport(e){const t=e.keys(),r={};let i=t.next();for(;!i.done;){const n=i.value,s=e.get(n);/^RTCCodec_/.test(n)||(r[n]=s),i=t.next()}return r}formatRCRTCStateReport(e){return{senders:[],receivers:[]}}getAudioLevelList(e){return[]}getResourceIdByParseSdp(e){var t,r;const i=e.ssrc,n=e.kind||e.mediaType,s=null===(t=this._rtcPeerConn.currentLocalDescription)||void 0===t?void 0:t.sdp,o=null===(r=this._rtcPeerConn.currentRemoteDescription)||void 0===r?void 0:r.sdp;let a;a="unified-plan"===this._sdpSemantics?new RegExp("a=msid:(.*?) "):new RegExp(`a=ssrc:${i} msid:(.*?) `);const c=null==s?void 0:s.split("\r\nm="),d=null==c?void 0:c.filter((e=>e.includes(`a=ssrc:${i}`)))[0],u=null==d?void 0:d.match(a);let l=u?u[1]:"";if(l)return`${l}_${"video"===n?1:0}`;const h=null==o?void 0:o.split("\r\nm="),p=null==h?void 0:h.filter((e=>e.includes(`a=ssrc:${i}`)))[0],_=null==p?void 0:p.match(a);return l=_?_[1]:"",`${l}_${"video"===n?1:0}`}isValidSender(e){var t;const r=null===(t=this._rtcPeerConn.currentLocalDescription)||void 0===t?void 0:t.sdp,{ssrc:i}=e;return!(null==r?void 0:r.split("\r\nm=").some((e=>e.includes(i)&&e.includes("a=inactive"))))}isValidReceiver(e){var t;const r=null===(t=this._rtcPeerConn.currentRemoteDescription)||void 0===t?void 0:t.sdp,{ssrc:i}=e;return!(null==r?void 0:r.split("\r\nm=").some((e=>e.includes(i)&&e.includes("a=inactive"))))}}class Vt extends jt{formatRCRTCStateReport(e){const t={senders:[],receivers:[]},r=Math.floor(e.RTCPeerConnection.timestamp);t.timestamp=r;const i=Object.keys(e);let n=0,s=0;i.filter((e=>/^RTCOutboundRTP(Video|Audio)Stream_/.test(e))).forEach((i=>{const o=e[i];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(o))return;const{id:a,kind:c,transportId:d,mediaSourceId:u,remoteId:l,packetsSent:h,bytesSent:p,trackId:_,encoderImplementation:m,pliCount:f,nackCount:v,firCount:g}=o;if(!_)return;let{framesPerSecond:R,frameWidth:S,frameHeight:T}=o;"video"!==c||S||T||R||(S=e[_].frameWidth,T=e[_].frameHeight,R=u?e[u].framesPerSecond:null);const C=e[l];let E=null,y=null,I=0;C&&(E=C.jitter,y=C.roundTripTime,I=C.packetsLost),n+=I;const k=this.getResourceIdByParseSdp(o),b=u?e[u].audioLevel:e[_].audioLevel;let P=null;!this._latestPacketsSent[k]&&(this._latestPacketsSent[k]={}),C?P=this.updateSenderPacketsLost(k,I,h):this._latestPacketsSent[k].crtPacketsSent=h;let O=this.updateBytesSent(k,p,r);O<0&&(O=0),s+=O,t.senders.push({id:a,trackId:k,kind:c,packetsLostRate:P,remoteResource:!1,audioLevel:b||0===b?wt(b):null,frameWidth:S,frameHeight:T,frameRate:R,bitrate:O,jitter:E?Math.round(1e3*E):E,rtt:y,encoderImplementation:m,pliCount:f,nackCount:v,googFirsSent:-1,samplingRate:-1,googRenderDelayMs:-1,trackState:-1})}));i.filter((e=>/RTCRemoteInboundRtp(Video|Audio)Stream_/.test(e))).forEach((r=>{const{localId:i,jitter:n,roundTripTime:s,packetsLost:o}=e[r],a=t.senders.filter((e=>e.id===i))[0];if(a&&!$t(a)){const t=this.getResourceIdByParseSdp(e[a.id]);a.jitter=Math.round(1e3*n),a.rtt=s;const r=this._latestPacketsSent[t].crtPacketsSent;a.packetsLostRate=this.updateSenderPacketsLost(t,o,r)}}));let o=0;i.filter((e=>/^RTCInboundRTP(Video|Audio)Stream_/.test(e))).forEach((i=>{const s=e[i];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(s))return;const{trackId:a,packetsLost:c,packetsReceived:d,jitter:u,bytesReceived:l,framesPerSecond:h,kind:p,codecImplementationName:_,nackCount:m,pliCount:f}=s;if(!a)return;let{frameWidth:v,frameHeight:g,audioLevel:R}=s;"video"===p?v||g||(v=e[a].frameWidth,g=e[a].frameHeight):R||(R=e[a].audioLevel),n+=c;const S=this.getResourceIdByParseSdp(s),T=this.updateReceiverPacketsLost(S,c,d);let C=this.updateBytesRecv(S,l,r);C<0&&(C=0),o+=C,t.receivers.push({trackId:S,kind:p,packetsLostRate:T,remoteResource:!0,audioLevel:R||0===R?wt(R):null,frameWidth:v,frameHeight:g,frameRate:h,bitrate:C,jitter:u?Math.round(1e3*u):0,codecImplementationName:_,nackCount:m,pliCount:f,rtt:null,samplingRate:-1,googFirsReceived:-1,googRenderDelayMs:-1,trackState:-1})}));const a=i.filter((e=>/^RTCTransport_/.test(e)))[0];if(a){const r=e[a],{selectedCandidatePairId:i}=r;if(i){const r=e[i],{availableOutgoingBitrate:a,availableIncomingBitrate:c,currentRoundTripTime:d,localCandidateId:u,remoteCandidateId:l}=r,h=e[u],{ip:p,port:_,networkType:m}=h,f=e[l],{ip:v,port:g,protocol:R}=f;t.iceCandidatePair={IP:p,port:_,networkType:m,remoteIP:v,remotePort:g,protocol:R,bitrateRecv:o,bitrateSend:s,rtt:1e3*d,availableOutgoingBitrate:a,availableIncomingBitrate:c,totalPacketsLost:n},t.receivers.forEach((e=>{e.rtt=d}))}}return t}getAudioLevelList(e){const t=[],r=Object.keys(e);r.filter((e=>/^RTCOutboundRTPAudioStream_/.test(e))).forEach((r=>{var i;const n=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(n))return;const{mediaSourceId:s,trackId:o}=n,a=this.getResourceIdByParseSdp(n),c=s&&e[s]?e[s].audioLevel:(null===(i=e[o])||void 0===i?void 0:i.audioLevel)||null;t.push({trackId:a,audioLevel:c||0===c?wt(c):null})}));return r.filter((e=>/^RTCInboundRTPAudioStream_/.test(e))).forEach((r=>{const i=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(i))return;const{trackId:n}=i,s=i.audioLevel||e[n].audioLevel,o=this.getResourceIdByParseSdp(i);t.push({trackId:o,audioLevel:s||0===s?wt(s):null})})),t}}class Bt extends jt{formatRCRTCStateReport(e){const t=+new Date,r={senders:[],receivers:[],timestamp:t};let i=0,n=0,s=0;for(const o in e){const a=e[o],c=a.type;if("outbound-rtp"===c){if("unified-plan"===this._sdpSemantics&&!this.isValidSender(a))continue;const{id:s,kind:o,bytesSent:c,packetsSent:d,bitrateMean:u,framerateMean:l,nackCount:h,pliCount:p,remoteId:_}=a,{jitter:m,roundTripTime:f,packetsLost:v}=_?e[_]:{jitter:null,roundTripTime:null,packetsLost:0},g=this.getResourceIdByParseSdp(a);i+=v;let R=null;!this._latestPacketsSent[g]&&(this._latestPacketsSent[g]={}),_?R=this.updateSenderPacketsLost(g,v,d):this._latestPacketsSent[g].crtPacketsSent=d;let S=0;"video"===o?u&&(S=Math.floor(u/1e3)):S=this.updateBytesSent(g,c,t),S<0&&(S=0),n+=S,r.senders.push({trackId:g,kind:o,packetsLostRate:R,remoteResource:!1,audioLevel:null,frameWidth:null,frameHeight:null,frameRate:Math.floor(l),bitrate:S,jitter:m?Math.round(1e3*m):null,rtt:f,encoderImplementation:null,pliCount:p,nackCount:h,googFirsSent:-1,samplingRate:-1,googRenderDelayMs:-1,trackState:-1})}if("remote-inbound-rtp"===c){const{localId:t}=a,i=this.getResourceIdByParseSdp(e[t]),n=r.senders.filter((e=>e.trackId===i))[0];n&&$t(n)&&(n.jitter=Math.round(1e3*a.jitter),n.rtt=a.rtt,n.packetsLostRate=this.updateSenderPacketsLost(i,a.packetsLost,this._latestPacketsSent[i].crtPacketsSent))}if("inbound-rtp"===c){if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(a))continue;const{id:e,packetsLost:n,bytesReceived:o,packetsReceived:c,jitter:d,framerateMean:u,kind:l,bitrateMean:h,nackCount:p,pliCount:_}=a,m=this.getResourceIdByParseSdp(a);i+=n;const f=this.updateReceiverPacketsLost(m,n,c);let v=0;"video"===l?h&&(v=Math.floor(h/1e3)):v=this.updateBytesRecv(m,o,t),v<0&&(v=0),s+=v,r.receivers.push({trackId:m,kind:l,packetsLostRate:f,remoteResource:!0,audioLevel:null,frameWidth:null,frameHeight:null,frameRate:Math.floor(u),bitrate:v,jitter:d?Math.round(1e3*d):null,codecImplementationName:null,nackCount:p,pliCount:_,rtt:null,samplingRate:-1,googFirsReceived:-1,googRenderDelayMs:-1,trackState:-1})}if("candidate-pair"===c&&"succeeded"===a.state){const t=e[a.localCandidateId],{address:o,port:c}=t,d=e[a.remoteCandidateId],{address:u,port:l,protocol:h}=d;r.iceCandidatePair={IP:o,port:c,networkType:null,remoteIP:u,remotePort:l,protocol:h,bitrateRecv:s,bitrateSend:n,rtt:null,availableOutgoingBitrate:null,availableIncomingBitrate:null,totalPacketsLost:i}}}return r.iceCandidatePair&&(r.iceCandidatePair.bitrateSend=n),r.iceCandidatePair&&(r.iceCandidatePair.bitrateRecv=s),r}getAudioLevelList(e){const t=[];for(const r in e){const i=e[r],n=i.type;if("outbound-rtp"===n){if("unified-plan"===this._sdpSemantics&&!this.isValidSender(i))continue;const{kind:e}=i;if("video"===e)continue;const r=this.getResourceIdByParseSdp(i);t.push({trackId:r,audioLevel:null})}if("inbound-rtp"===n){if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(i))continue;const{kind:e}=i;if("video"===e)continue;const r=this.getResourceIdByParseSdp(i);t.push({trackId:r,audioLevel:null})}}return t}}class Ft extends jt{formatRCRTCStateReport(e){const t={senders:[],receivers:[]},r=Math.floor(e.RTCPeerConnection.timestamp);t.timestamp=r;const i=Object.keys(e);let n=0,s=0;i.filter((e=>/^RTCOutboundRTP(Video|Audio)Stream_/.test(e))).forEach((i=>{const n=e[i];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(n))return;const o=this.getResourceIdByParseSdp(n),{mediaType:a,transportId:c,remoteId:d,packetsSent:u,bytesSent:l,trackId:h,encoderImplementation:p,pliCount:_,nackCount:m,firCount:f}=n;if(!h)return;const{audioLevel:v,frameHeight:g,frameWidth:R}=e[h];let S=this.updateBytesSent(o,l,r);S<0&&(S=0),s+=S,t.senders.push({trackId:o,kind:a,packetsLostRate:null,remoteResource:!1,audioLevel:v||0===v?wt(v):null,frameWidth:R,frameHeight:g,frameRate:null,bitrate:S,jitter:null,rtt:null,encoderImplementation:p,pliCount:_,nackCount:m,googFirsSent:-1,samplingRate:-1,googRenderDelayMs:-1,trackState:-1})}));let o=0;i.filter((e=>/^RTCInboundRTP(Video|Audio)Stream_/.test(e))).forEach((i=>{const s=e[i];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(s))return;const{trackId:a,packetsLost:c,packetsReceived:d,jitter:u,bytesReceived:l,mediaType:h,nackCount:p,pliCount:_}=s,m=this.getResourceIdByParseSdp(s);if(!a)return;const{frameHeight:f,frameWidth:v,audioLevel:g}=e[a];n+=c;const R=this.updateReceiverPacketsLost(m,c,d);let S=this.updateBytesRecv(m,l,r);S<0&&(S=0),o+=S,t.receivers.push({trackId:m,kind:h,packetsLostRate:R,remoteResource:!0,audioLevel:g||0===g?wt(g):null,frameWidth:v,frameHeight:f,frameRate:null,bitrate:S,jitter:u,codecImplementationName:null,nackCount:p,pliCount:_,rtt:null,samplingRate:-1,googFirsReceived:-1,googRenderDelayMs:-1,trackState:-1})}));const a=i.filter((e=>/^RTCTransport_/.test(e)))[0];if(a){const r=e[a],{selectedCandidatePairId:i}=r;if(i){const r=e[i],{availableOutgoingBitrate:a,availableIncomingBitrate:c,currentRoundTripTime:d,localCandidateId:u,remoteCandidateId:l}=r,h=e[u],{address:p,port:_}=h,m=e[l],{address:f,port:v,protocol:g}=m;t.iceCandidatePair={IP:p||null,port:_,networkType:null,remoteIP:f,remotePort:v,protocol:g,bitrateRecv:o,bitrateSend:s,rtt:1e3*d,availableOutgoingBitrate:a,availableIncomingBitrate:c,totalPacketsLost:n},t.receivers.forEach((e=>{e.rtt=d}))}}return t}getAudioLevelList(e){const t=[],r=Object.keys(e);r.filter((e=>/^RTCOutboundRTP(Video|Audio)Stream_/.test(e))).forEach((r=>{const i=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(i))return;const{trackId:n,mediaType:s}=i;if("video"===s)return;const o=this.getResourceIdByParseSdp(i),a=e[n];t.push({trackId:o,audioLevel:a||0===a?wt(a):null})}));return r.filter((e=>/^RTCInboundRTP(Video|Audio)Stream_/.test(e))).forEach((r=>{const i=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(i))return;const{trackId:n,mediaType:s}=i;if(!n||"video"===s)return;const{audioLevel:o}=e[n],a=this.getResourceIdByParseSdp(i);t.push({trackId:a,audioLevel:o||0===o?wt(o):null})})),t}}class Ht{constructor(e){this._peer=e,this._outboundStreams={}}static setSdpSemantics(e){const{browser:t,version:r,supportsUnifiedPlan:i}=yt;S.debug(`sdpSemantics, browser: ${t}, version: ${r}, supportsUnifiedPlan: ${i}`),i?/chrome/i.test(t)?this._sdpSemantics=r>92?"unified-plan":r<72?"plan-b":e:/firefox/i.test(t)?this._sdpSemantics="unified-plan":/safari/i.test(t)?this._sdpSemantics=r<12?"plan-b":"unified-plan":this._sdpSemantics="unified-plan":this._sdpSemantics="plan-b"}static getSdpSemantics(){return Ht._sdpSemantics}getOutboundVideoInfo(){const e=[];for(const t in this._outboundStreams){const r=this._outboundStreams[t].getVideoTracks()[0];if(!r)continue;const i=/_tiny$/.test(t),{width:n,height:s}=ht(r);e.push({trackId:r.id,simulcast:i?At.TINY:At.NORMAL,resolution:`${n}x${s}`})}return e}setRemoteAnswer(e){return R(this,void 0,void 0,(function*(){e=e.replace(/\s+\r\n/g,"\r\n");try{yield this._peer.setRemoteDescription({type:"answer",sdp:e})}catch(e){return S.error(e),T.SET_REMOTE_DESCRIPTION_FAILED}return T.SUCCESS}))}getStatParsr(e,t){return/chrome/i.test(yt.browser)?new Vt(e,t):/Firefox/i.test(yt.browser)?new Bt(e,t):/Safari/i.test(yt.browser)?new Ft(e,t):null}}class Gt extends Ht{constructor(){super(...arguments),this.senders={},this._localTracks=[]}addLocalTrack(e){this._localTracks.includes(e)||this._localTracks.push(e);const t=e.getStreamId(),r=e.__innerGetMediaStreamTrack(),i=this._outboundStreams[t]||(this._outboundStreams[t]=new MediaStream);i.getTracks().forEach((e=>{e.kind===r.kind&&i.removeTrack(e)})),i.addTrack(r);const n=e.getTrackId(),s=this.senders[n];s?s.replaceTrack(r):this.senders[n]=this._peer.addTrack(r,i)}removeLocalTrack(e){const t=this._localTracks.findIndex((t=>t===e));t>=0&&this._localTracks.splice(t,1);const r=e.getTrackId(),i=this.senders[r];i&&(i.replaceTrack(null),this._peer.removeTrack(i),delete this.senders[r])}updateSubRemoteTracks(e){}updateRecvTransceiverMap(e,t){}setBitrate(e,t,r){this._maxBitrate=e,this._minBitrate=t,this._startBitrate=r||.7*e}createOffer(e){return R(this,void 0,void 0,(function*(){const t=yield this._peer.createOffer({iceRestart:e,offerToReceiveAudio:!0,offerToReceiveVideo:!0});for(const e in this._outboundStreams){const r=this._outboundStreams[e].id;t.sdp=t.sdp.replace(new RegExp(r,"g"),e)}return yield this._peer.setLocalDescription(t),{type:"offer",semantics:"plan-b",sdp:t.sdp}}))}setRemoteAnswer(e){let t=0,r=0;this._localTracks.forEach((e=>{const{min:i,max:n}=e.getBitrate();r+=i,t+=n})),t=this._maxBitrate&&this._maxBitrate>0?Math.min(t,this._maxBitrate):t,r=this._minBitrate&&this._minBitrate>0?Math.max(r,this._minBitrate):r;const i=this._startBitrate||Math.round(.7*t),n=`b=AS:${t}`;e=e.replace(/[\r\n]+m=video[^\r\n]+/,(e=>`${e}\r\n${n}`));const s=[`;x-google-min-bitrate=${r}`,`;x-google-max-bitrate=${t}`,`;x-google-start-bitrate=${i}`].join("");return e=e.replace(/[\r\n]+[^\r\n]+profile-level-id[^\r\n]+/g,(e=>e+s)),super.setRemoteAnswer(e)}}class Jt extends Ht{constructor(){super(...arguments),this._sendTransceiver={},this._localTracks={},this._recvAudio=[],this._recvVideo=[],this._recvTransceiver={},this._subedTracks=[]}setBitrate(e,t,r){S.warn("the interface named `setBitrate` is invalid while sdpSemantics value is `unified-plan`")}addLocalTrack(e){const t=e.getTrackId(),r=e.getStreamId(),i=e.__innerGetMediaStreamTrack();this._localTracks[t]=e;const n=this._outboundStreams[r]||(this._outboundStreams[r]=new MediaStream);n.getTracks().forEach((e=>{e.kind===i.kind&&n.removeTrack(e)})),n.addTrack(i);const s=this._sendTransceiver[t];s?(s.sender.replaceTrack(i),s.direction="sendonly"):this._sendTransceiver[t]=this._peer.addTransceiver(i,{direction:"sendonly",streams:[n]})}removeLocalTrack(e){const t=e.getTrackId(),r=e.getStreamId();e.__innerGetMediaStreamTrack(),delete this._localTracks[t];const i=this._sendTransceiver[t];if(!i)return;i.direction="inactive",this._peer.removeTrack(i.sender),i.sender.replaceTrack(null);const n=this._outboundStreams[r];(e.isAudioTrack()?n.getAudioTracks():n.getVideoTracks()).forEach((e=>n.removeTrack(e)));const s=this._sendTransceiver[`${t}_tiny`];if(!s||"inactive"===s.direction)return;s.direction="inactive";const o=s.sender,a=o.track;this._peer.removeTrack(o),o.replaceTrack(null);this._outboundStreams[`${r}_tiny`].removeTrack(a),a.stop()}updateRecvTransceiverMap(e,t){const{mediaType:r}=mt(e);this._recvTransceiver[e]=t;const i=r===Fe.AUDIO_ONLY?this._recvAudio:this._recvVideo,n=i.findIndex((e=>e===t));n>=0&&i.splice(n,1)}updateSubRemoteTracks(e){const t=e.slice(),r=this._subedTracks.slice();this._subedTracks=e.slice();for(let e=t.length-1;e>=0;e-=1){const i=t[e],n=r.findIndex((e=>e===i));n>=0&&(t.splice(e,1),r.splice(n,1))}r.length&&r.forEach((e=>{const t=e.getTrackId();e.__innerSetMediaStreamTrack(void 0);const r=this._recvTransceiver[t];r&&(r.direction="inactive")}));const i={audio:0,video:0};t.length&&t.forEach((e=>{const t=e.isAudioTrack()?"audio":"video",r=this._recvTransceiver[e.getTrackId()];r?r.direction="recvonly":i[t]+=1}));for(let e=this._recvAudio.length;e<i.audio;e+=1)this._recvAudio.push(this._peer.addTransceiver("audio",{direction:"recvonly"}));for(let e=this._recvVideo.length;e<i.video;e+=1)this._recvVideo.push(this._peer.addTransceiver("video",{direction:"recvonly"}))}createOffer(e){return R(this,void 0,void 0,(function*(){const t=yield this._peer.createOffer({iceRestart:e});let r=t.sdp;for(const e in this._outboundStreams){const t=this._outboundStreams[e].id;r=r.replace(new RegExp(t,"g"),e)}return r=(e=>e.split(/\r\n(?=m=)/).map((e=>(e=>/a=(recvonly|inactive)/.test(e)?e.replace(/\r\na=(ssrc|msid)[^\r\n]+/g,""):e)(e))).join("\r\n"))(r),r=r.replace(/a=ice-options:trickle/g,"a=ice-options:trickle\r\na=ice-options:renomination"),t.sdp=r,yield this._peer.setLocalDescription(t),{type:"offer",semantics:"unified-plan",sdp:r}}))}setRemoteAnswer(e){e=e.split(/\r\n(?=m=)/).map((e=>{var t;const r=e.match(/a=mid:[^\s]+/);if(!r)return e;const i=r[0].replace("a=mid:","");let n="";for(const e in this._sendTransceiver){if(this._sendTransceiver[e].mid===i){n=e;break}}if(!n)return e;const s=null===(t=this._localTracks[n])||void 0===t?void 0:t.getBitrate();if(!s)return e;const{max:o,min:a}=s,c=o&&o>0?s.start||.7*o:0,d=[];if(o&&o>0&&d.push(`;x-google-max-bitrate=${o}`),a&&a>0&&d.push(`;x-google-min-bitrate=${a}`),c>0&&d.push(`;x-google-start-bitrate=${c}`),0===d.length)return e;const u=d.join("");return e.replace(/[\r\n]+[^\r\n]+profile-level-id[^\r\n]+/g,(e=>e+u))})).join("\r\n");const t=/[\r\n]+\r\n[\r\n]+/g;return t.test(e)&&(S.warn(`answer sdp invalid -> ${JSON.stringify(e)}`),e=e.replace(t,"\r\n")),super.setRemoteAnswer(e)}}class Wt extends t{constructor(e,t){super(),this._reTryExchange=e,this._polarisReport=t,this.pubLocalTracks={},this._reTryExchangeTimer=null,this._reportStatsTimer=null,this._reportListener=null;const r=Ht.getSdpSemantics(),i=this._rtcPeerConn=new RTCPeerConnection({sdpSemantics:r});this._sdpStrategy="plan-b"===r?new Gt(i):new Jt(i),this._rtcPeerConn.oniceconnectionstatechange=this._onICEConnectionStateChange.bind(this),this._rtcPeerConn.onconnectionstatechange=this._onConnectionStateChange.bind(this),this._rtcPeerConn.ontrack=this._onTrackReady.bind(this),this.reportParser=this._sdpStrategy.getStatParsr(this._rtcPeerConn,r)}getLocalTracks(){return Object.values(this.pubLocalTracks)}_onConnectionStateChange(){S.info(`onconnectionstatechange -> ${this._rtcPeerConn.connectionState}`)}_onICEConnectionStateChange(){var e,t;S.info(`oniceconnectionstatechange -> ${this._rtcPeerConn.iceConnectionState}`),"connected"===this._rtcPeerConn.iceConnectionState&&(this._reportStatsTimer&&clearInterval(this._reportStatsTimer),this._reportStatsTimer=setInterval(this._reportHandle.bind(this),1e3)),"failed"!==this._rtcPeerConn.iceConnectionState&&"disconnected"!==this._rtcPeerConn.iceConnectionState||(S.warn("iceconenction state is `failed`, exchange SDP to try again."),this._reTryExchange(),this._reTryExchangeTimer=setInterval(this._reTryExchange,15e3));try{null===(t=null===(e=this._reportListener)||void 0===e?void 0:e.onICEConnectionStateChange)||void 0===t||t.call(e,this._rtcPeerConn.iceConnectionState)}catch(e){S.error("onICEConnectionStateChange error",e)}}_onTrackReady(e){if(!e.streams.length)return;const t=[e.streams[0].id,"audio"===e.receiver.track.kind?Fe.AUDIO_ONLY:Fe.VIDEO_ONLY].join("_");this._updateRecvTransceiverMap(t,e.transceiver),this.emit(Wt.__INNER_EVENT_TRACK_READY__,e)}setBitrate(e,t,r){return R(this,void 0,void 0,(function*(){this._sdpStrategy.setBitrate(e,t,r)}))}createOffer(e){return R(this,void 0,void 0,(function*(){const t=yield this._sdpStrategy.createOffer(e);return S.debug(`offer -> ${JSON.stringify(t.sdp)}`),t}))}setRemoteAnswer(e){return R(this,void 0,void 0,(function*(){return S.debug(`answer -> ${JSON.stringify(e)}`),this._sdpStrategy.setRemoteAnswer(e)}))}getLocalTrack(e){return this.pubLocalTracks[e]||null}addLocalTrack(e){this.pubLocalTracks[e.getTrackId()]=e,this._sdpStrategy.addLocalTrack(e),e.off(qe.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.off(qe.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this),e.on(qe.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.on(qe.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this)}removeLocalTrackById(e){const t=this.getLocalTrack(e);t&&this.removeLocalTrack(t)}removeAllLocalTrack(){Object.keys(this.pubLocalTracks).forEach((e=>{/_tiny$/.test(e)||this.removeLocalTrackById(e)}))}removeLocalTrack(e){const t=e.getTrackId();delete this.pubLocalTracks[t],this._sdpStrategy.removeLocalTrack(e),e.__innerSetPublished(!1),e.off(qe.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.off(qe.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this);const r=`${t}_tiny`,i=this.getLocalTrack(r);i&&(this._sdpStrategy.removeLocalTrack(i),delete this.pubLocalTracks[r],i.destroy())}_updateRecvTransceiverMap(e,t){this._sdpStrategy.updateRecvTransceiverMap(e,t)}updateSubRemoteTracks(e){this._sdpStrategy.updateSubRemoteTracks(e)}getOutboundVideoInfo(){return this._sdpStrategy.getOutboundVideoInfo()}_onLocalTrackMuted(e){const t=this.getLocalTrack(`${e.getTrackId()}_tiny`);t&&(t.__innerGetMediaStreamTrack().enabled=!e.isLocalMuted()),this.emit(qe.__INNER_EVENT_MUTED_CHANGE__,e)}_onLocalTrackDestroied(e){this.emit(qe.__INNER_EVENT_DESTROY__,e)}registerReportListener(e){this._reportListener=e}_createRCRTCStateReport(e){const{timestamp:t,iceCandidatePair:r,senders:i,receivers:n}=JSON.parse(JSON.stringify(e));null==r||delete r.totalPacketsLost;for(const e in r)bt(r[e])&&delete r[e];return{timestamp:t,iceCandidatePair:r,senders:i.map((e=>{const t={};return e.trackId&&(t.trackId=e.trackId),e.kind&&(t.kind=e.kind),(e.packetsLostRate||0===e.packetsLostRate)&&(t.packetsLostRate=e.packetsLostRate),t.remoteResource=e.remoteResource,(e.audioLevel||0===e.audioLevel)&&(t.audioLevel=e.audioLevel),e.frameWidth&&(t.frameWidth=e.frameWidth),e.frameHeight&&(t.frameHeight=e.frameHeight),e.frameRate&&(t.frameRate=e.frameRate),(e.bitrate||0===e.bitrate)&&(t.bitrate=e.bitrate),e.jitter&&(t.jitter=e.jitter),t})),receivers:n.map((e=>{const t={};return e.trackId&&(t.trackId=e.trackId),e.kind&&(t.kind=e.kind),(e.packetsLostRate||0===e.packetsLostRate)&&(t.packetsLostRate=e.packetsLostRate),t.remoteResource=e.remoteResource,(e.audioLevel||0===e.audioLevel)&&(t.audioLevel=e.audioLevel),e.frameWidth&&(t.frameWidth=e.frameWidth),e.frameHeight&&(t.frameHeight=e.frameHeight),e.frameRate&&(t.frameRate=e.frameRate),(e.bitrate||0===e.bitrate)&&(t.bitrate=e.bitrate),e.jitter&&(t.jitter=e.jitter),t}))}}_getStatsData(){var e,t;return R(this,void 0,void 0,(function*(){const r=yield this._rtcPeerConn.getStats(),i=null===(e=this.reportParser)||void 0===e?void 0:e.parseRTCStatsReport(r);return null===(t=this.reportParser)||void 0===t?void 0:t.formatRCRTCStateReport(i)}))}getAudioLevelReportData(){var e,t;return R(this,void 0,void 0,(function*(){const r=yield this._rtcPeerConn.getStats(),i=null===(e=this.reportParser)||void 0===e?void 0:e.parseRTCStatsReport(r);if(!i)return[];return null===(t=this.reportParser)||void 0===t?void 0:t.getAudioLevelList(i)}))}_reportHandle(){var e,t,r;return R(this,void 0,void 0,(function*(){const i=yield this._getStatsData();if(!i)return;(i.senders.length||i.receivers.length)&&(null===(e=this._polarisReport)||void 0===e||e.sendR3R4Data(i));const n=this._createRCRTCStateReport(i);null===(r=null===(t=this._reportListener)||void 0===t?void 0:t.onStateReport)||void 0===r||r.call(t,n)}))}getRTCPeerConn(){return this._rtcPeerConn}destroy(){this.clear(),this.clearReTryExchangeTimer(),this._reportStatsTimer&&(clearInterval(this._reportStatsTimer),this._reportStatsTimer=null),this.registerReportListener(null),this._rtcPeerConn.close(),this.reportParser=null}clearReTryExchangeTimer(){clearInterval(this._reTryExchangeTimer),this._reTryExchangeTimer=null}}var Yt,Kt,qt,zt,Qt;Wt.__INNER_EVENT_TRACK_READY__="inner-track-ready",function(e){e[e.DISABLE=0]="DISABLE",e[e.ENABLE=1]="ENABLE"}(Yt||(Yt={})),function(e){e[e.MeetingOrAnchor=1]="MeetingOrAnchor",e[e.Audience=2]="Audience"}(Kt||(Kt={}));class Xt{constructor(e,t,r,i,n=Kt.MeetingOrAnchor){this._context=e,this._runtime=t,this._roomId=r,this._crtRTCRoom=i,this._userRole=n}_send(e){this._context.getConnectionStatus()===n.CONNECTED&&this._context.setRTCState(this._roomId,e)}_getClientID(){const e="uuid";let t=this._runtime.localStorage.getItem(e);return t||(t=Rt(),this._runtime.localStorage.setItem(e,t)),t}_getRealResourceId(e){let t=e;const r=e.indexOf("_tiny");return r>-1&&(t=e.slice(0,r)),t}_getPolarisTrackId(e){let t="";const r=e.split("_");if(e.includes("_tiny")){const e=r.pop(),i=parseInt(r.pop())===Fe.AUDIO_ONLY?"audio":"video",n=r.pop();t=[r.join("_"),n,e,i].join("_")}else{const e=parseInt(r.pop())===Fe.AUDIO_ONLY?"audio":"video",i=r.pop();t=[r.join("_"),i,e].join("_")}return t}sendR3R4Data(e){const{iceCandidatePair:t,senders:r,receivers:i}=e,n=(null==t?void 0:t.bitrateSend)||-1,s=(null==t?void 0:t.bitrateRecv)||-1,o=(null==t?void 0:t.networkType)||"unknown",a=(null==t?void 0:t.rtt)||-1,c=`${(null==t?void 0:t.IP)||-1}:${null==t?void 0:t.port}`,d=(null==t||t.remoteIP,null==t||t.remotePort,(null==t?void 0:t.availableIncomingBitrate)||-1),u=(null==t?void 0:t.availableOutgoingBitrate)||-1,l=(null==t?void 0:t.totalPacketsLost)||-1,h=this._context.getCurrentId();let p=`R3\t${n}\t-1\t-1\t-1\t${o}\t${a}\t${c}\t${d}\t${u}\t${l}\t${h}\r`,_=`R4\t${s}\t-1\t-1\t-1\t${o}\t${a}\t${c}\t${d}\t${u}\t${l}\t${h}\r`;const m=r.map((e=>{var t;const{trackId:r,audioLevel:i,samplingRate:n,bitrate:s,packetsLostRate:o,frameRate:a,frameWidth:c,frameHeight:d,googRenderDelayMs:u,jitter:l,nackCount:h,pliCount:p,rtt:_,googFirsSent:m,encoderImplementation:f}=e,v=this._getPolarisTrackId(r),g=this._getRealResourceId(r);return{trackId:v,googCodecName:f||String(-1),audioLevel:i||0===i?i:-1,bitrate:s||0===s?s:-1,packetsLostRate:o||0===o?o:-1,frameRate:a||-1,resolution:c&&d?`${c} * ${d}`:"-1",jitter:l||-1,nackCount:h||0===h?h:-1,pliCount:p||0===p?p:-1,rtt:_||-1,googFirsSent:m,samplingRate:n,googRenderDelayMs:u,encoderImplementation:f||String(-1),trackState:(null===(t=this._crtRTCRoom.getLocalTrack(g))||void 0===t?void 0:t.isLocalMuted())?Yt.DISABLE:Yt.ENABLE}})),f=i.filter((e=>!!e.trackId)).map((e=>{var t;const{trackId:r,audioLevel:i,samplingRate:n,bitrate:s,packetsLostRate:o,frameRate:a,frameWidth:c,frameHeight:d,googRenderDelayMs:u,jitter:l,nackCount:h,pliCount:p,rtt:_,googFirsReceived:m,codecImplementationName:f}=e,v=this._getPolarisTrackId(r),g=this._getRealResourceId(r);return{trackId:v,googCodecName:f||String(-1),audioLevel:i||0===i?i:-1,bitrate:s||0===s?s:-1,packetsLostRate:o||0===o?o:-1,frameRate:a||-1,resolution:c&&d?`${c} * ${d}`:"-1",jitter:l||-1,nackCount:h||0===h?h:-1,pliCount:p||0===p?p:-1,rtt:_||-1,googFirsReceived:m,samplingRate:n,googRenderDelayMs:u,codecImplementationName:f||String(-1),trackState:(null===(t=this._crtRTCRoom.getRemoteTrack(g))||void 0===t?void 0:t.isLocalMuted())?Yt.DISABLE:Yt.ENABLE}}));p+=m.map((e=>`${e.trackId}\t${e.googCodecName}\t${e.audioLevel}\t${e.samplingRate}\t${e.bitrate}\t${e.packetsLostRate}\t${e.frameRate}\t${e.resolution}\t${e.googRenderDelayMs}\t${e.jitter}\t${e.nackCount}\t${e.pliCount}\t${e.rtt}\t${e.googFirsSent}\t${e.encoderImplementation}\t${e.trackState}`)).join("\n"),e.senders.length&&this._send(p+`\r${this._userRole}`),_+=f.map((e=>`${e.trackId}\t${e.googCodecName}\t${e.audioLevel}\t${e.samplingRate}\t${e.bitrate}\t${e.packetsLostRate}\t${e.frameRate}\t${e.resolution}\t${e.googRenderDelayMs}\t${e.jitter}\t${e.nackCount}\t${e.pliCount}\t${e.rtt}\t${e.googFirsReceived}\t${e.codecImplementationName}\t${e.trackState}`)).join("\n"),e.receivers.length&&this._send(_+`\r${this._userRole}`)}sendR1(){const e=`R1\t5.2.4\t${this._context.getCoreVersion()}\tweb\t${navigator.platform}\t-1\t${yt.browser}\t${yt.version}\t${this._getClientID()}\t${this._userRole}`;this._send(e)}sendR2(e,t,r){const i=`R2\t${e}\t${t}\t${this._getClientID()}\r${r.join("\t")}\r${this._userRole}`;this._send(i)}}!function(e){e.PUBLISH="publish",e.SUBSCRIBE="subscribe"}(qt||(qt={})),function(e){e.BEGIN="begin",e.END="end"}(zt||(zt={}));class Zt{constructor(e){this._room=e,this._audioLevelChangeHandler=null,this._timer=null,this._pc=this._room.__getPC()}_audioLevelReport(){return R(this,void 0,void 0,(function*(){if("new"===this._pc.getRTCPeerConn().iceConnectionState||!this._audioLevelChangeHandler)return;const e=(yield this._pc.getAudioLevelReportData()).map((e=>{const{userId:t}=Ir.parseTrackId(e.trackId);return{track:this._room.getCrtUserId()===t?this._room.getLocalTrack(e.trackId):this._room.getRemoteTrack(e.trackId),audioLevel:e.audioLevel||0}})).filter((e=>e.track));this._audioLevelChangeHandler(e)}))}onAudioLevelChange(e,t){t<300||t>1e3?S.error('the valid range of onAudioLevelChange params "gap" is: > 300 && < 1000'):e?(this._audioLevelChangeHandler=e,this._timer=setInterval(this._audioLevelReport.bind(this),t)):this._audioLevelChangeHandler=null}clearAudioLevelReportTimer(){this._timer&&(clearInterval(this._timer),this._timer=null)}}!function(e){e[e.ANCHOR=1]="ANCHOR",e[e.AUDIENCE=2]="AUDIENCE"}(Qt||(Qt={}));const er=e=>e instanceof Ke?e.getTrackId():e.track.getTrackId();class tr{constructor(e,t,r,i,n,s,o,a,c){this._context=e,this._runtime=t,this._roomId=r,this._roomMode=n,this._service=s,this._initOptions=o,this._ntfClearRoomItem=a,this._remoteTracks={},this._subscribedList=[],this._destroyed=!1,this.msgTaskQueue=new E,this._appListener=null,this._token=i.token,this._sessionId=i.sessionId,this._roomResources=c?{}:Ot(i),this._initRemoteTracks();const d=this._context.getCurrentId(),u=this._roomResources[d]=this._roomResources[d]||[];S.debug(`room data -> ${JSON.stringify(this._roomResources)}`),u.length>0&&I((()=>this._unpublishPrev(u))),c&&this._afterChangedRole(i),this._pinger=new Nt(r,this._roomMode,e,this._initOptions.pingGap),this._pinger.onFailed=this._kickoff.bind(this),this._pinger.onPingResult=this._handlePingResult.bind(this),this._pinger.start(),this._polarisReport=new Xt(this._context,this._runtime,this._roomId,this),this._polarisReport.sendR1(),this._pc=new Wt(this._reTryExchange.bind(this),this._polarisReport),this._pc.on(Wt.__INNER_EVENT_TRACK_READY__,this._onTrackReady,this),this._pc.on(qe.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),this._pc.on(qe.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this)}_initRemoteTracks(){const e=this._context.getCurrentId();for(const t in this._roomResources){const r=this._roomResources[t];t!==e&&0!==r.length&&r.forEach((e=>{const t=_t(e),{tag:r,userId:i,mediaType:n}=mt(t),s=n===Fe.AUDIO_ONLY?new st(r,i):new ot(r,i);s.__innerSetRemoteMuted(0===e.state),this._remoteTracks[t]=s}))}}_handlePingResult(e){this._callAppListener("onPing",e)}setBitrate(e,t,i){S.warn("`RCAbstractRoom.setBitrate` will be deprecated, use `RCLocalTrack.setBitrate` instead."),s("max",e,(e=>r(e)&&e>Math.max(t||1,200)),!0),s("min",t,(t=>r(t)&&t>=1&&(!r(e)||t<e)),!0),s("start",i,(i=>r(i)&&i>t&&i<=e)),this._pc.setBitrate(e,t,i)}_onTrackReady(e){const t=e.streams[0].id,r=e.receiver.track,i=[t,"audio"===r.kind?Fe.AUDIO_ONLY:Fe.VIDEO_ONLY].join("_"),n=this._remoteTracks[i];n?(n.__innerSetMediaStreamTrack(r),this._callAppListener("onTrackReady",n)):S.warn(`cannot found remote track ${r.id}`)}_callAppListener(e,...t){var r;const i=null===(r=this._appListener)||void 0===r?void 0:r[e];if(i)try{i(...t)}catch(e){S.error(e)}}_onUserUnpublish(e){return R(this,void 0,void 0,(function*(){yield this.unsubscribe(e),e.forEach((e=>{e.__innerDestroy(),delete this._remoteTracks[e.getTrackId()]})),this._onTrackUnpublish(e)}))}_onTrackUnpublish(e){this._callAppListener("onTrackUnpublish",e)}_unpublishPrev(e){return R(this,void 0,void 0,(function*(){const t=e.slice();e.length=0,S.info(`unpublish uris prev login: ${JSON.stringify(t)}`);const r=yield this._context.setRTCTotalRes(this._roomId,at(Lt.UNPUBLISH,t),ct([]),Lt.TOTAL_CONTENT_RESOURCE,ct([]));r!==i.SUCCESS?S.error(`unpublish prev uris failed -> code: ${r}`):S.debug("unpublish uris prev login succeed")}))}__parseInnerMessage(e){const{targetId:t,conversationType:r}=e;if(r!==o.RTC_ROOM)return!1;if(t!==this._roomId)return!0;S.info(`recv inner msg -> message: ${JSON.stringify(e)} | roomid: ${this._roomId}`);const i=e.content;switch(e.messageType){case Lt.KICK:this._kickoff(!0,i);break;case Lt.STATE:this.msgTaskQueue.push((()=>this._stateHandle(i)));break;case Lt.MODIFY:case Lt.PUBLISH:case Lt.UNPUBLISH:case Lt.TOTAL_CONTENT_RESOURCE:this.msgTaskQueue.push((()=>this._resourceHandle(i,e.messageType,e.senderUserId)));break;case Lt.ROOM_NOTIFY:this._callAppListener("onRoomAttributeChange",e.messageType,e.content);break;case Lt.USER_NOTIFY:S.warn(`TODO: ${Lt.USER_NOTIFY}`);break;default:this._callAppListener("onMessageReceive",e.messageType,e.content,e.senderUserId,e.messageUId)}return!0}_kickoff(e,t){let r;S.warn(`onKickOff -> byServer: ${e}`),this._ntfClearRoomItem(),this._leaveHandle(!e),e&&((null==t?void 0:t.users)||[]).forEach((e=>{e.userId===this._context.getCurrentId()&&(r=e.type)})),this._callAppListener("onKickOff",e,r)}_rtcpeerClosed(){this._ntfClearRoomItem(),this._leaveHandle(!0),this._callAppListener("onRTCPeerConnectionCloseByException")}_resourceHandle(e,t,r){return R(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return void S.warn(`room has been destroyed. -> roomId: ${this._roomId}`);const{uris:i,ignore:n}=e;if(n||!i)return;const s=[],o=[],a=[];let c;const d=this._roomResources[r]||(this._roomResources[r]=[]);switch(t){case Lt.MODIFY:a.push(...i);break;case Lt.PUBLISH:s.push(...i);break;case Lt.UNPUBLISH:o.push(...i);break;case Lt.TOTAL_CONTENT_RESOURCE:c=gt(d,i),s.push(...c.publishedList),o.push(...c.unpublishedList),a.push(...c.modifiedList)}if(s.length>0){const e=d.map(_t),t=[],r=[];if(s.forEach((i=>{const n=_t(i),s=e.indexOf(n),{userId:o,tag:a,mediaType:c}=mt(n);s>-1?d[s]=i:d.push(i);let u=this._remoteTracks[n];u?u.isSubscribed()&&t.push(u):(u=c===Fe.AUDIO_ONLY?new st(a,o):new ot(a,o),this._remoteTracks[n]=u,r.push(u)),u.__innerSetRemoteMuted(0===i.state)})),t.length){const e=t.map((e=>e.getTrackId()));S.debug(`resub tracks -> ${JSON.stringify(e)}`);const{code:r}=yield I((()=>this.__subscribe(t,!0)));r!==T.SUCCESS&&S.error(`resub tracks failed -> code: ${r}, ids: ${JSON.stringify(e)}`)}this._onTrackPublish(r)}if(o.length>0){const e=o.map(_t);for(let t=d.length-1;t>=0;t-=1){const r=d[t];e.includes(_t(r))&&d.splice(t,1)}const t=o.map((e=>{const t=_t(e);return this._remoteTracks[t]}));yield this._onUserUnpublish(t)}if(a.length>0){const e=d.map(_t);for(let t=0;t<a.length;t+=1){const r=a[t],i=_t(r),n=e.indexOf(i);d[n].state=r.state;const s=this._remoteTracks[i];s.__innerSetRemoteMuted(0===r.state),s.isAudioTrack()?this._onAudioMuteChange(s):this._onVideoMuteChange(s)}}}))}_onTrackPublish(e){this._callAppListener("onTrackPublish",e)}_stateHandle(e){var t;return R(this,void 0,void 0,(function*(){const{users:r}=e;if(0===r.length)return;const i=[],n=[],s=[],o=[];r.forEach((e=>{0==+e.state?(S.debug(`user joined -> ${e.userId}`),this._roomResources[e.userId]||(e.switchRoleType?s.push(e.userId):i.push(e.userId)),this._roomResources[e.userId]=this._roomResources[e.userId]||[]):(S.debug(`user left -> ${e.userId}`),e.switchRoleType?o.push(e.userId):n.push(e.userId))}));const a=[...i,...s],c=[...n,...o];if(c.length){const e=[],t=[];c.forEach((r=>{e.push(...this.getRemoteTracksByUserId(r)),t.push(r)})),e.length&&(yield this.unsubscribe(e),e.forEach((e=>delete this._remoteTracks[e.getTrackId()]))),t.length&&t.forEach((e=>delete this._roomResources[e]))}if(null===(t=this._appListener)||void 0===t?void 0:t.onSwitchRole)return s.length&&s.forEach((e=>this._callAppListener("onSwitchRole",e,Qt.ANCHOR))),o.length&&o.forEach((e=>this._callAppListener("onSwitchRole",e,Qt.AUDIENCE))),i.length&&this._callAppListener("onUserJoin",i),void(n.length&&this._callAppListener("onUserLeave",n));a.length&&this._callAppListener("onUserJoin",a),c.length&&this._callAppListener("onUserLeave",c)}))}getRoomId(){return this._roomId}getCrtUserId(){return this._context.getCurrentId()}__getPC(){return this._pc}getRemoteUserIds(){const e=this._context.getCurrentId();return Object.keys(this._roomResources).filter((t=>t!==e))}getRemoteTracks(){const e=[];return this.getRemoteUserIds().forEach((t=>{e.push(...this.getRemoteTracksByUserId(t))})),e}getRemoteTracksByUserId(e){const t=[];for(const r in this._remoteTracks){const i=this._remoteTracks[r];i.getUserId()===e&&t.push(i)}return t}getSessionId(){return this._sessionId}sendMessage(e,t){return R(this,void 0,void 0,(function*(){const{code:r}=yield this._context.sendMessage(o.RTC_ROOM,this._roomId,{messageType:e,content:t,isStatusMessage:!0});return r!==i.SUCCESS?(S.error(`send message failed -> code: ${r}`),{code:T.SIGNAL_ERROR}):{code:T.SUCCESS}}))}setRoomAttribute(e,t,r,n=!1){return R(this,void 0,void 0,(function*(){const s=yield this._context.setRTCData(this._roomId,e,t,n,a.ROOM,r);return s!==i.SUCCESS?(S.error(`SetRoomAttributeValue Failed: ${s}`),{code:T.SIGNAL_ERROR}):{code:T.SUCCESS}}))}deleteRoomAttributes(e,t,r=!1){return R(this,void 0,void 0,(function*(){const n=yield this._context.removeRTCData(this._roomId,e,r,a.ROOM,t);return n!==i.SUCCESS?(S.error(`DeleteRoomAttribute Failed: ${n}`),{code:T.SIGNAL_ERROR}):{code:T.SUCCESS}}))}getRoomAttributes(e=[],t=!1){return R(this,void 0,void 0,(function*(){const{code:r,data:n}=yield this._context.getRTCData(this._roomId,e,t,a.ROOM);return r!==i.SUCCESS?(S.error(`GetRoomAttributes Failed: ${r}`),{code:T.SIGNAL_ERROR}):{code:T.SUCCESS,data:n}}))}_setUserAttributeValue(e,t,r){return this._context.setRTCData(this._roomId,e,t,!1,a.PERSON,r)}_deleteUserAttributes(e,t){return this._context.removeRTCData(this._roomId,e,!1,a.PERSON,t)}_getUserAttributes(e){return this._context.getRTCData(this._roomId,e,!1,a.PERSON)}isDestroyed(){return this._destroyed}__destroy(e){return this._leaveHandle(e)}_leaveHandle(e){var t;return R(this,void 0,void 0,(function*(){this._destroyed||(this._destroyed=!0,null===(t=this._audioLevelReport)||void 0===t||t.clearAudioLevelReportTimer(),e&&(yield this._context.quitRTCRoom(this._roomId)),this._pc.removeAllLocalTrack(),this._pinger.stop(),yield this._service.exit(this._getRTCReqestHeaders()),this._pc.destroy(),this._polarisReport=null,this._removeRemoteTracks())}))}_onLocalTrackDestroied(e){e instanceof Qe&&e.__isTiny()||this.unpublish([e])}_onLocalTrackMuted(e){return R(this,void 0,void 0,(function*(){const t=e.getTrackId(),r=this._context.getCurrentId(),n=[{resourceId:t,enabled:!e.isLocalMuted()}],s=this._roomResources[r]||[],o=[];for(let e=0;e<s.length;e+=1){const t=s[e],r=_t(t),i=n.findIndex((e=>e.resourceId===r));if(i>=0){const{enabled:e}=n[i];t.state=e?1:0,o.push(t);break}}const a=yield I((()=>this._context.setRTCTotalRes(this._roomId,at(Lt.MODIFY,o),ct(s),Lt.TOTAL_CONTENT_RESOURCE)));a!==i.SUCCESS&&S.error("notice `track.enabled` change failed -> code: "+a)}))}_removePubFailedTracks(e){e.forEach((e=>{const t=e instanceof qe?e:e.track;S.debug(`remove pub failed track from peerconnection -> trackId: ${t.getTrackId()}`),this._pc.removeLocalTrackById(t.getTrackId())}))}publish(e){return R(this,void 0,void 0,(function*(){return I((()=>this.__publish(e)))}))}__publish(e){return R(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return S.error(`publish failed, room has been destroyed. -> roomId: ${this._roomId}`),{code:T.ROOM_HAS_BEEN_DESTROYED};if(!c("tracks",e,(()=>d(e)&&e.length>0&&e.every((e=>e instanceof qe||e.track instanceof qe))),!0))return S.error(`publish failed, tracks is invalid -> roomId: ${this._roomId}`),{code:T.PARAMS_ERROR};const t=this._context.getCurrentId();if(this._pc.getLocalTracks().length+(e=>{let t=0;return e.forEach((e=>{e instanceof qe?t++:e.pubTiny&&e.track.isVideoTrack()?t+=2:t++})),t})(e)>10)return S.error(`publish failed, tracks limit exceeded -> roomId: ${this._roomId}`),{code:T.PUBLISH_TRACK_LIMIT_EXCEEDED};S.debug(`publish tracks -> roomId: ${this._roomId}, tracks: ${e.map(er)}`),e.forEach((e=>{const{track:t,pubTiny:r}=e instanceof qe?{pubTiny:!1,track:e}:e;if(this._pc.addLocalTrack(t),t.isVideoTrack()&&r){let e;try{e=t.__innerGetMediaStreamTrack().clone();const i=r.frameRate||Ve.FPS_15,n=r.resolution||Be.W176_H144,{width:s,height:o}=St(n),a=Et(i);e.applyConstraints({width:s,height:o,frameRate:a})}catch(r){return null==e||e.stop(),void S.warn(`pubTiny failed -> id: ${t.getTrackId()}, msg: ${r.message}`)}this._pc.addLocalTrack(new Qe(t.getTag(),t.getUserId(),e,!0))}})),this._pc.clearReTryExchangeTimer();const r=yield this._createExchangeParams(this._subscribedList,!1),n=yield this._exchangeHandle(r);if(n.code!==T.SUCCESS)return S.error(`publish failed -> roomId: ${this._roomId}, code: ${n.code}`),this._removePubFailedTracks(e),{code:n.code};const{publishList:s,sdp:o,resultCode:a,message:l,urls:h,mcuPublishList:p}=n.data;if(a!==T.SUCCESS)return S.error(`publish failed -> roomId: ${this._roomId}, code: ${a}, msg: ${l}`),this._removePubFailedTracks(e),{code:a};const _=yield this._pc.setRemoteAnswer(o.sdp);if(_!==T.SUCCESS)return{code:_};const m=this._roomResources[t],f=s.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:this._getResourceState(_t(e))},e))),{publishedList:v}=gt(m,f),g=(null==p?void 0:p.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:1},e))))||[],R=yield this._context.setRTCTotalRes(this._roomId,at(Lt.PUBLISH,v),ct(f),Lt.TOTAL_CONTENT_RESOURCE,ct(g));if(R!==i.SUCCESS)return S.error(`send publish streams notification failed: ${R}`),{code:T.SIGNAL_ERROR};this._roomResources[t]=f;const C=v.map((e=>_t(e)));return this._polarisReport&&this._polarisReport.sendR2(qt.PUBLISH,zt.BEGIN,C),e.forEach((e=>{const{track:t}=e instanceof qe?{track:e}:e;t.__innerSetPublished(!0)})),S.debug(`publish success: ${C.join(",")}`),this._roomMode===u.LIVE?{code:T.SUCCESS,liveUrl:null==h?void 0:h.liveUrl}:{code:T.SUCCESS}}))}_reTryExchange(){return R(this,void 0,void 0,(function*(){I((()=>R(this,void 0,void 0,(function*(){const e=yield this._createExchangeParams(this._subscribedList,!0),t=yield this._exchangeHandle(e);if(t.code!==T.SUCCESS)return S.error(`reTryExchange failed: ${t.code}`),{code:t.code};const{sdp:r,resultCode:i}=t.data;if(i!==T.SUCCESS)return S.error(`reTryExchange failed: ${i}`),{code:i};this._pc.clearReTryExchangeTimer();const n=yield this._pc.setRemoteAnswer(r.sdp);return n!==T.SUCCESS?{code:n}:void 0}))))}))}_exchangeHandle(e){return this._service.exchange(this._getRTCReqestHeaders(),e)}_getRTCReqestHeaders(){return{"App-Key":this._context.getAppkey(),RoomId:this._roomId,Token:this._token,RoomType:this._roomMode,UserId:this._context.getCurrentId()}}_createExchangeParams(e,t){return R(this,void 0,void 0,(function*(){return{sdp:yield this._pc.createOffer(t),extend:JSON.stringify({resolutionInfo:this._pc.getOutboundVideoInfo()}),subscribeList:e.filter((e=>{const t=e.track.getTrackId(),{userId:r}=mt(t);if(!this._roomResources[r])return!1;const i=this._roomResources[r].filter((e=>t===`${e.msid}_${e.mediaType}`)).length;return i})).map((e=>({simulcast:e.subTiny?At.TINY:At.NORMAL,resolution:"",uri:this._getResourceById(e.track.getTrackId()).uri}))),switchstream:!1}}))}_getResourceState(e){var t;return(null===(t=this.getLocalTrack(e))||void 0===t?void 0:t.isLocalMuted())?0:1}unpublish(e){return R(this,void 0,void 0,(function*(){return I((()=>this.__unpublish(e)))}))}__unpublish(e){var t;return R(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return S.warn(`room has been destroyed, no need to unpublish tracks -> roomId: ${this._roomId}`),{code:T.SUCCESS};const r=this._context.getCurrentId();if(!c("tracks",e,(()=>e.every((e=>e.getUserId()===r&&e instanceof qe))),!0))return S.warn(`unpublish failed, tracks is invalid -> roomId: ${this._roomId}, tracks: ${e.map(er)}`),{code:T.PARAMS_ERROR};const n=e.map((e=>e.getTrackId())),s=n.map(this._getResourceById.bind(this)).filter((e=>!!e));if(0===s.length)return{code:T.SUCCESS};const o=this._roomResources[r].filter((e=>!s.includes(e)));n.forEach((e=>this._pc.removeLocalTrackById(e))),null===(t=this._polarisReport)||void 0===t||t.sendR2(qt.PUBLISH,zt.END,n),this._pc.clearReTryExchangeTimer();const a=yield this._createExchangeParams(this._subscribedList,!1),d=yield this._exchangeHandle(a);if(d.code!==T.SUCCESS)return S.error(`exchange failed -> code: ${d.code}`),{code:d.code};const{publishList:u,sdp:l,resultCode:h,message:p,mcuPublishList:_}=d.data;h!==T.SUCCESS&&S.error(`unpublish streams failed -> code: ${h}, msg: ${p}`);const m=_?_.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:1},e))):[],f=yield this._context.setRTCTotalRes(this._roomId,at(Lt.UNPUBLISH,s),ct(o),Lt.TOTAL_CONTENT_RESOURCE,ct(m));if(f!==i.SUCCESS)return S.error("send unpublish notification failed:",f),{code:T.SIGNAL_ERROR};S.debug(`unpublish success -> tracks: ${n.join(",")}`);const v=yield this._pc.setRemoteAnswer(l.sdp);if(v!==T.SUCCESS)return{code:v};const g=u.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:this._getResourceState(_t(e))},e)));return this._roomResources[r]=g,{code:T.SUCCESS}}))}_getResourceById(e){const{userId:t}=mt(e);return this._roomResources[t].find((t=>_t(t)===e))}_isValidResourceId(e){var t;const{userId:r}=mt(e);return!!(null===(t=this._roomResources[r])||void 0===t?void 0:t.find((t=>_t(t)===e)))}subscribe(e){return R(this,void 0,void 0,(function*(){return I((()=>this.__subscribe(e,!1)))}))}__subscribe(e,t=!1){var r;return R(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return S.error(`subscribe failed, room has been destroyed -> roomId: ${this._roomId}`),{code:T.ROOM_HAS_BEEN_DESTROYED};if(!c("tracks",e,(()=>d(e)&&e.length>0&&e.every((e=>e instanceof nt||e.track instanceof nt))),!0))return S.error(`subscribe failed, tracks is invalid -> roomId: ${this._roomId}`),{code:T.PARAMS_ERROR};S.info(`subscribe -> roomId: ${this._roomId}, tracks: ${e.map(er)}`);const i=this._subscribedList.map((e=>Object.assign({},e))),n=e.map((e=>e instanceof nt?{track:e}:e));let s=!1;const o=[];return n.forEach((e=>{const t=e.track.getTrackId();o.push(t);const r=i.find((e=>e.track.getTrackId()===t));r&&r.subTiny===e.subTiny||(r?r.subTiny=e.subTiny:i.push(e),s=!0)})),s||t?(null===(r=this._polarisReport)||void 0===r||r.sendR2(qt.SUBSCRIBE,zt.BEGIN,o),this._updateSubListHandle(i,!0)):{code:T.SUCCESS}}))}unsubscribe(e){return R(this,void 0,void 0,(function*(){return I((()=>this.__unsubscribe(e)))}))}__unsubscribe(e){var t;return R(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return S.warn(`room has beed destroyed, no need to unsubscribe tracks -> roomId: ${this._roomId}`),{code:T.SUCCESS};if(!c("tracks",e,(()=>d(e)&&e.length>0&&e.every((e=>e instanceof nt))),!0))return S.error(`unsubscribe failed, tracks is invalid -> roomId: ${this._roomId}`),{code:T.PARAMS_ERROR};S.info(`unsubscribe -> roomId: ${this._roomId}, tracks: ${e.map(er)}`);const r=this._subscribedList.map((e=>Object.assign({},e))).filter((t=>!e.includes(t.track)));return null===(t=this._polarisReport)||void 0===t||t.sendR2(qt.SUBSCRIBE,zt.END,e.map((e=>e.getTrackId()))),this._updateSubListHandle(r,!1)}))}_assertRoomDestroyed(){if(this._destroyed){const e="This room has been destroyed. Please use `RCRTCClient.joinRTCRoom` or `RCRTCClient.joinLivingRoom` to catch another instance.";return S.warn(e),T.ROOM_HAS_BEEN_DESTROYED}}getLocalTrack(e){return this._pc.getLocalTrack(e)}getLocalTracks(){return this._pc.getLocalTracks()}getRemoteTrack(e){return this._remoteTracks[e]||null}updateSubList(e){return R(this,void 0,void 0,(function*(){return I((()=>this._updateSubListHandle(e,!1)))}))}_updateSubListHandle(e,t=!1){return R(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return{code:T.ROOM_HAS_BEEN_DESTROYED};if(!c("resources",e,(()=>d(e)&&e.every((e=>e instanceof nt||e.track instanceof nt))),!0))return S.error(`update sublist failed, tracks is invalid -> roomId: ${this._roomId}`),{code:T.PARAMS_ERROR};S.info(`update subscribe list -> roomId: ${this._roomId}, forceReq: ${t}, tracks: ${e.map(er)}`);let r=e.map((e=>e instanceof nt?{track:e}:Object.assign({},e)));const i={};r=r.filter((e=>{const t=e.track.getTrackId();return this._remoteTracks[t]?!i[t]&&(i[t]=!0):(S.warn(`track cannot found in room -> trackId: ${t}`),!1)})).map((e=>Object.assign({},e)));const n=this._subscribedList.map((e=>Object.assign({},e)));if(!t){let e=!1;if(r.forEach((t=>{const r=n.findIndex((e=>e.track===t.track));if(-1===r)return void(e=!0);n.splice(r,1)[0].subTiny!==t.subTiny&&(e=!0)})),n.length&&(e=!0),!e)return{code:T.SUCCESS}}this._pc.clearReTryExchangeTimer(),this._pc.updateSubRemoteTracks(r.map((e=>e.track)));const s=yield this._createExchangeParams(r,!1),o=yield this._exchangeHandle(s),a=r.map((e=>e.track.getTrackId()));if(o.code!==T.SUCCESS)return{code:o.code};const{sdp:u,resultCode:l,message:h,subscribedList:p}=o.data;if(l!==T.SUCCESS)return S.error(`change subscribe list failed: ${l}`),{code:l};S.debug(`subscribe success: ${a.join(",")}`);const _=yield this._pc.setRemoteAnswer(u.sdp);if(_!==T.SUCCESS)return{code:_};const m=null==p?void 0:p.map((e=>`${e.msid}_${e.mediaType}`)),f=r.filter((e=>null==m?void 0:m.includes(e.track.getTrackId()))),v=r.filter((e=>!(null==m?void 0:m.includes(e.track.getTrackId()))));for(const e in this._remoteTracks){const t=f.some((t=>t.track.getTrackId()===e));this._remoteTracks[e].__innerSetSubscribed(t)}return this._subscribedList.splice(0,this._subscribedList.length,...f),v.length?{code:T.SUCCESS,failedList:v}:{code:T.SUCCESS}}))}registerRoomEventListener(e){this._appListener=e}registerReportListener(e){this._pc.registerReportListener(e)}onAudioLevelChange(e,t){var r;null===(r=this._audioLevelReport)||void 0===r||r.clearAudioLevelReportTimer(),this._audioLevelReport=new Zt(this),this._audioLevelReport.onAudioLevelChange(e,t||1e3)}__onReconnected(e){return R(this,void 0,void 0,(function*(){if("closed"===this._pc.getRTCPeerConn().connectionState)return S.warn("RTCPeerConnection closed. Please rejoin room to restore services."),void this._rtcpeerClosed();const{code:t,data:r}=yield this._context.joinRTCRoom(this._roomId,this._roomMode,e);if(t!==i.SUCCESS)return void S.error(`RTC __onReconnected getRTCRoomInfo failed: ${t}`);S.debug(`RTC __onReconnected getRTCRoomInfo success: ${JSON.stringify(r)}`);const n=[],s={},o={},a={},c=Ot(r),d=Object.keys(c),u=Object.keys(this._roomResources);for(let e=d.length-1;e>=0;e-=1){const t=d[e],r=u.indexOf(t);if(-1===r){n.push(t),s[t]=vt(c[t]);continue}const i=this._roomResources[t],l=c[t],{publishedList:h,modifiedList:p,unpublishedList:_}=gt(i,l,!0);s[t]=vt(h),o[t]=vt(_),a[t]=vt(p),u.splice(r,1)}u.length&&u.forEach((e=>{delete this._roomResources[e]})),Object.assign(this._roomResources,c),u.length&&this._callAppListener("onUserLeave",u),n.length&&this._callAppListener("onUserJoin",n);for(const e in o){const t=o[e];if(t.length){const e=t.map((e=>this._remoteTracks[_t(e)]));yield this._onUserUnpublish(e)}}return Object.keys(s).forEach((e=>{const t=s[e];if(0===t.length)return;const r=t.map((e=>{const t=_t(e),{userId:r,tag:i,mediaType:n}=mt(t),s=this._remoteTracks[t]=n===Fe.AUDIO_ONLY?new st(i,r):new ot(i,r);return s.__innerSetRemoteMuted(0===e.state),s}));this._onTrackPublish(r)})),Object.keys(a).forEach((e=>{a[e].forEach((e=>{const t=_t(e),r=this._remoteTracks[t];r.__innerSetRemoteMuted(0===e.state),r.isAudioTrack()?this._onAudioMuteChange(r):this._onVideoMuteChange(r)}))})),{data:r}}))}_onAudioMuteChange(e){this._callAppListener("onAudioMuteChange",e)}_onVideoMuteChange(e){this._callAppListener("onVideoMuteChange",e)}_afterChangedRole(e){}_removeRemoteTracks(){const e=Object.values(this._remoteTracks);e.length&&(e.forEach((e=>{e.isAudioTrack()&&e.__releaseMediaElement()})),this._remoteTracks={})}}var rr,ir,nr;!function(e){e[e.CROP=1]="CROP",e[e.WHOLE=2]="WHOLE"}(rr||(rr={})),function(e){e[e.CUSTOMIZE=1]="CUSTOMIZE",e[e.SUSPENSION=2]="SUSPENSION",e[e.ADAPTATION=3]="ADAPTATION"}(ir||(ir={})),function(e){e[e.CROP=1]="CROP",e[e.WHOLE=2]="WHOLE"}(nr||(nr={}));const sr=()=>({version:1,mode:ir.SUSPENSION});class or{constructor(e,t,r){this._onFlush=e,this._isValidTrackId=t,this._sendCDNInfoSignal=r,this._values=sr()}setHostVideoTrack(e){if(!this._isValidTrackId(e))return S.error(`setHostVideoTrack failed: videoTrackId is invalid -> ${e}`),this;const{mediaType:t,tag:r,userId:i}=mt(e);return t!==Fe.VIDEO_ONLY?(S.error(`setHostVideoTrack failed: kind of resource is not 'video' -> ${e}`),this):(this._values.host_stream_id=ft(i,r),this)}setMixLayoutMode(e){return[ir.CUSTOMIZE,ir.SUSPENSION,ir.ADAPTATION].includes(e)?(this._values.mode=e,this):(S.error(`layout mode is invalid: ${e}`),this)}_addOutputValue(e,t,r="normal"){const i=this._values.output||(this._values.output={video:{normal:{width:640,height:480}}});if("cdn"===e)return void(i.cdn=t);if("audio"===e)return void(i.audio={bitrate:t});const n=i.video;if("normal"!==r&&"tiny"!==r)if("backgroundColor"!==r)if("exparams"!==r){if("backgroundPicture"===r){const e=n.backgroundPicture||(n.backgroundPicture={fillMode:rr.CROP,picture:[]});Object.assign(e,t)}}else n.exparams={renderMode:t};else n.backgroundColor=t;else{const e=n[r]||(n[r]={});Object.assign(e,t)}}setOutputVideoResolution(e){if(!Tt(e))return S.warn("setOutputVideoResolution failed: `resolution` is invalid"),this;const{width:t,height:r}=St(e);return this._addOutputValue("video",{width:t,height:r},"normal"),this}setOutputVideoFPS(e){if(!Ct(e))return S.warn("setOutputVideoFPS failed: `fps` is invalid"),this;const t=Et(e);return this._addOutputValue("video",{fps:t},"normal"),this}setOutputVideoBitrate(e){return!r(e)||e<=0?S.error(`bitrate is invalid: ${e}`):this._addOutputValue("video",{bitrate:e},"normal"),this}setOutputTinyVideoResolution(e){if(!Tt(e))return S.warn("setOutputTinyVideoResolution failed: `resolution` is invalid"),this;const{width:t,height:r}=St(e);return this._addOutputValue("video",{width:t,height:r},"tiny"),this}setOutputTinyVideoFPS(e){if(!Ct(e))return S.warn("setOutputTinyVideoFPS failed: `fps` is invalid"),this;const t=Et(e);return this._addOutputValue("video",{fps:t},"tiny"),this}setOutputTinyVideoBitrate(e){return!r(e)||e<=0?S.error(`bitrate is invalid: ${e}`):this._addOutputValue("video",{bitrate:e},"tiny"),this}setOutputVideoRenderMode(e){return[nr.CROP,nr.WHOLE].includes(e)?this._addOutputValue("video",e,"exparams"):S.error(`renderMode is invalid: ${e}`),this}setOutputAudioBitrate(e){return r(e)&&e>0?this._addOutputValue("audio",e):S.error(`bitrate is invalid: ${e}`),this}setOutputBackgroundColor(e){return/^0x[a-fA-F0-9]{6}$/.test(e)?this._addOutputValue("video",e,"backgroundColor"):S.error(`color is invalid: ${e}`),this}addOutputBackgroundPicture(e,t,i,n,s){var o,a,c;if(!l(e))return S.error(`uri is invalid: ${e}`),this;if([t,i,n,s].some((e=>!r(e)||e<0||e>1)))return S.error(`some attrs of (x, y, w, h) is invalid: ${t}, ${i}, ${n}, ${s}`),this;const d=(null===(c=null===(a=null===(o=this._values.output)||void 0===o?void 0:o.video)||void 0===a?void 0:a.backgroundPicture)||void 0===c?void 0:c.picture)||[];return d.push({uri:e,w:n,h:s,x:t,y:i}),this._addOutputValue("video",{picture:d},"backgroundPicture"),this}removeOutputBackgroundPicture(e){var t,r,i;if(!l(e))return S.error(`uri is invalid: ${e}`),this;let n=null===(i=null===(r=null===(t=this._values.output)||void 0===t?void 0:t.video)||void 0===r?void 0:r.backgroundPicture)||void 0===i?void 0:i.picture;return n&&(n=n.filter((t=>t.uri!==e)),this._addOutputValue("video",{pictures:n},"backgroundPicture")),this}clearOutputBackgroundPicture(){return this._addOutputValue("video",{pictures:[]},"backgroundPicture"),this}setOutputBackgroundPictureFillMode(e){return[rr.CROP,rr.WHOLE].includes(e)?this._addOutputValue("video",{fillMode:e},"backgroundPicture"):S.error(`fillMode is invalid: ${e}`),this}addPublishStreamUrls(e){var t,r;const i=/^rtmp:\/\/.+/;if(!d(e)||0===e.length||e.some((e=>!i.test(e))))return S.error(`urls is invalid: ${e}`),this;const n=(null===(r=null===(t=this._values.output)||void 0===t?void 0:t.cdn)||void 0===r?void 0:r.concat())||[];let s=!1;return e.forEach((e=>{n.some((t=>t.pushurl===e))||(s=!0,n.push({pushurl:e}))})),n.length>5?(S.error("publish stream url no more than 5"),this):(s&&this._addOutputValue("cdn",n),this)}removePublishStreamUrls(e){var t,r;const i=/^rtmp:\/\/.+/;if(!d(e)||0===e.length||e.some((e=>!i.test(e))))return S.error(`urls is invalid: ${e}`),this;const n=(null===(r=null===(t=this._values.output)||void 0===t?void 0:t.cdn)||void 0===r?void 0:r.concat())||[];for(let t=n.length-1;t>=0;t-=1){const{pushurl:r}=n[t],i=e.indexOf(r);i>=0&&(e.splice(i,1),n.splice(t,1))}return this._addOutputValue("cdn",n),this}clearPublishStreamUrls(){return this._addOutputValue("cdn",[]),this}addCustomizeLayoutVideo(e,t,i,n,s){if(!this._isValidTrackId(e))return S.error(`trackId is invalid: ${e}`),this;if(!r(t)||!r(i))return S.error(`some attrs of (x, y) is invalid: ${t}, ${i}`),this;if([n,s].some((e=>!r(e)||e<0)))return S.error(`some attrs of (width, height) is invalid: ${n}, ${s}`),this;const{userId:o,tag:a,mediaType:c}=mt(e);if(c!==Fe.VIDEO_ONLY)return S.error(`kind of resource is not 'video': ${e}`),this;const d=ft(o,a);return(this._values.input||(this._values.input={video:[]})).video.push({user_id:o,stream_id:d,x:t,y:i,width:n,height:s}),this}removeCustomizeLayoutVideo(e){if(!this._isValidTrackId(e))return S.error(`trackId is invalid: ${e}`),this;const{userId:t,tag:r,mediaType:i}=mt(e);if(i!==Fe.VIDEO_ONLY)return S.error(`kind of resource is not 'video': ${e}`),this;const n=ft(t,r),s=this._values.input||(this._values.input={video:[]});return s.video=s.video.filter((e=>e.stream_id===n)),this}clearCustomizeLayoutVideo(){return(this._values.input||(this._values.input={video:[]})).video=[],this}flush(){var e,t,r,i;return R(this,void 0,void 0,(function*(){const n=JSON.parse(JSON.stringify(this._values)),{code:s}=yield this._onFlush(n);return s===T.SUCCESS&&((null===(t=null===(e=this._values.output)||void 0===e?void 0:e.video.normal)||void 0===t?void 0:t.width)||(null===(i=null===(r=this._values.output)||void 0===r?void 0:r.video.normal)||void 0===i?void 0:i.fps))&&this._sendCDNInfoSignal(),this._values=sr(),{code:s}}))}}var ar,cr,dr;!function(e){e[e.OPEN=1]="OPEN",e[e.STOP=2]="STOP"}(ar||(ar={})),function(e){e[e.SPREAD=0]="SPREAD",e[e.NO_SPREAD=-1]="NO_SPREAD"}(cr||(cr={})),function(e){e[e.AUTOMATIC=0]="AUTOMATIC",e[e.MANUAL=1]="MANUAL"}(dr||(dr={}));class ur extends tr{constructor(e,t,r,i,n,s,o,a,c=!1){var d;super(e,t,r,i,u.LIVE,n,s,o,c),this._livingType=a,this._CDNUris=null,this._CDNEnable=!1,this._mcuConfigBuilder=new or(this._onMCUConfigFlush.bind(this),this._isValidResourceId.bind(this),this._sendCDNInfoSignal.bind(this));const l=null===(d=i.roomInfo.filter((e=>"cdn_uris"===e.key))[0])||void 0===d?void 0:d.value;l&&(this._CDNUris=JSON.parse(l)[0])}getLivingType(){return this._livingType}getMCUConfigBuilder(){return this._mcuConfigBuilder}_onMCUConfigFlush(e){return R(this,void 0,void 0,(function*(){const t={"App-Key":this._context.getAppkey(),Token:this._token,RoomId:this.getRoomId(),UserId:this._context.getCurrentId(),SessionId:this.getSessionId()},{code:r,res:i}=yield this._service.setMcuConfig(t,e);return r!==T.SUCCESS?(S.error(`set MCU config failed: ${r}`),{code:r}):(S.info("set MCU config success"),i.pull_url&&(this._CDNUris=JSON.parse(i.pull_url)),{code:r,res:i})}))}__onReconnected(){const e=Object.create(null,{__onReconnected:{get:()=>super.__onReconnected}});var t,r;return R(this,void 0,void 0,(function*(){const i=yield e.__onReconnected.call(this,this._livingType);if(!i||!i.data)return;const n=i.data.roomInfo,s=null===(t=n.filter((e=>"cdn_uris"===e.key))[0])||void 0===t?void 0:t.value;if(!s)return;const o=JSON.parse(s);(null===(r=this._CDNUris)||void 0===r?void 0:r.enableInnerCDN)!==o.enableInnerCDN&&this._callAppListener("onCDNEnableChange",o.enableInnerCDN),this._CDNUris=o}))}enableInnerCDN(e){return R(this,void 0,void 0,(function*(){if(!h(e))return S.error("`enable` is invalid"),{code:T.PARAMS_ERROR};this._CDNEnable=e;const t={version:2,output:{inCDNModel:e?ar.OPEN:ar.STOP}},{code:r}=yield this._onMCUConfigFlush(t);if(r!==T.SUCCESS)return S.error(`enableInnerCDN failed -> code: ${r}`),{code:T.SIGNAL_ERROR};if(this._CDNUris&&this._CDNUris.broadcast!==cr.SPREAD)return S.info("enableInnerCDN succeed"),{code:T.SUCCESS};const{code:i}=yield I((()=>R(this,void 0,void 0,(function*(){return this._sendCDNInfoSignal()}))));return i===T.SUCCESS?(S.info("enableInnerCDN succeed"),{code:T.SUCCESS}):(S.error(`enableInnerCDN failed -> code: ${i}`),{code:i})}))}_sendCDNInfoSignal(){return R(this,void 0,void 0,(function*(){this._CDNUris=Object.assign({},this._CDNUris,{enableInnerCDN:this._CDNEnable});return(yield Promise.all([this._spreadCDNInfo(this._CDNUris),this._setRoomCDNInfo(this._CDNUris)])).every((e=>e.code===T.SUCCESS))?{code:T.SUCCESS}:{code:T.SIGNAL_ERROR}}))}_spreadCDNInfo(e){return R(this,void 0,void 0,(function*(){const t=yield this._context.setRTCCDNUris(this._roomId,Lt.TOTAL_CONTENT_RESOURCE,JSON.stringify([e]));return t!==i.SUCCESS?(S.error(`spreadCDNInfo failed -> code: ${t}`),{code:T.SIGNAL_ERROR}):(S.info("spreadCDNInfo succeed"),{code:T.SUCCESS})}))}_setRoomCDNInfo(e){return R(this,void 0,void 0,(function*(){const t=yield this._context.setRTCData(this._roomId,"cdn_uris",JSON.stringify([e]),!0,a.ROOM);return t!==i.SUCCESS?(S.error(`setRoomCDNInfo failed -> code: ${t}`),{code:T.SIGNAL_ERROR}):(S.info("setRoomCDNInfo succeed"),{code:T.SUCCESS})}))}_resourceHandle(e,t,r){const i=Object.create(null,{_resourceHandle:{get:()=>super._resourceHandle}});var n;return R(this,void 0,void 0,(function*(){i._resourceHandle.call(this,e,t,r),e.cdn_uris&&((null===(n=this._CDNUris)||void 0===n?void 0:n.enableInnerCDN)!==e.cdn_uris[0].enableInnerCDN&&this._callAppListener("onCDNEnableChange",!this.__getCDNEnable()),this._CDNUris=e.cdn_uris[0])}))}_exchangeHandle(e){var t,r,i;return R(this,void 0,void 0,(function*(){const n=yield this._service.exchange(this._getRTCReqestHeaders(),e),s=null===(r=null===(t=n.data)||void 0===t?void 0:t.urls)||void 0===r?void 0:r.pull_url;return n.code===T.SUCCESS&&s?(this._CDNUris=JSON.parse(s),(null===(i=this._CDNUris)||void 0===i?void 0:i.broadcast)===cr.SPREAD&&(this._CDNEnable=!0,this._sendCDNInfoSignal()),n):n}))}_afterChangedRole(e){const t=Ot(e),r=this._context.getCurrentId(),i=Object.keys(t);setTimeout((()=>{var n,s,o;const a=i.filter((e=>e!==r));a.length>0&&this._callAppListener("onUserJoin",a);for(const e in t)e!==r&&this._resourceHandle({uris:t[e]},Lt.TOTAL_CONTENT_RESOURCE,e);(null===(n=e.roomInfo.filter((e=>"cdn_uris"===e.key))[0])||void 0===n?void 0:n.value)&&(null===(s=this._CDNUris)||void 0===s?void 0:s.push_mode)===dr.MANUAL&&this._callAppListener("onCDNEnableChange",null===(o=this._CDNUris)||void 0===o?void 0:o.enableInnerCDN)}))}__getCDNEnable(){var e;return null===(e=this._CDNUris)||void 0===e?void 0:e.enableInnerCDN}__getCDNPushMode(){var e;return null===(e=this._CDNUris)||void 0===e?void 0:e.push_mode}}class lr extends tr{constructor(e,t,r,i,n,s,o){super(e,t,r,i,u.RTC,n,s,o,!1)}}const hr=()=>({"Content-Type":"application/json;charset=UTF-8","Cache-Control":"no-cache",ClientType:`web|${yt.browser}|${yt.version}`,ClientVersion:"5.2.4","Client-Session-Id":"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})),"Request-Id":Date.now().toString()});class pr{constructor(e,t,r,i=5e3){this._runtime=e,this._context=t,this._msUrl=r,this._timeout=i,this._msInNavi=[],this._failedMs=[],this._rtcFinger=void 0,this._clusterId="",this._configUrl=""}getNaviMS(){return this._msUrl?[this._msUrl]:this._clusterId?[`https://${this._clusterId}`]:(0===this._msInNavi.length&&(0===this._failedMs.length?this._msInNavi.push(...(e=>{var t;if(!e)return[];let r;try{r=JSON.parse(e.voipCallInfo||'{ "strategy": 0 }')}catch(t){return S.warn("parse `voipCallInfo` of navi failed: "+e.voipCallInfo),[]}if(0===r.strategy)return[];const i=null===(t=r.callEngine)||void 0===t?void 0:t.filter((e=>4===e.engineType));if(!i||0===i.length)return[];const n=i[0],s=[];return n.mediaServer&&s.push(n.mediaServer.replace(/^(https?:\/\/)?/,"https://")),n.backupMediaServer&&n.backupMediaServer.forEach((e=>{s.push(e.replace(/^(https?:\/\/)?/,"https://"))})),s})(this._context.getNaviInfo())):(this._msInNavi.push(...this._failedMs),this._failedMs.length=0)),this._msInNavi.map((e=>e.trim())))}_request(e,t,r){return R(this,void 0,void 0,(function*(){const i=this.getNaviMS();if(0===i.length)return{code:T.NOT_OPEN_VIDEO_AUDIO_SERVER};this._rtcFinger&&(r.rtcFinger=this._rtcFinger);for(let n=0;n<i.length;n+=1){const s=`${i[n]}${e}`,o=hr();S.debug(`request -> Request-Id: ${o["Request-Id"]}, url: ${s}`);const{status:a,data:c}=yield this._runtime.httpReq({url:s,body:JSON.stringify(r),headers:Object.assign(Object.assign({},o),t),method:p.POST,timeout:this._timeout});if(200===a){const e=JSON.parse(c);return e.rtcFinger&&(this._rtcFinger=e.rtcFinger),e.clusterId&&(this._clusterId=e.clusterId),S.debug(`request success -> Request-Id: ${o["Request-Id"]}`),{code:T.SUCCESS,data:e}}S.warn(`request failed -> Request-Id: ${o["Request-Id"]}, status: ${a}, url: ${s}`),this._failedMs.push(...this._msInNavi.splice(n,1))}return{code:T.REQUEST_FAILED}}))}exchange(e,t){var r;return R(this,void 0,void 0,(function*(){const i=yield this._request("/exchange",e,t);if(i.code===T.SUCCESS&&(null===(r=i.data)||void 0===r?void 0:r.resultCode)===T.SUCCESS){const e=i.data.urls;e&&(this._configUrl=e.configUrl)}return i}))}exit(e){return R(this,void 0,void 0,(function*(){const{code:t}=yield this._request("/exit",e,{});return t}))}broadcastSubscribe(e,t){return this._request("/broadcast/subscribe",e,t)}broadcastExit(e){return R(this,void 0,void 0,(function*(){const{code:t}=yield this._request("/broadcast/exit",e,{});return{code:t}}))}setMcuConfig(e,t){return R(this,void 0,void 0,(function*(){if(!this._configUrl)return{code:T.MCU_SERVER_NOT_FOUND};const r=`${this._configUrl.replace(/^(https?:\/\/)?/,"https://")}/server/mcu/config`,i=hr();S.debug(`request -> Request-Id: ${i["Request-Id"]}, url: ${r}`);const{status:n,data:s}=yield this._runtime.httpReq({url:r,headers:Object.assign(Object.assign({},i),e),body:JSON.stringify(t),method:p.POST});if(200===n){S.debug(`request success -> Request-Id: ${i["Request-Id"]}`);const e=JSON.parse(s);return{code:e.resultCode,res:e}}return{code:T.REQUEST_FAILED}}))}getCDNResourceInfo(e,t){return R(this,void 0,void 0,(function*(){const r=hr(),{status:i,data:n}=yield this._runtime.httpReq({url:t,headers:Object.assign(Object.assign({},r),e),method:p.GET});if(200===i){const e=JSON.parse(n);return{code:e.resultCode,res:e}}return S.warn(`request failed -> Request-Id: ${r["Request-Id"]}, status: ${i}, url: ${t}`),{code:T.REQUEST_FAILED}}))}}var _r,mr,fr;!function(e){e[e.VIDEO=0]="VIDEO",e[e.AUDIO=1]="AUDIO"}(_r||(_r={}));class vr{constructor(e,t,r){this._context=e,this._rtcToken="",this._liveUrl="",this._subTracks=[],this._livingType=null,this._mediaType=null,this._subTiny=!1,this._fromRetry=!1,this._appListener=null,this._service=new pr(t,e,r.mediaServer)}_getReqHeaders(e){return R(this,void 0,void 0,(function*(){const t=this._context.getCurrentId(),r=t;if(!this._rtcToken){const{code:t,data:n}=yield this._context.getRTCToken(r,u.LIVE,e);if(t!==i.SUCCESS)return S.error(`getRTCToken failed: ${t}`),{code:T.SIGNAL_ERROR};this._rtcToken=n.rtcToken}return{code:T.SUCCESS,headers:{"App-Key":this._context.getAppkey(),UserId:t,RoomId:r,RoomType:u.LIVE,Token:this._rtcToken}}}))}_clearSubscribeInfo(){var e;this._liveUrl="",this._livingType=null,this._mediaType=null,this._subTiny=!1,this._subTracks.length=0,null===(e=this._pc)||void 0===e||e.destroy(),this._pc=null}_reTryExchange(){var e;return R(this,void 0,void 0,(function*(){this._fromRetry=!0;const{code:t}=yield this.subscribe(this._liveUrl,this._livingType,this._mediaType,this._subTiny);t===T.SUCCESS&&(null===(e=this._pc)||void 0===e||e.clearReTryExchangeTimer())}))}subscribe(e,t,r,i=!1){return R(this,void 0,void 0,(function*(){return I((()=>this.__subscribe(e,t,r,i)))}))}__subscribe(e,t,r,i=!1){var n;return R(this,void 0,void 0,(function*(){const s=[];if(Pt(this._context.getNaviInfo()))return{code:T.PACKAGE_ENVIRONMENT_ERROR,tracks:s};if(!this._fromRetry&&(null===(n=this._pc)||void 0===n||n.clearReTryExchangeTimer()),this._fromRetry=!1,!_(e))return S.error(`liveUrl is invalid: ${e}`),{code:T.PARAMS_ERROR,tracks:s};if(![_r.AUDIO,_r.VIDEO].includes(t))return S.error(`livingType is invalid: ${t}`),{code:T.PARAMS_ERROR,tracks:s};if(![Fe.AUDIO_ONLY,Fe.VIDEO_ONLY,Fe.AUDIO_VIDEO].includes(r))return S.error(`mediaType is invalid: ${r}`),{code:T.PARAMS_ERROR,tracks:s};if(this._liveUrl&&this._liveUrl!==e)return{code:T.BROADCAST_SUB_LIST_NOT_EMPTY,tracks:s};this._pc||(this._pc=new Wt(this._reTryExchange.bind(this)),this._pc.on(Wt.__INNER_EVENT_TRACK_READY__,this._onTrackReady,this),this.registerReportListener(this._reportListener)),this._liveUrl=e;const{code:o,headers:a}=yield this._getReqHeaders(t);if(o!==T.SUCCESS)return{code:o,tracks:s};const c=`rc_mcu_${Date.now()}`,d="RongCloudRTC";0===this._subTracks.length&&(this._subTracks.push(new st(d,c),new ot(d,c)),this._pc.updateSubRemoteTracks(this._subTracks.slice()));const u={sdp:yield this._pc.createOffer(!0),liveUrl:e,mediaType:r,simulcast:i?At.TINY:At.NORMAL,switchstream:!1},l=yield this._service.broadcastSubscribe(a,u);if(l.code!==T.SUCCESS)return S.error(`andience subscribe failed: ${l.code}`),{code:l.code,tracks:s};const h=l.data;if(h.resultCode!==T.SUCCESS)return S.error(`andience subscribe failed! code: ${h.resultCode}; message: ${h.message}`),{code:h.resultCode,tracks:s};S.debug(`andience subscribe success: ${e}`),this._livingType=t,this._mediaType=r,this._subTiny=i;const{sdp:p,subscribedList:m}=h,f=[];return m.forEach((e=>{const{mediaType:t}=e,r=this._subTracks[t];f.push(r),r.__innerSetRemoteMuted(!0)})),this._pc.setRemoteAnswer(p.sdp),{code:T.SUCCESS,tracks:f}}))}unsubscribe(){return R(this,void 0,void 0,(function*(){return I((()=>this.__unsubscribe()))}))}__unsubscribe(){var e;return R(this,void 0,void 0,(function*(){if(null===(e=this._pc)||void 0===e||e.clearReTryExchangeTimer(),!this._rtcToken||!this._liveUrl)return{code:T.SUCCESS};const{headers:t}=yield this._getReqHeaders(),{code:r}=yield this._service.broadcastExit(t);return r!==T.SUCCESS?S.error(`broadcast unsubscribe failed: ${r}`):S.debug("broadcast unsubscribe success"),this._clearSubscribeInfo(),{code:r}}))}registerReportListener(e){var t;this._reportListener=e,null===(t=this._pc)||void 0===t||t.registerReportListener(e)}registerTrackEventListener(e){this._appListener=e}_onTrackReady(e){var t,r;const i=e.receiver.track,n="audio"===i.kind?Fe.AUDIO_ONLY:Fe.VIDEO_ONLY,s=this._subTracks[n];s.__innerSetMediaStreamTrack(i);try{null===(r=null===(t=this._appListener)||void 0===t?void 0:t.onTrackReady)||void 0===r||r.call(t,s)}catch(e){S.error(e)}}}!function(e){e.RTMP="rtmp",e.FLV="flv",e.HLS="hls"}(mr||(mr={})),function(e){e[e.NOT_HTTPS=0]="NOT_HTTPS",e[e.HTTPS=1]="HTTPS"}(fr||(fr={}));const gr=Object.assign(Object.assign({},St(Be.W176_H144)),{frameRate:Et(Ve.FPS_15)});class Rr{constructor(e,t,r,i,n,s){this._context=e,this._runtime=t,this._initOptions=r,this._roomId=i,this._joinResData=n,this._livingType=s,this._roomAnchorList=[],this._roomRes={},this._roomAnchorRes={},this._remoteTracks={},this._appListener=null,this._subscribedList=[],this._sessionId="",this._destroyed=!1,this._setInitData(),this._service=new pr(this._runtime,this._context,this._initOptions.mediaServer,this._initOptions.timeout),this._polarisReport=new Xt(this._context,this._runtime,this._roomId,this,Kt.Audience),this._polarisReport.sendR1(),this._pc=new Wt(this._reTryExchange.bind(this),this._polarisReport),this._pc.on(Wt.__INNER_EVENT_TRACK_READY__,(e=>{const t=e.streams[0].id,r=e.receiver.track,i=[t,"audio"===r.kind?Fe.AUDIO_ONLY:Fe.VIDEO_ONLY].join("_"),n=this._remoteTracks[i];n?(n.__innerSetMediaStreamTrack(r),this._callAppListener("onTrackReady",n)):S.warn("cannot found RCRemoteTrack:",r.id)})),this._context.onrtcdatachange=this.singalDataChange.bind(this)}_setInitData(){const{sessionId:e,remoteUserIds:t,remoteRTCUris:r,remoteMUCUris:i,remoteTracks:n,CDNUris:s}=((e,t)=>{const r=t.filter((e=>"RC_RTC_SESSIONID"===e.key))[0].value,i=t.filter((e=>"RC_ANCHOR_LIST"===e.key)).map((e=>JSON.parse(e.value||"[]")))[0],n=t.filter((e=>e.key.includes("RC_RES_"))).map((e=>JSON.parse(e.value||"{}"))),s=n.length?JSON.parse(n[0].mcu_uris||"[]"):[],o=[];s.forEach((t=>{const{mediaType:r,tag:i}=t,n=r===Fe.AUDIO_ONLY?new st(i,"",e):new ot(i,"",e);o.push(n)}));const a=[],c=[];n.forEach((e=>{const t=JSON.parse(e.uris||"[]");a.push(...t),t.forEach((e=>{const{mediaType:t,tag:r,msid:i}=e,n=i.split("_")[0],s=t===Fe.AUDIO_ONLY?new st(r,n):new ot(r,n);c.push(s)}))}));const d=t.filter((e=>"RC_CDN"===e.key)).map((e=>{const t=JSON.parse(e.value||"[]");return JSON.parse(t.cdn_uris)[0]}))[0];return{sessionId:r,remoteUserIds:i||[],remoteRTCUris:a,remoteMUCUris:s,remoteRTCTracks:c,remoteMCUTracks:o,remoteTracks:[...c,...o],CDNUris:d||{}}})(this._roomId,this._joinResData.kvEntries);this._sessionId=e,this._roomAnchorList=t,n.forEach((e=>{this._remoteTracks[e.getTrackId()]=e})),this._CDNUris=s,r.forEach((e=>{const t=e.msid.split("_")[0];this._roomAnchorRes[t]?this._roomAnchorRes[t].push(e):this._roomAnchorRes[t]=[e]})),i.forEach((e=>{const{mediaType:t,tag:r}=e,i=[this._roomId,r,t].join("_");this._roomRes[i]=e})),r.forEach((e=>{const t=_t(e);this._roomRes[t]=e}))}_assertRoomDestroyed(){if(this._destroyed){const e="This room has been destroyed. Please use `RCRTCClient.joinLivingRoomAsAudience` to catch another instance.";return S.warn(e),T.ROOM_HAS_BEEN_DESTROYED}}singalDataChange(e,t){var r;if(t!==this._roomId)return void S.warn(`singalDataChange -> not the current room data: data roomId: ${t}, current roomId: ${this._roomId}`);S.debug("singalDataChange -> singalData:",JSON.stringify(e||{}));const i=[],n=null===(r=e.filter((e=>"RC_CDN"===e.key))[0])||void 0===r?void 0:r.value;n&&this._diffCDNUris(JSON.parse(JSON.parse(n).cdn_uris)[0]),e.forEach((e=>{const{key:t,value:r,timestamp:n,uid:s}=e;if(-1!==t.indexOf("RC_RES_")){const e=JSON.parse(r||"{}"),t=JSON.parse(e.mcu_uris||"[]"),n=JSON.parse(e.uris||"[]");return i.push(...t),void this._diffAnchorResource(n,s)}if("RC_ANCHOR_LIST"===t){const e=JSON.parse(r||"[]"),{joinUserIds:t,leftUserIds:i}=this._diffAnchorList(e);t.length>0&&this._handleNewJoinedAnchor(t),i.length>0&&this._handleLeftedAnchor(i)}})),this._diffRoomResource(i)}_diffAnchorList(e){const t=e.filter((e=>this._roomAnchorList.indexOf(e)<0));return{leftUserIds:this._roomAnchorList.filter((t=>e.indexOf(t)<0)),joinUserIds:t}}_handleNewJoinedAnchor(e){this._roomAnchorList.push(...e),this._callAppListener("onAnchorJoin",e)}_handleLeftedAnchor(e){return R(this,void 0,void 0,(function*(){this._roomAnchorList=this._roomAnchorList.filter((t=>!(e.indexOf(t)>-1)));const t=[];e.forEach((e=>{t.push(...this.getRemoteTracksByUserId(e)),delete this._roomAnchorRes[e]})),t.length&&(yield this.unsubscribe(t),t.forEach((e=>delete this._remoteTracks[e.getTrackId()]))),this._callAppListener("onAnchorLeave",e)}))}_diffRoomResource(e){return R(this,void 0,void 0,(function*(){const t=[],r=[],i=[];e.forEach((e=>{const r=_t(e),{userId:n,tag:s,mediaType:o}=mt(r),a=[this._roomId,s,o].join("_");if(!this._remoteTracks[a]){const r=o===Fe.AUDIO_ONLY?new st(s,"",this._roomId):new ot(s,"",this._roomId);t.push(r),this._remoteTracks[a]=r,this._roomRes[r.getTrackId()]=e}i.push(a)})),Object.keys(this._remoteTracks).forEach((e=>{i.indexOf(e)<0&&this._remoteTracks[e].isMCUTrack()&&r.push(this._remoteTracks[e])})),t.length>0&&this._callAppListener("onTrackPublish",t),r.length>0&&this._onUserUnpublish(r,"onTrackUnpublish")}))}_diffAnchorResource(e,t){return R(this,void 0,void 0,(function*(){const r=this._roomAnchorRes[t]||(this._roomAnchorRes[t]=[]),{publishedList:i,unpublishedList:n,modifiedList:s}=gt(r,e);if(i.length){const e=r.map(_t),t=[],n=[];if(i.forEach((i=>{const s=_t(i),o=e.indexOf(s),{userId:a,tag:c,mediaType:d}=mt(s);o>-1?r[o]=i:r.push(i);let u=this._remoteTracks[s];this._roomRes[s]=i,u?u.isSubscribed()&&t.push(u):(u=d===Fe.AUDIO_ONLY?new st(c,a):new ot(c,a),this._remoteTracks[s]=u,n.push(u)),u.__innerSetRemoteMuted(0===i.state)})),t.length){const e=t.map((e=>e.getTrackId()));S.debug(`resub tracks -> ${JSON.stringify(e)}`);const{code:r}=yield I((()=>this._subscribeHandle(t,!0)));r!==T.SUCCESS&&S.error(`resub tracks failed -> code: ${r}, ids: ${JSON.stringify(e)}`)}this._callAppListener("onAnchorTrackPublish",n)}if(n.length){const e=n.map(_t);for(let t=r.length-1;t>=0;t-=1){const i=r[t];e.includes(_t(i))&&r.splice(t,1)}const t=n.map((e=>{const t=_t(e);return this._remoteTracks[t]}));yield this._onUserUnpublish(t,"onAnchorTrackUnpublish")}if(s.length){const e=r.map(_t);for(let t=0;t<s.length;t++){const i=s[t],n=_t(i),o=e.indexOf(n);r[o].state=i.state;const a=this._remoteTracks[n];a.__innerSetRemoteMuted(0===i.state),a.isAudioTrack()?this._callAppListener("onAudioMuteChange",a):this._callAppListener("onVideoMuteChange",a)}}}))}_onUserUnpublish(e,t){return R(this,void 0,void 0,(function*(){yield this.unsubscribe(e),e.forEach((e=>{this._subscribedList=this._subscribedList.filter((t=>t.track.getTrackId()!==e.getTrackId())),delete this._roomRes[e.getTrackId()],e.__innerDestroy(),delete this._remoteTracks[e.getTrackId()]})),this._callAppListener(t,e)}))}_callAppListener(e,...t){var r;const i=null===(r=this._appListener)||void 0===r?void 0:r[e];if(i)try{i(...t)}catch(e){S.error(e)}}_reTryExchange(){return R(this,void 0,void 0,(function*(){I((()=>R(this,void 0,void 0,(function*(){var e;const{reqBody:t}=yield this._createSubscribeParams(this._subscribedList,{},!0),r=yield this._exchangeHandle(t);if(r.code!==T.SUCCESS)return S.error(`reTryExchange failed: ${r.code}`),{code:r.code};const{sdp:i,resultCode:n}=r.data;if(n!==T.SUCCESS)return S.error(`reTryExchange failed: ${n}`),{code:n};this._pc.clearReTryExchangeTimer();const s=this._subscribedList.filter((e=>e.track.isMCUTrack()));if(s.length>0){const t=s[0].track.getTrackId(),r=null===(e=this._roomRes[t])||void 0===e?void 0:e.msid,n=[this._roomId,"RongCloudRTC"].join("_");i.sdp=i.sdp.replace(new RegExp(r,"g"),n)}const o=yield this._pc.setRemoteAnswer(i.sdp);return o!==T.SUCCESS?{code:o}:void 0}))))}))}_createSubscribeParams(e,t,r){return R(this,void 0,void 0,(function*(){const i=yield this._pc.createOffer(r),n={resolutionInfo:[]},s={min:0,max:0};Object.keys(t).forEach((e=>{const{mediaStream:r,tinyStream:o}=t[e];[r,o].forEach(((t,r)=>{var o;const a=1===r?[e,"tiny"].join("_"):e;i.sdp=null===(o=i.sdp)||void 0===o?void 0:o.replace(new RegExp(t.id,"g"),a);const c=t.getVideoTracks()[0];if(!c)return;const d=0===r,{width:u,height:l,frameRate:h}=d?ht(c):gr;n.resolutionInfo.push({trackId:c.id,simulcast:d?At.NORMAL:At.TINY,resolution:`${u}x${l}`});const p=Ge(u,l),_=We(h);s.min+=p.minBitrate*_,s.max+=p.maxBitrate*_}))}));return{reqBody:{sdp:i,switchstream:!1,newVersionFlag:!0,subscribeList:e.map((e=>({simulcast:e.subTiny?At.TINY:At.NORMAL,resolution:"",uri:this._roomRes[e.track.getTrackId()].uri})))},dynamicBitrate:s,offer:i}}))}_subscribeHandle(e,t=!1){var r;return R(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return{code:T.ROOM_HAS_BEEN_DESTROYED};if(!c("tracks",e,(()=>d(e)&&e.length>0&&e.every((e=>e instanceof nt||e.track instanceof nt))),!0))return{code:T.PARAMS_ERROR};const i=this._subscribedList.map((e=>Object.assign({},e))),n=e.map((e=>e instanceof nt?{track:e}:e));let s=!1;const o=[];return n.forEach((e=>{const t=e.track.getTrackId();o.push(t);const r=i.find((e=>e.track.getTrackId()===t));r&&r.subTiny===e.subTiny||(r?r.subTiny=e.subTiny:i.push(e),s=!0)})),s||t?(null===(r=this._polarisReport)||void 0===r||r.sendR2(qt.SUBSCRIBE,zt.BEGIN,o),this._updateSubListHandle(i,!0)):{code:T.SUCCESS}}))}_getReqHeaders(){const e=this._context.getCurrentId();return{"App-Key":this._context.getAppkey(),RoomId:e,Token:this._joinResData.token,RoomType:u.LIVE,UserId:e,"Session-Id":this._sessionId}}_exchangeHandle(e){return this._service.broadcastSubscribe(this._getReqHeaders(),e)}_updateSubListHandle(e,t=!1){var r;return R(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return{code:T.ROOM_HAS_BEEN_DESTROYED};if(!c("resources",e,(()=>d(e)&&e.every((e=>e instanceof nt||e.track instanceof nt))),!0))return{code:T.PARAMS_ERROR};let i=e.map((e=>e instanceof nt?{track:e}:Object.assign({},e)));const n={};i=i.filter((e=>{const t=e.track.getTrackId();return!n[t]&&(n[t]=!0)})).map((e=>Object.assign({},e)));const s=this._subscribedList.map((e=>Object.assign({},e)));if(!t){let e=!1;if(i.forEach((t=>{const r=s.findIndex((e=>e.track===t.track));if(-1===r)return void(e=!0);s.splice(r,1)[0].subTiny!==t.subTiny&&(e=!0)})),s.length&&(e=!0),!e)return{code:T.SUCCESS}}this._pc.clearReTryExchangeTimer(),this._pc.updateSubRemoteTracks(i.map((e=>e.track)));const{reqBody:o}=yield this._createSubscribeParams(i,{},!1),a=yield this._exchangeHandle(o);if(s.length){const e=[];s.forEach((t=>{e.push(t.track.getTrackId())})),null===(r=this._pc.reportParser)||void 0===r||r.clearLatestPacketsRecv(e)}if(a.code!==T.SUCCESS)return{code:a.code};const{sdp:u,resultCode:l,message:h,subscribedList:p}=a.data;if(l!==T.SUCCESS)return S.error("change subscribe list failed:",h,l),{code:l};i.forEach((e=>{const{track:t}=e;if(t.isMCUTrack()){const e=this._roomRes[t.getTrackId()].msid,{tag:r,userId:i}=mt(t.getTrackId()),n=[i,r].join("_");u.sdp=u.sdp.replace(new RegExp(e,"g"),n)}}));const _=yield this._pc.setRemoteAnswer(u.sdp);if(_!==T.SUCCESS)return{code:_};const m=null==p?void 0:p.map((e=>`${e.msid}_${e.mediaType}`)),f=i.filter((e=>{if(e.track.isMCUTrack()){const t=this._roomRes[e.track.getTrackId()],r=`${t.msid}_${t.mediaType}`;return m.includes(r)}return null==m?void 0:m.includes(e.track.getTrackId())})),v=null==f?void 0:f.map((e=>`${e.track.getTrackId()}`)),g=i.filter((e=>!(null==v?void 0:v.includes(e.track.getTrackId()))));for(const e in this._remoteTracks){const t=f.some((t=>t.track.getTrackId()===e));this._remoteTracks[e].__innerSetSubscribed(t)}return this._subscribedList.splice(0,this._subscribedList.length,...f),g.length?{code:T.SUCCESS,failedList:g}:{code:T.SUCCESS}}))}_diffCDNUris(e){return R(this,void 0,void 0,(function*(){if(this._CDNUris.url&&!e.url)return this._callAppListener("onCDNInfoDisable"),void(this._CDNUris=e);(!this._CDNUris||!this._CDNUris.url&&e.url)&&this._callAppListener("onCDNInfoEnable",{resolution:`W${e.w}_H${e.h}`,fps:`FPS_${e.fps}`});const t=this._CDNUris.w&&e.w&&this._CDNUris.w!==e.w,r=this._CDNUris.h&&e.h&&this._CDNUris.h!==e.h,i=this._CDNUris.fps&&e.fps&&this._CDNUris.fps!==e.fps;(t||r||i)&&this._callAppListener("onCDNInfoChange",{resolution:`W${e.w}_H${e.h}`,fps:`FPS_${e.fps}`}),this._CDNUris=e}))}_getCDNPlayUrl(e){return R(this,void 0,void 0,(function*(){const{w:t,h:r,fps:i}=e,n=this._initOptions.pullInnerCDNProtocol||mr.FLV,s=this._initOptions.pullInnerCDNUseHttps===fr.NOT_HTTPS?fr.NOT_HTTPS:fr.HTTPS;if(!this._CDNUris.url)return S.error(`cdn_uris url is empty, the anchor need to open or push CDN, code: ${T.CDN_RESOURCE_IS_EMPTY}`),{code:T.CDN_RESOURCE_IS_EMPTY};const o={"App-Key":this._context.getAppkey(),Token:this._joinResData.token,RoomId:this.getRoomId(),UserId:this._context.getCurrentId(),SessionId:this.getSessionId()},a=[];t&&a.push(`w=${t}`),r&&a.push(`h=${r}`),i&&a.push(`fps=${i}`),a.push(`kind=${n}`),a.push(`is_https=${s}`);const c=a.join("&");let d=`${this._CDNUris.url}?`;c&&(d+=c);const{code:u,res:l}=yield this._service.getCDNResourceInfo(o,d);return u!==T.SUCCESS?(S.error(`getCDNPlayUrl failed: ${u}`),{code:u}):(S.info(`getCDNPlayUrl success: ${null==l?void 0:l.data.pull_url}`),{code:u,CDNPlayUrl:null==l?void 0:l.data.pull_url})}))}getCDNPlayUrl(e,t){return R(this,void 0,void 0,(function*(){if(e&&!Tt(e))return S.error("`resolution` is invalid"),{code:T.PARAMS_ERROR};if(t&&!Ct(t))return S.error("`fps` is invalid"),{code:T.PARAMS_ERROR};const{width:r,height:i}=e?St(e):{width:null,height:null},n=t?Et(t):null,s={};return r&&(s.w=r),i&&(s.h=i),n&&(s.fps=n),this._getCDNPlayUrl(s)}))}subscribe(e){return R(this,void 0,void 0,(function*(){return I((()=>this._subscribeHandle(e,!1)))}))}__unsubscribe(e){var t;return R(this,void 0,void 0,(function*(){if(!c("tracks",e,(()=>d(e)&&e.length>0&&e.every((e=>e instanceof nt))),!0))return S.error(`unsubscribe failed, tracks is invalid -> roomId: ${this._roomId}`),{code:T.PARAMS_ERROR};const r=this._subscribedList.map((e=>Object.assign({},e))).filter((t=>!e.includes(t.track)));return null===(t=this._polarisReport)||void 0===t||t.sendR2(qt.SUBSCRIBE,zt.END,e.map((e=>e.getTrackId()))),this._updateSubListHandle(r,!1)}))}unsubscribe(e){return R(this,void 0,void 0,(function*(){return I((()=>this.__unsubscribe(e)))}))}__destroy(e){var t;return R(this,void 0,void 0,(function*(){this._destroyed||(this._destroyed=!0,null===(t=this._audioLevelReport)||void 0===t||t.clearAudioLevelReportTimer(),e&&(yield this._context.quitLivingRoomAsAudience(this._roomId)),yield this._service.broadcastExit(this._getReqHeaders()),this._pc.destroy(),this._polarisReport=null,this._context.onrtcdatachange=()=>{})}))}getRemoteTrack(e){return this._remoteTracks[e]}__getPC(){return this._pc}getLocalTrack(e){return{}}__onReconnected(){return R(this,void 0,void 0,(function*(){const{code:e}=yield this._context.joinLivingRoomAsAudience(this._roomId,u.LIVE);e!==i.SUCCESS&&S.error("join living room error when on reconnected")}))}registerRoomEventListener(e){this._appListener=e}onAudioLevelChange(e,t){var r;null===(r=this._audioLevelReport)||void 0===r||r.clearAudioLevelReportTimer(),this._audioLevelReport=new Zt(this),this._audioLevelReport.onAudioLevelChange(e,t||1e3)}registerReportListener(e){var t;null===(t=this._pc)||void 0===t||t.registerReportListener(e)}getRoomId(){return this._roomId}getCrtUserId(){return this._context.getCurrentId()}getSessionId(){return this._sessionId}getRemoteUserIds(){return this._roomAnchorList}getRemoteTracksByUserId(e){const t=[];for(const r in this._remoteTracks){const i=this._remoteTracks[r];i.getUserId()===e&&t.push(i)}return t}getRemoteTracks(){const e=[],t=[];for(const e in this._remoteTracks){if(2===t.length)break;const r=this._remoteTracks[e];r.isMCUTrack()&&t.push(r)}return this._roomAnchorList.forEach((t=>{e.push(...this.getRemoteTracksByUserId(t))})),[...t,...e]}getRemoteRTCTracks(){const e=[];for(const t in this._remoteTracks){const r=this._remoteTracks[t];r.isMCUTrack()||e.push(r)}return e}getRemoteMCUTracks(){const e=[];for(const t in this._remoteTracks){const r=this._remoteTracks[t];r.isMCUTrack()&&e.push(r)}return e}getCDNInfo(){return this._CDNUris.w?{resolution:`W${this._CDNUris.w}_H${this._CDNUris.h}`,fps:`FPS_${this._CDNUris.fps}`,CDNEnable:this._CDNUris.enableInnerCDN}:{CDNEnable:!1}}}const Sr=(e,t)=>{const r=[];return r[0]=(null==t?void 0:t.withoutAudio)?void 0:e.getAudioTracks()[0],r[1]=(null==t?void 0:t.withoutVideo)?void 0:e.getVideoTracks()[0],r};class Tr{constructor(e,t,r){this._context=e,this._runtime=t,this._options=r,this._crtRoom=null,this._audience=null,this._crtAudienceLivingRoom=null,Ht.setSdpSemantics(r.sdpSemantics||"plan-b"),this._service=new pr(this._runtime,this._context,this._options.mediaServer,this._options.timeout),this._context.onconnectionstatechange=this._onIMStatusChange.bind(this),this._context.ondisconnect=this._onIMDisconnect.bind(this),this._context.ondestroy=this._onIMUninit.bind(this),this._context.onmessage=this._handleMessage.bind(this)}_handleMessage(e){var t;return e.conversationType===o.RTC_ROOM&&(null===(t=this._crtRoom)||void 0===t||t.__parseInnerMessage(e),!0)}getCurrentId(){return this._context.getCurrentId()}joinRTCRoom(e,t){return I((()=>this._joinRTCRoom(e,t)))}_joinRTCRoom(e,t){return R(this,void 0,void 0,(function*(){if(Pt(this._context.getNaviInfo()))return{code:T.PACKAGE_ENVIRONMENT_ERROR};if(!c("roomId",e,m,!0))return{code:T.PARAMS_ERROR};if(this._crtRoom)return{code:T.REPERT_JOIN_ROOM};if(this._context.getConnectionStatus()!==n.CONNECTED)return{code:T.SIGNAL_DISCONNECTED};if(!this._service.getNaviMS().length)return{code:T.NOT_OPEN_VIDEO_AUDIO_SERVER};S.debug(`joinRoom -> roomId: ${e}; joinType: ${t||f.KICK}`);const{code:r,data:s}=yield this._context.joinRTCRoom(e,u.RTC,void 0,t);if(r!==i.SUCCESS){S.error(`joinRoom failed -> code: ${r}`);return{code:r===C.JOIN_REFUSED?T.SIGNAL_JOIN_RTC_ROOM_REFUSED:r}}S.debug(`joinRoom success -> userId: ${this._context.getCurrentId()}, roomId: ${e}, data: ${JSON.stringify(s)}`);const o=new lr(this._context,this._runtime,e,s,this._service,this._options,this._releaseCrtRoomObj.bind(this));return this._crtRoom=o,{room:o,code:T.SUCCESS,userIds:o.getRemoteUserIds(),tracks:o.getRemoteTracks()}}))}joinLivingRoom(e,t){return I((()=>this._joinLivingRoom(e,t)))}_joinLivingRoom(e,t){return R(this,void 0,void 0,(function*(){if(Pt(this._context.getNaviInfo()))return{code:T.PACKAGE_ENVIRONMENT_ERROR};if(!c("roomId",e,m,!0)||!c("livingType",t,(e=>e===_r.AUDIO||e===_r.VIDEO)))return{code:T.PARAMS_ERROR};if(this._crtRoom)return{code:T.REPERT_JOIN_ROOM};if(this._context.getConnectionStatus()!==n.CONNECTED)return{code:T.SIGNAL_DISCONNECTED};if(!this._service.getNaviMS().length)return{code:T.NOT_OPEN_VIDEO_AUDIO_SERVER};S.debug(`joinRoom, roomId: ${e}`);const{code:r,data:s}=yield this._context.joinRTCRoom(e,u.LIVE,t);if(r!==i.SUCCESS)return S.error(`joinRoom failed -> code: ${r}`),{code:r};S.debug(`JoinRoom success -> userId: ${this._context.getCurrentId()}, roomId: ${e}, data: ${JSON.stringify(s)}`);const o=new ur(this._context,this._runtime,e,s,this._service,this._options,this._releaseCrtRoomObj.bind(this),t,!1);this._crtRoom=o;const a={room:o,code:T.SUCCESS,userIds:o.getRemoteUserIds(),tracks:o.getRemoteTracks()};return o.__getCDNPushMode()===dr.MANUAL&&Object.assign(a,{CDNEnable:o.__getCDNEnable()}),a}))}getAudienceClient(){return this._audience||(this._audience=new vr(this._context,this._runtime,this._options)),this._audience}_onIMStatusChange(e){S.debug(`signal server connection state change: ${e}`),e===n.CONNECTED&&this._crtRoom&&this._crtRoom.__onReconnected()}_onIMDisconnect(){S.debug("TODO -> on IM disconnect")}_onIMUninit(){S.debug("TODO -> on IM client ondestroy")}leaveRoom(e){return I((()=>this._leaveRoom(e)))}_leaveRoom(e){return R(this,void 0,void 0,(function*(){return this._crtRoom?(yield this._crtRoom.__destroy(!0),S.debug(`quitRTCRoom -> userId: ${this._context.getCurrentId()} , roomId: ${this._crtRoom.getRoomId()}`),this._crtRoom=null,{code:T.SUCCESS}):{code:T.SUCCESS}}))}_releaseCrtRoomObj(){this._crtRoom=null}_getMediaStream(e,t="getUserMedia"){return R(this,void 0,void 0,(function*(){try{const r=yield navigator.mediaDevices[t](e);return{code:T.SUCCESS,stream:r}}catch(e){if("Permission denied"===e.message)return{code:T.PERMISSION_DENIED};S.error(`get user media failed -> ${e.message}`)}return{code:"getUserMedia"===t?T.GET_USER_MEDIA_FAILED:T.GET_DISPLAY_MEDIA_FAILED}}))}createMicrophoneAudioTrack(e="RongCloudRTC",t){return R(this,void 0,void 0,(function*(){if(!dt(e))return{code:T.INVALID_TAGS};const r=this._context.getCurrentId();if(!r)return{code:T.INVALID_USER_ID};const{stream:i,code:n}=yield this._getMediaStream({audio:{deviceId:null==t?void 0:t.micphoneId,sampleRate:null==t?void 0:t.sampleRate}});if(n!==T.SUCCESS)return{code:n};const s=i.getAudioTracks()[0];return{code:n,track:new tt(e,r,s)}}))}createCameraVideoTrack(e="RongCloudRTC",t){return R(this,void 0,void 0,(function*(){if(!dt(e))return{code:T.INVALID_TAGS};const r=this._context.getCurrentId();if(!r)return{code:T.INVALID_USER_ID};const i=Tt(null==t?void 0:t.resolution)?t.resolution:Be.W640_H480,{width:n,height:s}=St(i),{stream:o,code:a}=yield this._getMediaStream({video:{deviceId:null==t?void 0:t.cameraId,frameRate:Et((null==t?void 0:t.frameRate)||Ve.FPS_15),width:n,height:s,facingMode:null==t?void 0:t.faceMode}});if(a!==T.SUCCESS)return{code:a};const c=o.getVideoTracks()[0];return{code:a,track:new rt(e,r,c)}}))}createMicrophoneAndCameraTracks(e="RongCloudRTC",t){var r,i,n,s,o,a;return R(this,void 0,void 0,(function*(){const c=[];if(!dt(e))return{code:T.INVALID_TAGS,tracks:c};const d=this._context.getCurrentId();if(!d)return{code:T.INVALID_USER_ID,tracks:c};const u=Tt(null===(r=null==t?void 0:t.video)||void 0===r?void 0:r.resolution)?t.video.resolution:Be.W640_H480,{width:l,height:h}=St(u),{stream:p,code:_}=yield this._getMediaStream({video:{deviceId:null===(i=null==t?void 0:t.video)||void 0===i?void 0:i.cameraId,frameRate:Et((null===(n=null==t?void 0:t.video)||void 0===n?void 0:n.frameRate)||Ve.FPS_15),width:l,height:h,facingMode:null===(s=null==t?void 0:t.video)||void 0===s?void 0:s.faceMode},audio:{deviceId:null===(o=null==t?void 0:t.audio)||void 0===o?void 0:o.micphoneId,sampleRate:null===(a=null==t?void 0:t.audio)||void 0===a?void 0:a.sampleRate}});return _!==T.SUCCESS||p.getTracks().forEach((t=>{"video"===t.kind?c.push(new rt(e,d,t)):c.unshift(new tt(e,d,t))})),{code:_,tracks:c}}))}createScreenVideoTrack(e="screenshare",t){return R(this,void 0,void 0,(function*(){if(!dt(e))return{code:T.INVALID_TAGS};const r=this._context.getCurrentId();if(!r)return{code:T.INVALID_USER_ID};if(!kt())return{code:T.BROWSER_NOT_SUPPORT};const i=/Electron/.test(navigator.userAgent);if(i&&!(null==t?void 0:t.chromeMediaSourceId))return{code:T.PARAMS_ERROR};const n=Tt(null==t?void 0:t.resolution)?t.resolution:Be.W1280_H720,{width:s,height:o}=St(n),a=i?{mandatory:{chromeMediaSourceId:t.chromeMediaSourceId,chromeMediaSource:"desktop",minWidth:s,maxWidth:s,minHeight:o,maxHeight:o}}:{frameRate:Et((null==t?void 0:t.frameRate)||Ve.FPS_15),width:s,height:o},{stream:c,code:d}=yield this._getMediaStream({video:a,audio:!1},i?"getUserMedia":"getDisplayMedia");if(d!==T.SUCCESS)return{code:d};const u=c.getVideoTracks()[0];return{code:d,track:new it(e,r,u)}}))}createLocalAudioTrack(e,t){return R(this,void 0,void 0,(function*(){if(!dt(e))return{code:T.INVALID_TAGS};if(!t||"[object MediaStreamTrack]"!==t.toString()||"audio"!==t.kind)return{code:T.CREATE_CUSTOM_TRACK_FAILED};const r=this._context.getCurrentId();return r?{code:T.SUCCESS,track:new ze(e,r,t)}:{code:T.INVALID_USER_ID}}))}createLocalVideoTrack(e,t){return R(this,void 0,void 0,(function*(){if(!dt(e))return{code:T.INVALID_TAGS};if(!t||"[object MediaStreamTrack]"!==t.toString()||"video"!==t.kind)return{code:T.CREATE_CUSTOM_TRACK_FAILED};const r=this._context.getCurrentId();return r?{code:T.SUCCESS,track:new Qe(e,r,t)}:{code:T.INVALID_USER_ID}}))}createLocalFileTracks(e,t,r){return R(this,void 0,void 0,(function*(){if(!dt(e))return{code:T.INVALID_TAGS,tracks:[]};if(!It())return{code:T.BROWSER_NOT_SUPPORT,tracks:[]};const i=t instanceof File?URL.createObjectURL(t):t;if(!l(i)&&!/^blob:/.test(i))return S.warn(`createLocalFileTracks failed: params error -> url: ${i}`),{code:T.PARAMS_ERROR,tracks:[]};const n=this._context.getCurrentId();return n?new Promise((t=>{const s=document.createElement("video");(null==r?void 0:r.withoutAudio)&&(s.muted=!0),s.onloadedmetadata=()=>{const o=[];let a;try{const e=s.mozCaptureStream?"mozCaptureStream":"captureStream";a=s[e]()}catch(e){S.error(`create RCLocalFileTrack failed, captureSteam error. -> url: ${i}`),S.error(e),t({code:T.CREATE_FILE_TRACK_FAILED,tracks:o})}const[c,d]=Sr(a,r);c&&o.push(new et(e,n,c,s)),d&&o.push(new Ze(e,n,d,s)),0===o.length&&(s.pause(),s.src=""),s.onerror=null,t({code:T.SUCCESS,tracks:o})},s.onerror=()=>{S.error(`create RCLocalFileTrack failed -> url: ${i}`),t({code:T.CREATE_FILE_TRACK_FAILED,tracks:[]})},s.src=i,s.loop=!0,s.play()})):{code:T.INVALID_USER_ID,tracks:[]}}))}createLocalTracks(e,t,r){return R(this,void 0,void 0,(function*(){const i=[];if(!dt(e))return{code:T.INVALID_TAGS,tracks:i};if(!(t instanceof MediaStream))return{code:T.PARAMS_ERROR,tracks:i};const n=this._context.getCurrentId();if(!n)return{code:T.INVALID_USER_ID,tracks:i};const[s,o]=Sr(t,r);return s&&i.push(new ze(e,n,s)),o&&i.push(new Qe(e,n,o)),{code:T.SUCCESS,tracks:i}}))}joinLivingRoomAsAudience(e,t){return R(this,void 0,void 0,(function*(){if(Pt(this._context.getNaviInfo()))return{code:T.PACKAGE_ENVIRONMENT_ERROR};if(!c("roomId",e,m,!0)||!c("livingType",t,(e=>e===_r.AUDIO||e===_r.VIDEO)))return{code:T.PARAMS_ERROR};if(this._crtAudienceLivingRoom)return{code:T.REPERT_JOIN_ROOM};if(!this._service.getNaviMS().length)return{code:T.NOT_OPEN_VIDEO_AUDIO_SERVER};const{code:r,data:n}=yield this._context.joinLivingRoomAsAudience(e,u.LIVE,t);if(r!==i.SUCCESS)return S.error("audienceJoinLivingRoomError:",r),{code:T.SIGNAL_AUDIENCE_JOIN_ROOM_FAILED};S.info(`joinLivingRoomAsAudience success, room data: ${JSON.stringify(n)}`);const s=new Rr(this._context,this._runtime,this._options,e,n,t);return this._crtAudienceLivingRoom=s,{room:s,code:T.SUCCESS,userIds:s.getRemoteUserIds(),RTCTracks:s.getRemoteRTCTracks(),MCUTracks:s.getRemoteMCUTracks(),CDNUris:s.getCDNInfo()}}))}leaveLivingRoomAsAudience(e){return R(this,void 0,void 0,(function*(){return this._crtAudienceLivingRoom?this._crtAudienceLivingRoom!==e?{code:T.PARAMS_ERROR}:(yield this._crtAudienceLivingRoom.__destroy(!0),this._crtAudienceLivingRoom=null,{code:T.SUCCESS}):{code:T.SUCCESS}}))}upgradeToAnchorRoom(e){return R(this,void 0,void 0,(function*(){if(!c("room._roomId",e._roomId,m,!0))return{code:T.PARAMS_ERROR};if(this._crtRoom)return{code:T.REPERT_JOIN_ROOM};const{code:t,data:r}=yield this._context.rtcIdentityChange(e._roomId,v.ViewerToAnchor,e._livingType);if(t!==i.SUCCESS)return S.error("change room identity error",t),{code:T.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED};yield this._crtAudienceLivingRoom.__destroy(!1);const n=new ur(this._context,this._runtime,e._roomId,r,this._service,this._options,this._releaseCrtRoomObj.bind(this),e._livingType,!0);return this._crtRoom=n,this._crtAudienceLivingRoom=null,{room:n,code:T.SUCCESS}}))}downgradeToAudienceRoom(e){return R(this,void 0,void 0,(function*(){if(!c("room._roomId",e._roomId,m,!0))return{code:T.PARAMS_ERROR};if(this._crtAudienceLivingRoom)return{code:T.REPERT_JOIN_ROOM};const{code:t,data:r}=yield this._context.rtcIdentityChange(e._roomId,v.AnchorToViewer,e.getLivingType());if(t!==i.SUCCESS)return S.error("change room identity error",t),{code:T.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED};S.info(`downgradeToAudienceRoom success, room data: ${JSON.stringify(r)}`);const n=new Rr(this._context,this._runtime,this._options,e._roomId,r,e.getLivingType());return this._crtAudienceLivingRoom=n,this._crtRoom.__destroy(!1),this._crtRoom=null,{room:n,code:T.SUCCESS,userIds:n.getRemoteUserIds(),RTCTracks:n.getRemoteRTCTracks(),MCUTracks:n.getRemoteMCUTracks(),CDNUris:n.getCDNInfo()}}))}getJoinedRoomInfo(){return R(this,void 0,void 0,(function*(){const{code:e,data:t}=yield this._context.getRTCJoinedUserInfo(this._context.getCurrentId());return e!==i.SUCCESS?(S.error("getJoinedUserInfo error",e),{code:T.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED}):{code:T.SUCCESS,data:t}}))}}var Cr;!function(e){e[e.SERVER_KICK=1]="SERVER_KICK",e[e.OTHER_KICK=2]="OTHER_KICK"}(Cr||(Cr={}));const Er={tag:"RCRTC",verify:e=>"browser"!==e.tag?(S.error(`RCRTC Plugin is not support the runtime '${e.tag}'`),!1):ut?(g.add("plugin-rtc","5.2.4"),!!g.validEngine(">=4.5.1")||(S.error(`The current engine version '${g.getInfo().engine}' error, plugin-rtc required engine version at least '>=4.5.1'.`),!1)):(S.error("Please use the https protocol or use `http://localhost` to open the page!"),!1),setup:(e,t,i={})=>(S.setLogLevel(i.logLevel),S.setLogStdout(i.logStdout),S.warn("RCRTC Version: 5.2.4, Commit: d2c309074e678b96ebd403c0967994360e8b389c"),S.warn(`browserInfo.browser -> ${yt.browser}`),S.warn(`browserInfo.supportsUnifiedPlan -> ${yt.supportsUnifiedPlan}`),S.warn(`browserInfo.version -> ${yt.version}`),s("options.mediaServer",i.mediaServer,(e=>!(!l(e)||"https:"===location.protocol&&!/^https/.test(e)))),s("options.timeout",i.timeout,(e=>r(e)&&e>=5e3&&e<=3e4)),s("options.pingGap",i.pingGap,(e=>r(e)&&e>=3e3&&e<=1e4)),new Tr(e,t,i))},yr={DEFAULT:"RongCloudRTC"},Ir={transResolution:St,transFrameRate:Et,parseTrackId:mt,ifSupportLocalFileTrack:It,ifSupportScreenShare:kt};export{rr as BackgroundPictureFillMode,ir as MixLayoutMode,nr as MixVideoRenderMode,tr as RCAbstractRoom,vr as RCAudienceClient,Rr as RCAudienceLivingRoom,rt as RCCameraVideoTrack,Ve as RCFrameRate,fr as RCInnerCDNPullIsHttps,mr as RCInnerCDNPullKind,Cr as RCKickReason,ur as RCLivingRoom,_r as RCLivingType,ze as RCLocalAudioTrack,et as RCLocalFileAudioTrack,Xe as RCLocalFileTrack,Ze as RCLocalFileVideoTrack,qe as RCLocalTrack,Qe as RCLocalVideoTrack,or as RCMCUConfigBuilder,Fe as RCMediaType,tt as RCMicphoneAudioTrack,Tr as RCRTCClient,T as RCRTCCode,Qt as RCRTCLiveRole,Dt as RCRTCPingResult,lr as RCRTCRoom,st as RCRemoteAudioTrack,nt as RCRemoteTrack,ot as RCRemoteVideoTrack,Be as RCResolution,it as RCScreenVideoTrack,yr as RCTag,Ke as RCTrack,Ye as device,Ir as helper,Er as installer};
15
+ ***************************************************************************** */function S(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))}const C=new e("RCRTC");var T,I;!function(e){e[e.SUCCESS=1e4]="SUCCESS",e[e.SIGNAL_DISCONNECTED=5e4]="SIGNAL_DISCONNECTED",e[e.PARAMS_ERROR=50001]="PARAMS_ERROR",e[e.REPERT_JOIN_ROOM=50002]="REPERT_JOIN_ROOM",e[e.NOT_IN_ROOM=50003]="NOT_IN_ROOM",e[e.SERVICE_INVALID=50004]="SERVICE_INVALID",e[e.RTC_TOKEN_INVALID=50006]="RTC_TOKEN_INVALID",e[e.SIGNAL_ERROR=53001]="SIGNAL_ERROR",e[e.CREATE_OFFER_FAILED=53003]="CREATE_OFFER_FAILED",e[e.REQUEST_FAILED=53004]="REQUEST_FAILED",e[e.MCU_SERVER_NOT_FOUND=53005]="MCU_SERVER_NOT_FOUND",e[e.BROADCAST_SUB_LIST_NOT_EMPTY=53007]="BROADCAST_SUB_LIST_NOT_EMPTY",e[e.ROOM_HAS_BEEN_DESTROYED=53008]="ROOM_HAS_BEEN_DESTROYED",e[e.NOT_OPEN_VIDEO_AUDIO_SERVER=53009]="NOT_OPEN_VIDEO_AUDIO_SERVER",e[e.GET_USER_MEDIA_FAILED=53010]="GET_USER_MEDIA_FAILED",e[e.GET_DISPLAY_MEDIA_FAILED=53011]="GET_DISPLAY_MEDIA_FAILED",e[e.PERMISSION_DENIED=53012]="PERMISSION_DENIED",e[e.CREATE_CUSTOM_TRACK_FAILED=53013]="CREATE_CUSTOM_TRACK_FAILED",e[e.INVALID_TAGS=53014]="INVALID_TAGS",e[e.INVALID_USER_ID=53015]="INVALID_USER_ID",e[e.CREATE_FILE_TRACK_FAILED=53016]="CREATE_FILE_TRACK_FAILED",e[e.INVALID_FILE_INSTANCE=53017]="INVALID_FILE_INSTANCE",e[e.SET_REMOTE_DESCRIPTION_FAILED=53018]="SET_REMOTE_DESCRIPTION_FAILED",e[e.BROWSER_NOT_SUPPORT=53019]="BROWSER_NOT_SUPPORT",e[e.TRACK_NOT_READY=53020]="TRACK_NOT_READY",e[e.VIDEO_TRACK_MISS_MEDIA_ELEMENT=53021]="VIDEO_TRACK_MISS_MEDIA_ELEMENT",e[e.TRACK_PLAY_ERROR=53022]="TRACK_PLAY_ERROR",e[e.SIGNAL_AUDIENCE_JOIN_ROOM_FAILED=53023]="SIGNAL_AUDIENCE_JOIN_ROOM_FAILED",e[e.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED=53024]="SIGNAL_ROOM_CHANGE_IDENTITY_FAILED",e[e.PACKAGE_ENVIRONMENT_ERROR=53025]="PACKAGE_ENVIRONMENT_ERROR",e[e.PUBLISH_TRACK_LIMIT_EXCEEDED=53026]="PUBLISH_TRACK_LIMIT_EXCEEDED",e[e.CDN_RESOURCE_IS_EMPTY=53027]="CDN_RESOURCE_IS_EMPTY",e[e.SIGNAL_JOIN_RTC_ROOM_REFUSED=53028]="SIGNAL_JOIN_RTC_ROOM_REFUSED",e[e.NO_PERMISSION_TO_USE_REQUESTED_DEVICE=53029]="NO_PERMISSION_TO_USE_REQUESTED_DEVICE",e[e.THE_FUNCTION_IS_DISABLED_IN_PKROOM=53030]="THE_FUNCTION_IS_DISABLED_IN_PKROOM"}(T||(T={})),function(e){e[e.JOIN_REFUSED=40032]="JOIN_REFUSED"}(I||(I={}));class E{constructor(){this.queue=[],this.locked=!1}checkToStart(){return S(this,void 0,void 0,(function*(){if(0===this.queue.length||this.locked)return;this.locked=!0;const{resolve:e,task:t,reject:r}=this.queue.shift();let i;try{i=yield t(),e(i)}catch(e){r(e)}this.locked=!1,this.checkToStart()}))}push(e){const t=new Promise(((t,r)=>{this.queue.push({resolve:t,task:e,reject:r})}));return this.checkToStart(),t}}const y=new E,k=e=>y.push(e);let b=!0,P=!0;function O(e,t,r){const i=e.match(t);return i&&i.length>=r&&parseInt(i[r],10)}function L(e,t,r){if(!e.RTCPeerConnection)return;const i=e.RTCPeerConnection.prototype,n=i.addEventListener;i.addEventListener=function(e,i){if(e!==t)return n.apply(this,arguments);const s=e=>{const t=r(e);t&&(i.handleEvent?i.handleEvent(t):i(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(i,s),n.apply(this,[e,s])};const s=i.removeEventListener;i.removeEventListener=function(e,r){if(e!==t||!this._eventMap||!this._eventMap[t])return s.apply(this,arguments);if(!this._eventMap[t].has(r))return s.apply(this,arguments);const i=this._eventMap[t].get(r);return this._eventMap[t].delete(r),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,s.apply(this,[e,i])},Object.defineProperty(i,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function N(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(b=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function D(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(P=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function A(){if("object"==typeof window){if(b)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function M(e,t){P&&console.warn(e+" is deprecated, please use "+t+" instead.")}function x(e){return"[object Object]"===Object.prototype.toString.call(e)}function U(e){return x(e)?Object.keys(e).reduce((function(t,r){const i=x(e[r]),n=i?U(e[r]):e[r],s=i&&!Object.keys(n).length;return void 0===n||s?t:Object.assign(t,{[r]:n})}),{}):e}function w(e,t,r){t&&!r.has(t.id)&&(r.set(t.id,t),Object.keys(t).forEach((i=>{i.endsWith("Id")?w(e,e.get(t[i]),r):i.endsWith("Ids")&&t[i].forEach((t=>{w(e,e.get(t),r)}))})))}function $(e,t,r){const i=r?"outbound-rtp":"inbound-rtp",n=new Map;if(null===t)return n;const s=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&s.push(e)})),s.forEach((t=>{e.forEach((r=>{r.type===i&&r.trackId===t.id&&w(e,r,n)}))})),n}const j=A;function V(e,t){const r=e&&e.navigator;if(!r.mediaDevices)return;const i=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((r=>{if("require"===r||"advanced"===r||"mediaSource"===r)return;const i="object"==typeof e[r]?e[r]:{ideal:e[r]};void 0!==i.exact&&"number"==typeof i.exact&&(i.min=i.max=i.exact);const n=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==i.ideal){t.optional=t.optional||[];let e={};"number"==typeof i.ideal?(e[n("min",r)]=i.ideal,t.optional.push(e),e={},e[n("max",r)]=i.ideal,t.optional.push(e)):(e[n("",r)]=i.ideal,t.optional.push(e))}void 0!==i.exact&&"number"!=typeof i.exact?(t.mandatory=t.mandatory||{},t.mandatory[n("",r)]=i.exact):["min","max"].forEach((e=>{void 0!==i[e]&&(t.mandatory=t.mandatory||{},t.mandatory[n(e,r)]=i[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},n=function(e,n){if(t.version>=61)return n(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=i(e.audio)}if(e&&"object"==typeof e.video){let s=e.video.facingMode;s=s&&("object"==typeof s?s:{ideal:s});const o=t.version<66;if(s&&("user"===s.exact||"environment"===s.exact||"user"===s.ideal||"environment"===s.ideal)&&(!r.mediaDevices.getSupportedConstraints||!r.mediaDevices.getSupportedConstraints().facingMode||o)){let t;if(delete e.video.facingMode,"environment"===s.exact||"environment"===s.ideal?t=["back","rear"]:"user"!==s.exact&&"user"!==s.ideal||(t=["front"]),t)return r.mediaDevices.enumerateDevices().then((r=>{let o=(r=r.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!o&&r.length&&t.includes("back")&&(o=r[r.length-1]),o&&(e.video.deviceId=s.exact?{exact:o.deviceId}:{ideal:o.deviceId}),e.video=i(e.video),j("chrome: "+JSON.stringify(e)),n(e)}))}e.video=i(e.video)}return j("chrome: "+JSON.stringify(e)),n(e)},s=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(r.getUserMedia=function(e,t,i){n(e,(e=>{r.webkitGetUserMedia(e,t,(e=>{i&&i(s(e))}))}))}.bind(r),r.mediaDevices.getUserMedia){const e=r.mediaDevices.getUserMedia.bind(r.mediaDevices);r.mediaDevices.getUserMedia=function(t){return n(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException("","NotFoundError");return e}),(e=>Promise.reject(s(e))))))}}}function B(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function H(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",(r=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===r.track.id)):{track:r.track};const n=new Event("track");n.track=r.track,n.receiver=i,n.transceiver={receiver:i},n.streams=[t.stream],this.dispatchEvent(n)})),t.stream.getTracks().forEach((r=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===r.id)):{track:r};const n=new Event("track");n.track=r,n.receiver=i,n.transceiver={receiver:i},n.streams=[t.stream],this.dispatchEvent(n)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else L(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function F(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const r=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){let n=r.apply(this,arguments);return n||(n=t(this,e),this._senders.push(n)),n};const i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){i.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],r.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function K(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,r,i]=arguments;if(arguments.length>0&&"function"==typeof e)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof e))return t.apply(this,[]);const n=function(e){const t={};return e.result().forEach((e=>{const r={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach((t=>{r[t]=e.stat(t)})),t[r.id]=r})),t},s=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const i=function(e){r(s(n(e)))};return t.apply(this,[i,e])}return new Promise(((e,r)=>{t.apply(this,[function(t){e(s(n(t)))},r])})).then(r,i)}}function G(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=r.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>$(t,e.track,!0)))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),L(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>$(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,r,i;return this.getSenders().forEach((r=>{r.track===e&&(t?i=!0:t=r)})),this.getReceivers().forEach((t=>(t.track===e&&(r?i=!0:r=t),t.track===e))),i||t&&r?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():r?r.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function J(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,r){if(!r)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const i=t.apply(this,arguments);return this._shimmedLocalStreams[r.id]?-1===this._shimmedLocalStreams[r.id].indexOf(i)&&this._shimmedLocalStreams[r.id].push(i):this._shimmedLocalStreams[r.id]=[r,i],i};const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();r.apply(this,arguments);const i=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(i)};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],i.apply(this,arguments)};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const r=this._shimmedLocalStreams[t].indexOf(e);-1!==r&&this._shimmedLocalStreams[t].splice(r,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),n.apply(this,arguments)}}function W(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return J(e);const r=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=r.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const r=new e.MediaStream(t.getTracks());this._streams[t.id]=r,this._reverseStreams[r.id]=t,t=r}i.apply(this,[t])};const n=e.RTCPeerConnection.prototype.removeStream;function s(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],n=e._streams[i.id];r=r.replace(new RegExp(n.id,"g"),i.id)})),new RTCSessionDescription({type:t.type,sdp:r})}function o(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],n=e._streams[i.id];r=r.replace(new RegExp(i.id,"g"),n.id)})),new RTCSessionDescription({type:t.type,sdp:r})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},n.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,r){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const i=[].slice.call(arguments,1);if(1!==i.length||!i[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");const n=this.getSenders().find((e=>e.track===t));if(n)throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const s=this._streams[r.id];if(s)s.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const i=new e.MediaStream([t]);this._streams[r.id]=i,this._reverseStreams[i.id]=r,this.addStream(i)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?r.apply(this,[t=>{const r=s(this,t);e[0].apply(null,[r])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):r.apply(this,arguments).then((e=>s(this,e)))}};e.RTCPeerConnection.prototype[t]=i[t]}));const a=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=o(this,arguments[0]),a.apply(this,arguments)):a.apply(this,arguments)};const c=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=c.get.apply(this);return""===e.type?e:s(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((r=>{this._streams[r].getTracks().find((t=>e.track===t))&&(t=this._streams[r])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Y(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]}))}function q(e,t){L(e,"negotiationneeded",(e=>{const r=e.target;if(!(t.version<72||r.getConfiguration&&"plan-b"===r.getConfiguration().sdpSemantics)||"stable"===r.signalingState)return e}))}var z=Object.freeze({__proto__:null,shimMediaStream:B,shimOnTrack:H,shimGetSendersWithDtmf:F,shimGetStats:K,shimSenderReceiverGetStats:G,shimAddTrackRemoveTrackWithNative:J,shimAddTrackRemoveTrack:W,shimPeerConnection:Y,fixNegotiationNeeded:q,shimGetUserMedia:V,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(r){return t(r).then((t=>{const i=r.video&&r.video.width,n=r.video&&r.video.height,s=r.video&&r.video.frameRate;return r.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:s||3}},i&&(r.video.mandatory.maxWidth=i),n&&(r.video.mandatory.maxHeight=n),e.navigator.mediaDevices.getUserMedia(r)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}});var Q,X,Z=(Q=function(e){var t={generateIdentifier:function(){return Math.random().toString(36).substr(2,10)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((function(e){return e.trim()}))},t.splitSections=function(e){return e.split("\nm=").map((function(e,t){return(t>0?"m="+e:e).trim()+"\r\n"}))},t.getDescription=function(e){var r=t.splitSections(e);return r&&r[0]},t.getMediaSections=function(e){var r=t.splitSections(e);return r.shift(),r},t.matchPrefix=function(e,r){return t.splitLines(e).filter((function(e){return 0===e.indexOf(r)}))},t.parseCandidate=function(e){for(var t,r={foundation:(t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" "))[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]},i=8;i<t.length;i+=2)switch(t[i]){case"raddr":r.relatedAddress=t[i+1];break;case"rport":r.relatedPort=parseInt(t[i+1],10);break;case"tcptype":r.tcpType=t[i+1];break;case"ufrag":r.ufrag=t[i+1],r.usernameFragment=t[i+1];break;default:r[t[i]]=t[i+1]}return r},t.writeCandidate=function(e){var t=[];t.push(e.foundation),t.push(e.component),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);var r=e.type;return t.push("typ"),t.push(r),"host"!==r&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substr(14).split(" ")},t.parseRtpMap=function(e){var t=e.substr(9).split(" "),r={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),r.name=t[0],r.clockRate=parseInt(t[1],10),r.channels=3===t.length?parseInt(t[2],10):1,r.numChannels=r.channels,r},t.writeRtpMap=function(e){var t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);var r=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==r?"/"+r:"")+"\r\n"},t.parseExtmap=function(e){var t=e.substr(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1]}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+"\r\n"},t.parseFmtp=function(e){for(var t,r={},i=e.substr(e.indexOf(" ")+1).split(";"),n=0;n<i.length;n++)r[(t=i[n].trim().split("="))[0].trim()]=t[1];return r},t.writeFmtp=function(e){var t="",r=e.payloadType;if(void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){var i=[];Object.keys(e.parameters).forEach((function(t){e.parameters[t]?i.push(t+"="+e.parameters[t]):i.push(t)})),t+="a=fmtp:"+r+" "+i.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){var t=e.substr(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){var t="",r=e.payloadType;return void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((function(e){t+="a=rtcp-fb:"+r+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){var t=e.indexOf(" "),r={ssrc:parseInt(e.substr(7,t-7),10)},i=e.indexOf(":",t);return i>-1?(r.attribute=e.substr(t+1,i-t-1),r.value=e.substr(i+1)):r.attribute=e.substr(t+1),r},t.parseSsrcGroup=function(e){var t=e.substr(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((function(e){return parseInt(e,10)}))}},t.getMid=function(e){var r=t.matchPrefix(e,"a=mid:")[0];if(r)return r.substr(6)},t.parseFingerprint=function(e){var t=e.substr(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1]}},t.getDtlsParameters=function(e,r){return{role:"auto",fingerprints:t.matchPrefix(e+r,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){var r="a=setup:"+t+"\r\n";return e.fingerprints.forEach((function(e){r+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),r},t.parseCryptoLine=function(e){var t=e.substr(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;var t=e.substr(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,r){return t.matchPrefix(e+r,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,r){var i=t.matchPrefix(e+r,"a=ice-ufrag:")[0],n=t.matchPrefix(e+r,"a=ice-pwd:")[0];return i&&n?{usernameFragment:i.substr(12),password:n.substr(10)}:null},t.writeIceParameters=function(e){return"a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n"},t.parseRtpParameters=function(e){for(var r={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},i=t.splitLines(e)[0].split(" "),n=3;n<i.length;n++){var s=i[n],o=t.matchPrefix(e,"a=rtpmap:"+s+" ")[0];if(o){var a=t.parseRtpMap(o),c=t.matchPrefix(e,"a=fmtp:"+s+" ");switch(a.parameters=c.length?t.parseFmtp(c[0]):{},a.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+s+" ").map(t.parseRtcpFb),r.codecs.push(a),a.name.toUpperCase()){case"RED":case"ULPFEC":r.fecMechanisms.push(a.name.toUpperCase())}}}return t.matchPrefix(e,"a=extmap:").forEach((function(e){r.headerExtensions.push(t.parseExtmap(e))})),r},t.writeRtpDescription=function(e,r){var i="";i+="m="+e+" ",i+=r.codecs.length>0?"9":"0",i+=" UDP/TLS/RTP/SAVPF ",i+=r.codecs.map((function(e){return void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType})).join(" ")+"\r\n",i+="c=IN IP4 0.0.0.0\r\n",i+="a=rtcp:9 IN IP4 0.0.0.0\r\n",r.codecs.forEach((function(e){i+=t.writeRtpMap(e),i+=t.writeFmtp(e),i+=t.writeRtcpFb(e)}));var n=0;return r.codecs.forEach((function(e){e.maxptime>n&&(n=e.maxptime)})),n>0&&(i+="a=maxptime:"+n+"\r\n"),i+="a=rtcp-mux\r\n",r.headerExtensions&&r.headerExtensions.forEach((function(e){i+=t.writeExtmap(e)})),i},t.parseRtpEncodingParameters=function(e){var r,i=[],n=t.parseRtpParameters(e),s=-1!==n.fecMechanisms.indexOf("RED"),o=-1!==n.fecMechanisms.indexOf("ULPFEC"),a=t.matchPrefix(e,"a=ssrc:").map((function(e){return t.parseSsrcMedia(e)})).filter((function(e){return"cname"===e.attribute})),c=a.length>0&&a[0].ssrc,d=t.matchPrefix(e,"a=ssrc-group:FID").map((function(e){return e.substr(17).split(" ").map((function(e){return parseInt(e,10)}))}));d.length>0&&d[0].length>1&&d[0][0]===c&&(r=d[0][1]),n.codecs.forEach((function(e){if("RTX"===e.name.toUpperCase()&&e.parameters.apt){var t={ssrc:c,codecPayloadType:parseInt(e.parameters.apt,10)};c&&r&&(t.rtx={ssrc:r}),i.push(t),s&&((t=JSON.parse(JSON.stringify(t))).fec={ssrc:c,mechanism:o?"red+ulpfec":"red"},i.push(t))}})),0===i.length&&c&&i.push({ssrc:c});var u=t.matchPrefix(e,"b=");return u.length&&(u=0===u[0].indexOf("b=TIAS:")?parseInt(u[0].substr(7),10):0===u[0].indexOf("b=AS:")?1e3*parseInt(u[0].substr(5),10)*.95-16e3:void 0,i.forEach((function(e){e.maxBitrate=u}))),i},t.parseRtcpParameters=function(e){var r={},i=t.matchPrefix(e,"a=ssrc:").map((function(e){return t.parseSsrcMedia(e)})).filter((function(e){return"cname"===e.attribute}))[0];i&&(r.cname=i.value,r.ssrc=i.ssrc);var n=t.matchPrefix(e,"a=rtcp-rsize");r.reducedSize=n.length>0,r.compound=0===n.length;var s=t.matchPrefix(e,"a=rtcp-mux");return r.mux=s.length>0,r},t.parseMsid=function(e){var r,i=t.matchPrefix(e,"a=msid:");if(1===i.length)return{stream:(r=i[0].substr(7).split(" "))[0],track:r[1]};var n=t.matchPrefix(e,"a=ssrc:").map((function(e){return t.parseSsrcMedia(e)})).filter((function(e){return"msid"===e.attribute}));return n.length>0?{stream:(r=n[0].value.split(" "))[0],track:r[1]}:void 0},t.parseSctpDescription=function(e){var r,i=t.parseMLine(e),n=t.matchPrefix(e,"a=max-message-size:");n.length>0&&(r=parseInt(n[0].substr(19),10)),isNaN(r)&&(r=65536);var s=t.matchPrefix(e,"a=sctp-port:");if(s.length>0)return{port:parseInt(s[0].substr(12),10),protocol:i.fmt,maxMessageSize:r};if(t.matchPrefix(e,"a=sctpmap:").length>0){var o=t.matchPrefix(e,"a=sctpmap:")[0].substr(10).split(" ");return{port:parseInt(o[0],10),protocol:o[1],maxMessageSize:r}}},t.writeSctpDescription=function(e,t){var r=[];return r="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&r.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),r.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,21)},t.writeSessionBoilerplate=function(e,r,i){var n=void 0!==r?r:2;return"v=0\r\no="+(i||"thisisadapterortc")+" "+(e||t.generateSessionId())+" "+n+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.writeMediaSection=function(e,r,i,n){var s=t.writeRtpDescription(e.kind,r);if(s+=t.writeIceParameters(e.iceGatherer.getLocalParameters()),s+=t.writeDtlsParameters(e.dtlsTransport.getLocalParameters(),"offer"===i?"actpass":"active"),s+="a=mid:"+e.mid+"\r\n",e.direction?s+="a="+e.direction+"\r\n":e.rtpSender&&e.rtpReceiver?s+="a=sendrecv\r\n":e.rtpSender?s+="a=sendonly\r\n":e.rtpReceiver?s+="a=recvonly\r\n":s+="a=inactive\r\n",e.rtpSender){var o="msid:"+n.id+" "+e.rtpSender.track.id+"\r\n";s+="a="+o,s+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" "+o,e.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" "+o,s+="a=ssrc-group:FID "+e.sendEncodingParameters[0].ssrc+" "+e.sendEncodingParameters[0].rtx.ssrc+"\r\n")}return s+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" cname:"+t.localCName+"\r\n",e.rtpSender&&e.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" cname:"+t.localCName+"\r\n"),s},t.getDirection=function(e,r){for(var i=t.splitLines(e),n=0;n<i.length;n++)switch(i[n]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return i[n].substr(2)}return r?t.getDirection(r):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substr(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){var r=t.splitLines(e)[0].substr(2).split(" ");return{kind:r[0],port:parseInt(r[1],10),protocol:r[2],fmt:r.slice(3).join(" ")}},t.parseOLine=function(e){var r=t.matchPrefix(e,"o=")[0].substr(2).split(" ");return{username:r[0],sessionId:r[1],sessionVersion:parseInt(r[2],10),netType:r[3],addressType:r[4],address:r[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;for(var r=t.splitLines(e),i=0;i<r.length;i++)if(r[i].length<2||"="!==r[i].charAt(1))return!1;return!0},e.exports=t},Q(X={exports:{}},X.exports),X.exports);function ee(e,t,r,i,n){var s=Z.writeRtpDescription(e.kind,t);if(s+=Z.writeIceParameters(e.iceGatherer.getLocalParameters()),s+=Z.writeDtlsParameters(e.dtlsTransport.getLocalParameters(),"offer"===r?"actpass":n||"active"),s+="a=mid:"+e.mid+"\r\n",e.rtpSender&&e.rtpReceiver?s+="a=sendrecv\r\n":e.rtpSender?s+="a=sendonly\r\n":e.rtpReceiver?s+="a=recvonly\r\n":s+="a=inactive\r\n",e.rtpSender){var o=e.rtpSender._initialTrackId||e.rtpSender.track.id;e.rtpSender._initialTrackId=o;var a="msid:"+(i?i.id:"-")+" "+o+"\r\n";s+="a="+a,s+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" "+a,e.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" "+a,s+="a=ssrc-group:FID "+e.sendEncodingParameters[0].ssrc+" "+e.sendEncodingParameters[0].rtx.ssrc+"\r\n")}return s+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" cname:"+Z.localCName+"\r\n",e.rtpSender&&e.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" cname:"+Z.localCName+"\r\n"),s}function te(e,t){var r={codecs:[],headerExtensions:[],fecMechanisms:[]},i=function(e,t){e=parseInt(e,10);for(var r=0;r<t.length;r++)if(t[r].payloadType===e||t[r].preferredPayloadType===e)return t[r]},n=function(e,t,r,n){var s=i(e.parameters.apt,r),o=i(t.parameters.apt,n);return s&&o&&s.name.toLowerCase()===o.name.toLowerCase()};return e.codecs.forEach((function(i){for(var s=0;s<t.codecs.length;s++){var o=t.codecs[s];if(i.name.toLowerCase()===o.name.toLowerCase()&&i.clockRate===o.clockRate){if("rtx"===i.name.toLowerCase()&&i.parameters&&o.parameters.apt&&!n(i,o,e.codecs,t.codecs))continue;(o=JSON.parse(JSON.stringify(o))).numChannels=Math.min(i.numChannels,o.numChannels),r.codecs.push(o),o.rtcpFeedback=o.rtcpFeedback.filter((function(e){for(var t=0;t<i.rtcpFeedback.length;t++)if(i.rtcpFeedback[t].type===e.type&&i.rtcpFeedback[t].parameter===e.parameter)return!0;return!1}));break}}})),e.headerExtensions.forEach((function(e){for(var i=0;i<t.headerExtensions.length;i++){var n=t.headerExtensions[i];if(e.uri===n.uri){r.headerExtensions.push(n);break}}})),r}function re(e,t,r){return-1!=={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][e].indexOf(r)}function ie(e,t){var r=e.getRemoteCandidates().find((function(e){return t.foundation===e.foundation&&t.ip===e.ip&&t.port===e.port&&t.priority===e.priority&&t.protocol===e.protocol&&t.type===e.type}));return r||e.addRemoteCandidate(t),!r}function ne(e,t){var r=new Error(t);return r.name=e,r.code={NotSupportedError:9,InvalidStateError:11,InvalidAccessError:15,TypeError:void 0,OperationError:void 0}[e],r}var se=function(e,t){function r(t,r){r.addTrack(t),r.dispatchEvent(new e.MediaStreamTrackEvent("addtrack",{track:t}))}function i(t,r,i,n){var s=new Event("track");s.track=r,s.receiver=i,s.transceiver={receiver:i},s.streams=n,e.setTimeout((function(){t._dispatchEvent("track",s)}))}var n=function(r){var i=this,n=document.createDocumentFragment();if(["addEventListener","removeEventListener","dispatchEvent"].forEach((function(e){i[e]=n[e].bind(n)})),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",r=JSON.parse(JSON.stringify(r||{})),this.usingBundle="max-bundle"===r.bundlePolicy,"negotiate"===r.rtcpMuxPolicy)throw ne("NotSupportedError","rtcpMuxPolicy 'negotiate' is not supported");switch(r.rtcpMuxPolicy||(r.rtcpMuxPolicy="require"),r.iceTransportPolicy){case"all":case"relay":break;default:r.iceTransportPolicy="all"}switch(r.bundlePolicy){case"balanced":case"max-compat":case"max-bundle":break;default:r.bundlePolicy="balanced"}if(r.iceServers=function(e,t){var r=!1;return(e=JSON.parse(JSON.stringify(e))).filter((function(e){if(e&&(e.urls||e.url)){var i=e.urls||e.url;e.url&&!e.urls&&console.warn("RTCIceServer.url is deprecated! Use urls instead.");var n="string"==typeof i;return n&&(i=[i]),i=i.filter((function(e){return 0!==e.indexOf("turn:")||-1===e.indexOf("transport=udp")||-1!==e.indexOf("turn:[")||r?0===e.indexOf("stun:")&&t>=14393&&-1===e.indexOf("?transport=udp"):(r=!0,!0)})),delete e.url,e.urls=n?i[0]:i,!!i.length}}))}(r.iceServers||[],t),this._iceGatherers=[],r.iceCandidatePoolSize)for(var s=r.iceCandidatePoolSize;s>0;s--)this._iceGatherers.push(new e.RTCIceGatherer({iceServers:r.iceServers,gatherPolicy:r.iceTransportPolicy}));else r.iceCandidatePoolSize=0;this._config=r,this.transceivers=[],this._sdpSessionId=Z.generateSessionId(),this._sdpSessionVersion=0,this._dtlsRole=void 0,this._isClosed=!1};Object.defineProperty(n.prototype,"localDescription",{configurable:!0,get:function(){return this._localDescription}}),Object.defineProperty(n.prototype,"remoteDescription",{configurable:!0,get:function(){return this._remoteDescription}}),n.prototype.onicecandidate=null,n.prototype.onaddstream=null,n.prototype.ontrack=null,n.prototype.onremovestream=null,n.prototype.onsignalingstatechange=null,n.prototype.oniceconnectionstatechange=null,n.prototype.onconnectionstatechange=null,n.prototype.onicegatheringstatechange=null,n.prototype.onnegotiationneeded=null,n.prototype.ondatachannel=null,n.prototype._dispatchEvent=function(e,t){this._isClosed||(this.dispatchEvent(t),"function"==typeof this["on"+e]&&this["on"+e](t))},n.prototype._emitGatheringStateChange=function(){var e=new Event("icegatheringstatechange");this._dispatchEvent("icegatheringstatechange",e)},n.prototype.getConfiguration=function(){return this._config},n.prototype.getLocalStreams=function(){return this.localStreams},n.prototype.getRemoteStreams=function(){return this.remoteStreams},n.prototype._createTransceiver=function(e,t){var r=this.transceivers.length>0,i={track:null,iceGatherer:null,iceTransport:null,dtlsTransport:null,localCapabilities:null,remoteCapabilities:null,rtpSender:null,rtpReceiver:null,kind:e,mid:null,sendEncodingParameters:null,recvEncodingParameters:null,stream:null,associatedRemoteMediaStreams:[],wantReceive:!0};if(this.usingBundle&&r)i.iceTransport=this.transceivers[0].iceTransport,i.dtlsTransport=this.transceivers[0].dtlsTransport;else{var n=this._createIceAndDtlsTransports();i.iceTransport=n.iceTransport,i.dtlsTransport=n.dtlsTransport}return t||this.transceivers.push(i),i},n.prototype.addTrack=function(t,r){if(this._isClosed)throw ne("InvalidStateError","Attempted to call addTrack on a closed peerconnection.");var i;if(this.transceivers.find((function(e){return e.track===t})))throw ne("InvalidAccessError","Track already exists.");for(var n=0;n<this.transceivers.length;n++)this.transceivers[n].track||this.transceivers[n].kind!==t.kind||(i=this.transceivers[n]);return i||(i=this._createTransceiver(t.kind)),this._maybeFireNegotiationNeeded(),-1===this.localStreams.indexOf(r)&&this.localStreams.push(r),i.track=t,i.stream=r,i.rtpSender=new e.RTCRtpSender(t,i.dtlsTransport),i.rtpSender},n.prototype.addStream=function(e){var r=this;if(t>=15025)e.getTracks().forEach((function(t){r.addTrack(t,e)}));else{var i=e.clone();e.getTracks().forEach((function(e,t){var r=i.getTracks()[t];e.addEventListener("enabled",(function(e){r.enabled=e.enabled}))})),i.getTracks().forEach((function(e){r.addTrack(e,i)}))}},n.prototype.removeTrack=function(t){if(this._isClosed)throw ne("InvalidStateError","Attempted to call removeTrack on a closed peerconnection.");if(!(t instanceof e.RTCRtpSender))throw new TypeError("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.");var r=this.transceivers.find((function(e){return e.rtpSender===t}));if(!r)throw ne("InvalidAccessError","Sender was not created by this connection.");var i=r.stream;r.rtpSender.stop(),r.rtpSender=null,r.track=null,r.stream=null,-1===this.transceivers.map((function(e){return e.stream})).indexOf(i)&&this.localStreams.indexOf(i)>-1&&this.localStreams.splice(this.localStreams.indexOf(i),1),this._maybeFireNegotiationNeeded()},n.prototype.removeStream=function(e){var t=this;e.getTracks().forEach((function(e){var r=t.getSenders().find((function(t){return t.track===e}));r&&t.removeTrack(r)}))},n.prototype.getSenders=function(){return this.transceivers.filter((function(e){return!!e.rtpSender})).map((function(e){return e.rtpSender}))},n.prototype.getReceivers=function(){return this.transceivers.filter((function(e){return!!e.rtpReceiver})).map((function(e){return e.rtpReceiver}))},n.prototype._createIceGatherer=function(t,r){var i=this;if(r&&t>0)return this.transceivers[0].iceGatherer;if(this._iceGatherers.length)return this._iceGatherers.shift();var n=new e.RTCIceGatherer({iceServers:this._config.iceServers,gatherPolicy:this._config.iceTransportPolicy});return Object.defineProperty(n,"state",{value:"new",writable:!0}),this.transceivers[t].bufferedCandidateEvents=[],this.transceivers[t].bufferCandidates=function(e){var r=!e.candidate||0===Object.keys(e.candidate).length;n.state=r?"completed":"gathering",null!==i.transceivers[t].bufferedCandidateEvents&&i.transceivers[t].bufferedCandidateEvents.push(e)},n.addEventListener("localcandidate",this.transceivers[t].bufferCandidates),n},n.prototype._gather=function(t,r){var i=this,n=this.transceivers[r].iceGatherer;if(!n.onlocalcandidate){var s=this.transceivers[r].bufferedCandidateEvents;this.transceivers[r].bufferedCandidateEvents=null,n.removeEventListener("localcandidate",this.transceivers[r].bufferCandidates),n.onlocalcandidate=function(e){if(!(i.usingBundle&&r>0)){var s=new Event("icecandidate");s.candidate={sdpMid:t,sdpMLineIndex:r};var o=e.candidate,a=!o||0===Object.keys(o).length;if(a)"new"!==n.state&&"gathering"!==n.state||(n.state="completed");else{"new"===n.state&&(n.state="gathering"),o.component=1,o.ufrag=n.getLocalParameters().usernameFragment;var c=Z.writeCandidate(o);s.candidate=Object.assign(s.candidate,Z.parseCandidate(c)),s.candidate.candidate=c,s.candidate.toJSON=function(){return{candidate:s.candidate.candidate,sdpMid:s.candidate.sdpMid,sdpMLineIndex:s.candidate.sdpMLineIndex,usernameFragment:s.candidate.usernameFragment}}}var d=Z.getMediaSections(i._localDescription.sdp);d[s.candidate.sdpMLineIndex]+=a?"a=end-of-candidates\r\n":"a="+s.candidate.candidate+"\r\n",i._localDescription.sdp=Z.getDescription(i._localDescription.sdp)+d.join("");var u=i.transceivers.every((function(e){return e.iceGatherer&&"completed"===e.iceGatherer.state}));"gathering"!==i.iceGatheringState&&(i.iceGatheringState="gathering",i._emitGatheringStateChange()),a||i._dispatchEvent("icecandidate",s),u&&(i._dispatchEvent("icecandidate",new Event("icecandidate")),i.iceGatheringState="complete",i._emitGatheringStateChange())}},e.setTimeout((function(){s.forEach((function(e){n.onlocalcandidate(e)}))}),0)}},n.prototype._createIceAndDtlsTransports=function(){var t=this,r=new e.RTCIceTransport(null);r.onicestatechange=function(){t._updateIceConnectionState(),t._updateConnectionState()};var i=new e.RTCDtlsTransport(r);return i.ondtlsstatechange=function(){t._updateConnectionState()},i.onerror=function(){Object.defineProperty(i,"state",{value:"failed",writable:!0}),t._updateConnectionState()},{iceTransport:r,dtlsTransport:i}},n.prototype._disposeIceAndDtlsTransports=function(e){var t=this.transceivers[e].iceGatherer;t&&(delete t.onlocalcandidate,delete this.transceivers[e].iceGatherer);var r=this.transceivers[e].iceTransport;r&&(delete r.onicestatechange,delete this.transceivers[e].iceTransport);var i=this.transceivers[e].dtlsTransport;i&&(delete i.ondtlsstatechange,delete i.onerror,delete this.transceivers[e].dtlsTransport)},n.prototype._transceive=function(e,r,i){var n=te(e.localCapabilities,e.remoteCapabilities);r&&e.rtpSender&&(n.encodings=e.sendEncodingParameters,n.rtcp={cname:Z.localCName,compound:e.rtcpParameters.compound},e.recvEncodingParameters.length&&(n.rtcp.ssrc=e.recvEncodingParameters[0].ssrc),e.rtpSender.send(n)),i&&e.rtpReceiver&&n.codecs.length>0&&("video"===e.kind&&e.recvEncodingParameters&&t<15019&&e.recvEncodingParameters.forEach((function(e){delete e.rtx})),e.recvEncodingParameters.length?n.encodings=e.recvEncodingParameters:n.encodings=[{}],n.rtcp={compound:e.rtcpParameters.compound},e.rtcpParameters.cname&&(n.rtcp.cname=e.rtcpParameters.cname),e.sendEncodingParameters.length&&(n.rtcp.ssrc=e.sendEncodingParameters[0].ssrc),e.rtpReceiver.receive(n))},n.prototype.setLocalDescription=function(e){var t,r,i=this;if(-1===["offer","answer"].indexOf(e.type))return Promise.reject(ne("TypeError",'Unsupported type "'+e.type+'"'));if(!re("setLocalDescription",e.type,i.signalingState)||i._isClosed)return Promise.reject(ne("InvalidStateError","Can not set local "+e.type+" in state "+i.signalingState));if("offer"===e.type)t=Z.splitSections(e.sdp),r=t.shift(),t.forEach((function(e,t){var r=Z.parseRtpParameters(e);i.transceivers[t].localCapabilities=r})),i.transceivers.forEach((function(e,t){i._gather(e.mid,t)}));else if("answer"===e.type){t=Z.splitSections(i._remoteDescription.sdp),r=t.shift();var n=Z.matchPrefix(r,"a=ice-lite").length>0;t.forEach((function(e,t){var s=i.transceivers[t],o=s.iceGatherer,a=s.iceTransport,c=s.dtlsTransport,d=s.localCapabilities,u=s.remoteCapabilities;if(!(Z.isRejected(e)&&0===Z.matchPrefix(e,"a=bundle-only").length)&&!s.rejected){var l=Z.getIceParameters(e,r),h=Z.getDtlsParameters(e,r);n&&(h.role="server"),i.usingBundle&&0!==t||(i._gather(s.mid,t),"new"===a.state&&a.start(o,l,n?"controlling":"controlled"),"new"===c.state&&c.start(h));var p=te(d,u);i._transceive(s,p.codecs.length>0,!1)}}))}return i._localDescription={type:e.type,sdp:e.sdp},"offer"===e.type?i._updateSignalingState("have-local-offer"):i._updateSignalingState("stable"),Promise.resolve()},n.prototype.setRemoteDescription=function(n){var s=this;if(-1===["offer","answer"].indexOf(n.type))return Promise.reject(ne("TypeError",'Unsupported type "'+n.type+'"'));if(!re("setRemoteDescription",n.type,s.signalingState)||s._isClosed)return Promise.reject(ne("InvalidStateError","Can not set remote "+n.type+" in state "+s.signalingState));var o={};s.remoteStreams.forEach((function(e){o[e.id]=e}));var a=[],c=Z.splitSections(n.sdp),d=c.shift(),u=Z.matchPrefix(d,"a=ice-lite").length>0,l=Z.matchPrefix(d,"a=group:BUNDLE ").length>0;s.usingBundle=l;var h=Z.matchPrefix(d,"a=ice-options:")[0];return s.canTrickleIceCandidates=!!h&&h.substr(14).split(" ").indexOf("trickle")>=0,c.forEach((function(i,c){var h=Z.splitLines(i),p=Z.getKind(i),_=Z.isRejected(i)&&0===Z.matchPrefix(i,"a=bundle-only").length,m=h[0].substr(2).split(" ")[2],f=Z.getDirection(i,d),v=Z.parseMsid(i),R=Z.getMid(i)||Z.generateIdentifier();if(_||"application"===p&&("DTLS/SCTP"===m||"UDP/DTLS/SCTP"===m))s.transceivers[c]={mid:R,kind:p,protocol:m,rejected:!0};else{var g,S,C,T,I,E,y,k,b;!_&&s.transceivers[c]&&s.transceivers[c].rejected&&(s.transceivers[c]=s._createTransceiver(p,!0));var P,O,L=Z.parseRtpParameters(i);_||(P=Z.getIceParameters(i,d),(O=Z.getDtlsParameters(i,d)).role="client"),y=Z.parseRtpEncodingParameters(i);var N=Z.parseRtcpParameters(i),D=Z.matchPrefix(i,"a=end-of-candidates",d).length>0,A=Z.matchPrefix(i,"a=candidate:").map((function(e){return Z.parseCandidate(e)})).filter((function(e){return 1===e.component}));if(("offer"===n.type||"answer"===n.type)&&!_&&l&&c>0&&s.transceivers[c]&&(s._disposeIceAndDtlsTransports(c),s.transceivers[c].iceGatherer=s.transceivers[0].iceGatherer,s.transceivers[c].iceTransport=s.transceivers[0].iceTransport,s.transceivers[c].dtlsTransport=s.transceivers[0].dtlsTransport,s.transceivers[c].rtpSender&&s.transceivers[c].rtpSender.setTransport(s.transceivers[0].dtlsTransport),s.transceivers[c].rtpReceiver&&s.transceivers[c].rtpReceiver.setTransport(s.transceivers[0].dtlsTransport)),"offer"!==n.type||_){if("answer"===n.type&&!_){S=(g=s.transceivers[c]).iceGatherer,C=g.iceTransport,T=g.dtlsTransport,I=g.rtpReceiver,E=g.sendEncodingParameters,k=g.localCapabilities,s.transceivers[c].recvEncodingParameters=y,s.transceivers[c].remoteCapabilities=L,s.transceivers[c].rtcpParameters=N,A.length&&"new"===C.state&&(!u&&!D||l&&0!==c?A.forEach((function(e){ie(g.iceTransport,e)})):C.setRemoteCandidates(A)),l&&0!==c||("new"===C.state&&C.start(S,P,"controlling"),"new"===T.state&&T.start(O)),!te(g.localCapabilities,g.remoteCapabilities).codecs.filter((function(e){return"rtx"===e.name.toLowerCase()})).length&&g.sendEncodingParameters[0].rtx&&delete g.sendEncodingParameters[0].rtx,s._transceive(g,"sendrecv"===f||"recvonly"===f,"sendrecv"===f||"sendonly"===f),!I||"sendrecv"!==f&&"sendonly"!==f?delete g.rtpReceiver:(b=I.track,v?(o[v.stream]||(o[v.stream]=new e.MediaStream),r(b,o[v.stream]),a.push([b,I,o[v.stream]])):(o.default||(o.default=new e.MediaStream),r(b,o.default),a.push([b,I,o.default])))}}else{(g=s.transceivers[c]||s._createTransceiver(p)).mid=R,g.iceGatherer||(g.iceGatherer=s._createIceGatherer(c,l)),A.length&&"new"===g.iceTransport.state&&(!D||l&&0!==c?A.forEach((function(e){ie(g.iceTransport,e)})):g.iceTransport.setRemoteCandidates(A)),k=e.RTCRtpReceiver.getCapabilities(p),t<15019&&(k.codecs=k.codecs.filter((function(e){return"rtx"!==e.name}))),E=g.sendEncodingParameters||[{ssrc:1001*(2*c+2)}];var M,x=!1;if("sendrecv"===f||"sendonly"===f){if(x=!g.rtpReceiver,I=g.rtpReceiver||new e.RTCRtpReceiver(g.dtlsTransport,p),x)b=I.track,v&&"-"===v.stream||(v?(o[v.stream]||(o[v.stream]=new e.MediaStream,Object.defineProperty(o[v.stream],"id",{get:function(){return v.stream}})),Object.defineProperty(b,"id",{get:function(){return v.track}}),M=o[v.stream]):(o.default||(o.default=new e.MediaStream),M=o.default)),M&&(r(b,M),g.associatedRemoteMediaStreams.push(M)),a.push([b,I,M])}else g.rtpReceiver&&g.rtpReceiver.track&&(g.associatedRemoteMediaStreams.forEach((function(t){var r=t.getTracks().find((function(e){return e.id===g.rtpReceiver.track.id}));r&&function(t,r){r.removeTrack(t),r.dispatchEvent(new e.MediaStreamTrackEvent("removetrack",{track:t}))}(r,t)})),g.associatedRemoteMediaStreams=[]);g.localCapabilities=k,g.remoteCapabilities=L,g.rtpReceiver=I,g.rtcpParameters=N,g.sendEncodingParameters=E,g.recvEncodingParameters=y,s._transceive(s.transceivers[c],!1,x)}}})),void 0===s._dtlsRole&&(s._dtlsRole="offer"===n.type?"active":"passive"),s._remoteDescription={type:n.type,sdp:n.sdp},"offer"===n.type?s._updateSignalingState("have-remote-offer"):s._updateSignalingState("stable"),Object.keys(o).forEach((function(t){var r=o[t];if(r.getTracks().length){if(-1===s.remoteStreams.indexOf(r)){s.remoteStreams.push(r);var n=new Event("addstream");n.stream=r,e.setTimeout((function(){s._dispatchEvent("addstream",n)}))}a.forEach((function(e){var t=e[0],n=e[1];r.id===e[2].id&&i(s,t,n,[r])}))}})),a.forEach((function(e){e[2]||i(s,e[0],e[1],[])})),e.setTimeout((function(){s&&s.transceivers&&s.transceivers.forEach((function(e){e.iceTransport&&"new"===e.iceTransport.state&&e.iceTransport.getRemoteCandidates().length>0&&(console.warn("Timeout for addRemoteCandidate. Consider sending an end-of-candidates notification"),e.iceTransport.addRemoteCandidate({}))}))}),4e3),Promise.resolve()},n.prototype.close=function(){this.transceivers.forEach((function(e){e.iceTransport&&e.iceTransport.stop(),e.dtlsTransport&&e.dtlsTransport.stop(),e.rtpSender&&e.rtpSender.stop(),e.rtpReceiver&&e.rtpReceiver.stop()})),this._isClosed=!0,this._updateSignalingState("closed")},n.prototype._updateSignalingState=function(e){this.signalingState=e;var t=new Event("signalingstatechange");this._dispatchEvent("signalingstatechange",t)},n.prototype._maybeFireNegotiationNeeded=function(){var t=this;"stable"===this.signalingState&&!0!==this.needNegotiation&&(this.needNegotiation=!0,e.setTimeout((function(){if(t.needNegotiation){t.needNegotiation=!1;var e=new Event("negotiationneeded");t._dispatchEvent("negotiationneeded",e)}}),0))},n.prototype._updateIceConnectionState=function(){var e,t={new:0,closed:0,checking:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach((function(e){e.iceTransport&&!e.rejected&&t[e.iceTransport.state]++})),e="new",t.failed>0?e="failed":t.checking>0?e="checking":t.disconnected>0?e="disconnected":t.new>0?e="new":t.connected>0?e="connected":t.completed>0&&(e="completed"),e!==this.iceConnectionState){this.iceConnectionState=e;var r=new Event("iceconnectionstatechange");this._dispatchEvent("iceconnectionstatechange",r)}},n.prototype._updateConnectionState=function(){var e,t={new:0,closed:0,connecting:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach((function(e){e.iceTransport&&e.dtlsTransport&&!e.rejected&&(t[e.iceTransport.state]++,t[e.dtlsTransport.state]++)})),t.connected+=t.completed,e="new",t.failed>0?e="failed":t.connecting>0?e="connecting":t.disconnected>0?e="disconnected":t.new>0?e="new":t.connected>0&&(e="connected"),e!==this.connectionState){this.connectionState=e;var r=new Event("connectionstatechange");this._dispatchEvent("connectionstatechange",r)}},n.prototype.createOffer=function(){var r=this;if(r._isClosed)return Promise.reject(ne("InvalidStateError","Can not call createOffer after close"));var i=r.transceivers.filter((function(e){return"audio"===e.kind})).length,n=r.transceivers.filter((function(e){return"video"===e.kind})).length,s=arguments[0];if(s){if(s.mandatory||s.optional)throw new TypeError("Legacy mandatory/optional constraints not supported.");void 0!==s.offerToReceiveAudio&&(i=!0===s.offerToReceiveAudio?1:!1===s.offerToReceiveAudio?0:s.offerToReceiveAudio),void 0!==s.offerToReceiveVideo&&(n=!0===s.offerToReceiveVideo?1:!1===s.offerToReceiveVideo?0:s.offerToReceiveVideo)}for(r.transceivers.forEach((function(e){"audio"===e.kind?--i<0&&(e.wantReceive=!1):"video"===e.kind&&--n<0&&(e.wantReceive=!1)}));i>0||n>0;)i>0&&(r._createTransceiver("audio"),i--),n>0&&(r._createTransceiver("video"),n--);var o=Z.writeSessionBoilerplate(r._sdpSessionId,r._sdpSessionVersion++);r.transceivers.forEach((function(i,n){var s=i.track,o=i.kind,a=i.mid||Z.generateIdentifier();i.mid=a,i.iceGatherer||(i.iceGatherer=r._createIceGatherer(n,r.usingBundle));var c=e.RTCRtpSender.getCapabilities(o);t<15019&&(c.codecs=c.codecs.filter((function(e){return"rtx"!==e.name}))),c.codecs.forEach((function(e){"H264"===e.name&&void 0===e.parameters["level-asymmetry-allowed"]&&(e.parameters["level-asymmetry-allowed"]="1"),i.remoteCapabilities&&i.remoteCapabilities.codecs&&i.remoteCapabilities.codecs.forEach((function(t){e.name.toLowerCase()===t.name.toLowerCase()&&e.clockRate===t.clockRate&&(e.preferredPayloadType=t.payloadType)}))})),c.headerExtensions.forEach((function(e){(i.remoteCapabilities&&i.remoteCapabilities.headerExtensions||[]).forEach((function(t){e.uri===t.uri&&(e.id=t.id)}))}));var d=i.sendEncodingParameters||[{ssrc:1001*(2*n+1)}];s&&t>=15019&&"video"===o&&!d[0].rtx&&(d[0].rtx={ssrc:d[0].ssrc+1}),i.wantReceive&&(i.rtpReceiver=new e.RTCRtpReceiver(i.dtlsTransport,o)),i.localCapabilities=c,i.sendEncodingParameters=d})),"max-compat"!==r._config.bundlePolicy&&(o+="a=group:BUNDLE "+r.transceivers.map((function(e){return e.mid})).join(" ")+"\r\n"),o+="a=ice-options:trickle\r\n",r.transceivers.forEach((function(e,t){o+=ee(e,e.localCapabilities,"offer",e.stream,r._dtlsRole),o+="a=rtcp-rsize\r\n",!e.iceGatherer||"new"===r.iceGatheringState||0!==t&&r.usingBundle||(e.iceGatherer.getLocalCandidates().forEach((function(e){e.component=1,o+="a="+Z.writeCandidate(e)+"\r\n"})),"completed"===e.iceGatherer.state&&(o+="a=end-of-candidates\r\n"))}));var a=new e.RTCSessionDescription({type:"offer",sdp:o});return Promise.resolve(a)},n.prototype.createAnswer=function(){var r=this;if(r._isClosed)return Promise.reject(ne("InvalidStateError","Can not call createAnswer after close"));if("have-remote-offer"!==r.signalingState&&"have-local-pranswer"!==r.signalingState)return Promise.reject(ne("InvalidStateError","Can not call createAnswer in signalingState "+r.signalingState));var i=Z.writeSessionBoilerplate(r._sdpSessionId,r._sdpSessionVersion++);r.usingBundle&&(i+="a=group:BUNDLE "+r.transceivers.map((function(e){return e.mid})).join(" ")+"\r\n"),i+="a=ice-options:trickle\r\n";var n=Z.getMediaSections(r._remoteDescription.sdp).length;r.transceivers.forEach((function(e,s){if(!(s+1>n)){if(e.rejected)return"application"===e.kind?"DTLS/SCTP"===e.protocol?i+="m=application 0 DTLS/SCTP 5000\r\n":i+="m=application 0 "+e.protocol+" webrtc-datachannel\r\n":"audio"===e.kind?i+="m=audio 0 UDP/TLS/RTP/SAVPF 0\r\na=rtpmap:0 PCMU/8000\r\n":"video"===e.kind&&(i+="m=video 0 UDP/TLS/RTP/SAVPF 120\r\na=rtpmap:120 VP8/90000\r\n"),void(i+="c=IN IP4 0.0.0.0\r\na=inactive\r\na=mid:"+e.mid+"\r\n");var o;if(e.stream)"audio"===e.kind?o=e.stream.getAudioTracks()[0]:"video"===e.kind&&(o=e.stream.getVideoTracks()[0]),o&&t>=15019&&"video"===e.kind&&!e.sendEncodingParameters[0].rtx&&(e.sendEncodingParameters[0].rtx={ssrc:e.sendEncodingParameters[0].ssrc+1});var a=te(e.localCapabilities,e.remoteCapabilities);!a.codecs.filter((function(e){return"rtx"===e.name.toLowerCase()})).length&&e.sendEncodingParameters[0].rtx&&delete e.sendEncodingParameters[0].rtx,i+=ee(e,a,"answer",e.stream,r._dtlsRole),e.rtcpParameters&&e.rtcpParameters.reducedSize&&(i+="a=rtcp-rsize\r\n")}}));var s=new e.RTCSessionDescription({type:"answer",sdp:i});return Promise.resolve(s)},n.prototype.addIceCandidate=function(e){var t,r=this;return e&&void 0===e.sdpMLineIndex&&!e.sdpMid?Promise.reject(new TypeError("sdpMLineIndex or sdpMid required")):new Promise((function(i,n){if(!r._remoteDescription)return n(ne("InvalidStateError","Can not add ICE candidate without a remote description"));if(e&&""!==e.candidate){var s=e.sdpMLineIndex;if(e.sdpMid)for(var o=0;o<r.transceivers.length;o++)if(r.transceivers[o].mid===e.sdpMid){s=o;break}var a=r.transceivers[s];if(!a)return n(ne("OperationError","Can not add ICE candidate"));if(a.rejected)return i();var c=Object.keys(e.candidate).length>0?Z.parseCandidate(e.candidate):{};if("tcp"===c.protocol&&(0===c.port||9===c.port))return i();if(c.component&&1!==c.component)return i();if((0===s||s>0&&a.iceTransport!==r.transceivers[0].iceTransport)&&!ie(a.iceTransport,c))return n(ne("OperationError","Can not add ICE candidate"));var d=e.candidate.trim();0===d.indexOf("a=")&&(d=d.substr(2)),(t=Z.getMediaSections(r._remoteDescription.sdp))[s]+="a="+(c.type?d:"end-of-candidates")+"\r\n",r._remoteDescription.sdp=Z.getDescription(r._remoteDescription.sdp)+t.join("")}else for(var u=0;u<r.transceivers.length&&(r.transceivers[u].rejected||(r.transceivers[u].iceTransport.addRemoteCandidate({}),(t=Z.getMediaSections(r._remoteDescription.sdp))[u]+="a=end-of-candidates\r\n",r._remoteDescription.sdp=Z.getDescription(r._remoteDescription.sdp)+t.join(""),!r.usingBundle));u++);i()}))},n.prototype.getStats=function(t){if(t&&t instanceof e.MediaStreamTrack){var r=null;if(this.transceivers.forEach((function(e){e.rtpSender&&e.rtpSender.track===t?r=e.rtpSender:e.rtpReceiver&&e.rtpReceiver.track===t&&(r=e.rtpReceiver)})),!r)throw ne("InvalidAccessError","Invalid selector.");return r.getStats()}var i=[];return this.transceivers.forEach((function(e){["rtpSender","rtpReceiver","iceGatherer","iceTransport","dtlsTransport"].forEach((function(t){e[t]&&i.push(e[t].getStats())}))})),Promise.all(i).then((function(e){var t=new Map;return e.forEach((function(e){e.forEach((function(e){t.set(e.id,e)}))})),t}))};["RTCRtpSender","RTCRtpReceiver","RTCIceGatherer","RTCIceTransport","RTCDtlsTransport"].forEach((function(t){var r=e[t];if(r&&r.prototype&&r.prototype.getStats){var i=r.prototype.getStats;r.prototype.getStats=function(){return i.apply(this).then((function(e){var t=new Map;return Object.keys(e).forEach((function(r){var i;e[r].type={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[(i=e[r]).type]||i.type,t.set(r,e[r])})),t}))}}}));var s=["createOffer","createAnswer"];return s.forEach((function(e){var t=n.prototype[e];n.prototype[e]=function(){var e=arguments;return"function"==typeof e[0]||"function"==typeof e[1]?t.apply(this,[arguments[2]]).then((function(t){"function"==typeof e[0]&&e[0].apply(null,[t])}),(function(t){"function"==typeof e[1]&&e[1].apply(null,[t])})):t.apply(this,arguments)}})),(s=["setLocalDescription","setRemoteDescription","addIceCandidate"]).forEach((function(e){var t=n.prototype[e];n.prototype[e]=function(){var e=arguments;return"function"==typeof e[1]||"function"==typeof e[2]?t.apply(this,arguments).then((function(){"function"==typeof e[1]&&e[1].apply(null)}),(function(t){"function"==typeof e[2]&&e[2].apply(null,[t])})):t.apply(this,arguments)}})),["getStats"].forEach((function(e){var t=n.prototype[e];n.prototype[e]=function(){var e=arguments;return"function"==typeof e[1]?t.apply(this,arguments).then((function(){"function"==typeof e[1]&&e[1].apply(null)})):t.apply(this,arguments)}})),n};function oe(e){const t=e&&e.navigator,r=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(e){return r(e).catch((e=>Promise.reject(function(e){return{name:{PermissionDeniedError:"NotAllowedError"}[e.name]||e.name,message:e.message,constraint:e.constraint,toString(){return this.name}}}(e))))}}function ae(e){"getDisplayMedia"in e.navigator&&e.navigator.mediaDevices&&(e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||(e.navigator.mediaDevices.getDisplayMedia=e.navigator.getDisplayMedia.bind(e.navigator)))}function ce(e,t){if(e.RTCIceGatherer&&(e.RTCIceCandidate||(e.RTCIceCandidate=function(e){return e}),e.RTCSessionDescription||(e.RTCSessionDescription=function(e){return e}),t.version<15025)){const t=Object.getOwnPropertyDescriptor(e.MediaStreamTrack.prototype,"enabled");Object.defineProperty(e.MediaStreamTrack.prototype,"enabled",{set(e){t.set.call(this,e);const r=new Event("enabled");r.enabled=e,this.dispatchEvent(r)}})}e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)&&Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=new e.RTCDtmfSender(this):"video"===this.track.kind&&(this._dtmf=null)),this._dtmf}}),e.RTCDtmfSender&&!e.RTCDTMFSender&&(e.RTCDTMFSender=e.RTCDtmfSender);const r=se(e,t.version);e.RTCPeerConnection=function(e){return e&&e.iceServers&&(e.iceServers=function(e,t){let r=!1;return(e=JSON.parse(JSON.stringify(e))).filter((e=>{if(e&&(e.urls||e.url)){let t=e.urls||e.url;e.url&&!e.urls&&M("RTCIceServer.url","RTCIceServer.urls");const i="string"==typeof t;return i&&(t=[t]),t=t.filter((e=>{if(0===e.indexOf("stun:"))return!1;const t=e.startsWith("turn")&&!e.startsWith("turn:[")&&e.includes("transport=udp");return t&&!r?(r=!0,!0):t&&!r})),delete e.url,e.urls=i?t[0]:t,!!t.length}}))}(e.iceServers,t.version),A("ICE servers after filtering:",e.iceServers)),new r(e)},e.RTCPeerConnection.prototype=r.prototype}function de(e){e.RTCRtpSender&&!("replaceTrack"in e.RTCRtpSender.prototype)&&(e.RTCRtpSender.prototype.replaceTrack=e.RTCRtpSender.prototype.setTrack)}var ue=Object.freeze({__proto__:null,shimPeerConnection:ce,shimReplaceTrack:de,shimGetUserMedia:oe,shimGetDisplayMedia:ae});function le(e,t){const r=e&&e.navigator,i=e&&e.MediaStreamTrack;if(r.getUserMedia=function(e,t,i){M("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),r.mediaDevices.getUserMedia(e).then(t,i)},!(t.version>55&&"autoGainControl"in r.mediaDevices.getSupportedConstraints())){const e=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])},t=r.mediaDevices.getUserMedia.bind(r.mediaDevices);if(r.mediaDevices.getUserMedia=function(r){return"object"==typeof r&&"object"==typeof r.audio&&(r=JSON.parse(JSON.stringify(r)),e(r.audio,"autoGainControl","mozAutoGainControl"),e(r.audio,"noiseSuppression","mozNoiseSuppression")),t(r)},i&&i.prototype.getSettings){const t=i.prototype.getSettings;i.prototype.getSettings=function(){const r=t.apply(this,arguments);return e(r,"mozAutoGainControl","autoGainControl"),e(r,"mozNoiseSuppression","noiseSuppression"),r}}if(i&&i.prototype.applyConstraints){const t=i.prototype.applyConstraints;i.prototype.applyConstraints=function(r){return"audio"===this.kind&&"object"==typeof r&&(r=JSON.parse(JSON.stringify(r)),e(r,"autoGainControl","mozAutoGainControl"),e(r,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[r])}}}}function he(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function pe(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]}));const r={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,n,s]=arguments;return i.apply(this,[e||null]).then((e=>{if(t.version<53&&!n)try{e.forEach((e=>{e.type=r[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach(((t,i)=>{e.set(i,Object.assign({},t,{type:r[t.type]||t.type}))}))}return e})).then(n,s)}}function _e(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=r.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function me(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),L(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function fe(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){M("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function ve(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Re(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];const e=arguments[1],r=e&&"sendEncodings"in e;r&&e.sendEncodings.forEach((e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const i=t.apply(this,arguments);if(r){const{sender:t}=i,r=t.getParameters();(!("encodings"in r)||1===r.encodings.length&&0===Object.keys(r.encodings[0]).length)&&(r.encodings=e.sendEncodings,t.sendEncodings=e.sendEncodings,this.setParametersPromises.push(t.setParameters(r).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return i})}function ge(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function Se(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}function Ce(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}var Te=Object.freeze({__proto__:null,shimOnTrack:he,shimPeerConnection:pe,shimSenderGetStats:_e,shimReceiverGetStats:me,shimRemoveStream:fe,shimRTCDataChannel:ve,shimAddTransceiver:Re,shimGetParameters:ge,shimCreateOffer:Se,shimCreateAnswer:Ce,shimGetUserMedia:le,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(r){if(!r||!r.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===r.video?r.video={mediaSource:t}:r.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(r)})}});function Ie(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((r=>t.call(this,r,e))),e.getVideoTracks().forEach((r=>t.call(this,r,e)))},e.RTCPeerConnection.prototype.addTrack=function(e,...r){return r&&r.forEach((e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const r=e.getTracks();this.getSenders().forEach((e=>{r.includes(e.track)&&this.removeTrack(e)}))})}}function Ee(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach((e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const r=new Event("addstream");r.stream=t,e.dispatchEvent(r)}))}),t.apply(e,arguments)}}}function ye(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,r=t.createOffer,i=t.createAnswer,n=t.setLocalDescription,s=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],n=r.apply(this,[i]);return t?(n.then(e,t),Promise.resolve()):n},t.createAnswer=function(e,t){const r=arguments.length>=2?arguments[2]:arguments[0],n=i.apply(this,[r]);return t?(n.then(e,t),Promise.resolve()):n};let a=function(e,t,r){const i=n.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i};t.setLocalDescription=a,a=function(e,t,r){const i=s.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i},t.setRemoteDescription=a,a=function(e,t,r){const i=o.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i},t.addIceCandidate=a}function ke(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,r=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>r(be(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,r,i){t.mediaDevices.getUserMedia(e).then(r,i)}.bind(t))}function be(e){return e&&void 0!==e.video?Object.assign({},e,{video:U(e.video)}):e}function Pe(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,r){if(e&&e.iceServers){const t=[];for(let r=0;r<e.iceServers.length;r++){let i=e.iceServers[r];!i.hasOwnProperty("urls")&&i.hasOwnProperty("url")?(M("RTCIceServer.url","RTCIceServer.urls"),i=JSON.parse(JSON.stringify(i)),i.urls=i.url,delete i.url,t.push(i)):t.push(e.iceServers[r])}e.iceServers=t}return new t(e,r)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function Oe(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Le(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find((e=>"audio"===e.receiver.track.kind));!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio"),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const r=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&r?"sendrecv"===r.direction?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":"recvonly"===r.direction&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):!0!==e.offerToReceiveVideo||r||this.addTransceiver("video")}return t.apply(this,arguments)}}function Ne(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var De=Object.freeze({__proto__:null,shimLocalStreamsAPI:Ie,shimRemoteStreamsAPI:Ee,shimCallbacksAPI:ye,shimGetUserMedia:ke,shimConstraints:be,shimRTCIceServerUrls:Pe,shimTrackEventTransceiver:Oe,shimCreateOfferLegacy:Le,shimAudioContext:Ne});function Ae(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substr(2)),e.candidate&&e.candidate.length){const r=new t(e),i=Z.parseCandidate(e.candidate),n=Object.assign(r,i);return n.toJSON=function(){return{candidate:n.candidate,sdpMid:n.sdpMid,sdpMLineIndex:n.sdpMLineIndex,usernameFragment:n.usernameFragment}},n}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,L(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function Me(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const r=function(e){if(!e||!e.sdp)return!1;const t=Z.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=Z.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))},i=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const r=parseInt(t[1],10);return r!=r?-1:r},n=function(e){let r=65536;return"firefox"===t.browser&&(r=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),r},s=function(e,r){let i=65536;"firefox"===t.browser&&57===t.version&&(i=65535);const n=Z.matchPrefix(e.sdp,"a=max-message-size:");return n.length>0?i=parseInt(n[0].substr(19),10):"firefox"===t.browser&&-1!==r&&(i=2147483637),i},o=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(r(arguments[0])){const e=i(arguments[0]),t=n(e),r=s(arguments[0],e);let o;o=0===t&&0===r?Number.POSITIVE_INFINITY:0===t||0===r?Math.max(t,r):Math.min(t,r);const a={};Object.defineProperty(a,"maxMessageSize",{get:()=>o}),this._sctp=a}return o.apply(this,arguments)}}function xe(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const r=e.send;e.send=function(){const i=arguments[0],n=i.length||i.size||i.byteLength;if("open"===e.readyState&&t.sctp&&n>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return r.apply(e,arguments)}}const r=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=r.apply(this,arguments);return t(e,this),e},L(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function Ue(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach((e=>{const r=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const r=new Event("connectionstatechange",e);t.dispatchEvent(r)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),r.apply(this,arguments)}}))}function we(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const r=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const r=t.sdp.split("\n").filter((e=>"a=extmap-allow-mixed"!==e.trim())).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:r}):t.sdp=r}return r.apply(this,arguments)}}function $e(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const r=e.RTCPeerConnection.prototype.addIceCandidate;r&&0!==r.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():r.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}var je=Object.freeze({__proto__:null,shimRTCIceCandidate:Ae,shimMaxMessageSize:Me,shimSendThrowTypeError:xe,shimConnectionState:Ue,removeExtmapAllowMixed:we,shimAddIceCandidateNullOrEmpty:$e});const Ve=function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimEdge:!0,shimSafari:!0}){const r=A,i=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator)return t.browser="Not a browser.",t;const{navigator:r}=e;if(r.mozGetUserMedia)t.browser="firefox",t.version=O(r.userAgent,/Firefox\/(\d+)\./,1);else if(r.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection&&!e.RTCIceGatherer)t.browser="chrome",t.version=O(r.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(r.mediaDevices&&r.userAgent.match(/Edge\/(\d+).(\d+)$/))t.browser="edge",t.version=O(r.userAgent,/Edge\/(\d+).(\d+)$/,2);else{if(!e.RTCPeerConnection||!r.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=O(r.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),n={browserDetails:i,commonShim:je,extractVersion:O,disableLog:N,disableWarnings:D};switch(i.browser){case"chrome":if(!z||!Y||!t.shimChrome)return r("Chrome shim is not included in this adapter release."),n;if(null===i.version)return r("Chrome shim can not determine version, not shimming."),n;r("adapter.js shimming chrome."),n.browserShim=z,$e(e,i),V(e,i),B(e),Y(e,i),H(e),W(e,i),F(e),K(e),G(e),q(e,i),Ae(e),Ue(e),Me(e,i),xe(e),we(e,i);break;case"firefox":if(!Te||!pe||!t.shimFirefox)return r("Firefox shim is not included in this adapter release."),n;r("adapter.js shimming firefox."),n.browserShim=Te,$e(e,i),le(e,i),pe(e,i),he(e),fe(e),_e(e),me(e),ve(e),Re(e),ge(e),Se(e),Ce(e),Ae(e),Ue(e),Me(e,i),xe(e);break;case"edge":if(!ue||!ce||!t.shimEdge)return r("MS edge shim is not included in this adapter release."),n;r("adapter.js shimming edge."),n.browserShim=ue,oe(e),ae(e),ce(e,i),de(e),Me(e,i),xe(e);break;case"safari":if(!De||!t.shimSafari)return r("Safari shim is not included in this adapter release."),n;r("adapter.js shimming safari."),n.browserShim=De,$e(e,i),Pe(e),Le(e),ye(e),Ie(e),Ee(e),Oe(e),ke(e),Ne(e),Ae(e),Me(e,i),xe(e),we(e,i);break;default:r("Unsupported browser!")}return n}({window:"undefined"==typeof window?void 0:window});var Be,He,Fe;!function(e){e.FPS_10="FPS_10",e.FPS_15="FPS_15",e.FPS_24="FPS_24",e.FPS_30="FPS_30"}(Be||(Be={})),function(e){e.W176_H132="W176_H132",e.W176_H144="W176_H144",e.W256_H144="W256_H144",e.W320_H180="W320_H180",e.W240_H240="W240_H240",e.W320_H240="W320_H240",e.W480_H360="W480_H360",e.W640_H360="W640_H360",e.W480_H480="W480_H480",e.W640_H480="W640_H480",e.W720_H480="W720_H480",e.W1280_H720="W1280_H720",e.W1920_H1080="W1920_H1080"}(He||(He={})),function(e){e[e.AUDIO_ONLY=0]="AUDIO_ONLY",e[e.VIDEO_ONLY=1]="VIDEO_ONLY",e[e.AUDIO_VIDEO=2]="AUDIO_VIDEO"}(Fe||(Fe={}));const Ke={[He.W176_H132]:{width:176,height:132,maxBitrate:150,minBitrate:80},[He.W176_H144]:{width:176,height:144,maxBitrate:160,minBitrate:80},[He.W256_H144]:{width:256,height:144,maxBitrate:240,minBitrate:120},[He.W320_H180]:{width:320,height:180,maxBitrate:280,minBitrate:120},[He.W240_H240]:{width:240,height:240,maxBitrate:280,minBitrate:120},[He.W320_H240]:{width:320,height:240,maxBitrate:400,minBitrate:120},[He.W480_H360]:{width:480,height:360,maxBitrate:650,minBitrate:150},[He.W640_H360]:{width:640,height:360,maxBitrate:800,minBitrate:180},[He.W480_H480]:{width:480,height:480,maxBitrate:800,minBitrate:180},[He.W640_H480]:{width:640,height:480,maxBitrate:900,minBitrate:200},[He.W720_H480]:{width:720,height:480,maxBitrate:1e3,minBitrate:200},[He.W1280_H720]:{width:1280,height:720,maxBitrate:2200,minBitrate:250},[He.W1920_H1080]:{width:1920,height:1080,maxBitrate:4e3,minBitrate:400}},Ge=(e,t)=>{const r=e*t;let i=Number.MAX_VALUE,n=null;for(const e in Ke){const t=Ke[e],s=Math.abs(t.width*t.height-r);s<i&&(n=t,i=s)}return n},Je={10:1,15:1,24:1.5,30:1.5},We=e=>{let t=Number.MAX_VALUE,r=1;for(const i in Je){const n=Math.abs(e-parseInt(i));n<t&&(t=n,r=Je[i])}return r},Ye={getCameras:()=>S(void 0,void 0,void 0,(function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"videoinput"===e.kind))})),getMicrophones:()=>S(void 0,void 0,void 0,(function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"audioinput"===e.kind))})),getSpeakers:()=>S(void 0,void 0,void 0,(function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"audiooutput"===e.kind))}))};class qe extends t{constructor(e,t,r,i,n){super(),this._tag=e,this._userId=t,this._kind=r,this._isLocalTrack=i,this._roomId=n,this._localMuted=!1,this._remoteMuted=!1,this._streamId=[this._userId||this._roomId,this._tag].join("_"),this._id=[this._streamId,this.isAudioTrack()?0:1].join("_")}getStreamId(){return this._streamId}getTrackId(){return this._id}getUserId(){return this._userId}__innerGetMediaStreamTrack(){return this._msTrack}getTag(){return this._tag}isLocalTrack(){return this._isLocalTrack}isVideoTrack(){return"video"===this._kind}isAudioTrack(){return"audio"===this._kind}isReady(){var e;return"live"===(null===(e=this._msTrack)||void 0===e?void 0:e.readyState)}__innerSetMediaStreamTrack(e){this._msTrack=e,this._setLocalMuted(this._localMuted);const t=this._msStream=this._msStream||new MediaStream,r=t.getTracks()[0];r&&t.removeTrack(r),e?t.addTrack(e):this._element&&(this._element.pause(),this._element.srcObject=null)}_setLocalMuted(e){this._msTrack&&(this._msTrack.enabled=!e),this._localMuted=e}mute(){C.info(`set ${this._id} enabled: false`),this._setLocalMuted(!0)}unmute(){C.info(`set ${this._id} enabled: true`),this._setLocalMuted(!1)}isLocalMuted(){return this._localMuted}isMCUTrack(){return Boolean(this._roomId)}isOwnerMuted(){return this._remoteMuted}play(e,t){return S(this,void 0,void 0,(function*(){if(!this._msTrack)return C.warn(`the track is not ready to play -> id: ${this._id}`),{code:T.TRACK_NOT_READY};if("ended"===this._msTrack.readyState&&C.warn(`the track's readyState is 'ended' -> id: ${this._id}`),null==t?void 0:t.volume){if(!r(null==t?void 0:t.volume))return C.error(`${null==t?void 0:t.volume} is not a number, the valid range of options.volume is 0-100`),{code:T.PARAMS_ERROR};(null==t?void 0:t.volume)<0&&(t.volume=0,C.warn("the valid range of options.volume is 0-100, the value of volume has been set 0")),(null==t?void 0:t.volume)>100&&(t.volume=100,C.warn("the valid range of options.volume is 0-100, the value of volume has been set 100"))}if(null==t?void 0:t.audioDeviceId){if(!(yield Ye.getSpeakers()).map((e=>e.deviceId)).includes(t.audioDeviceId))return C.error(`the options.audioDeviceId is invalid --\x3e ${t.audioDeviceId}`),{code:T.PARAMS_ERROR}}const i=this.isVideoTrack();if(i&&(!e||!(e instanceof HTMLVideoElement)))return C.error(`the video track need an <video> to play -> id: ${this._id}`),{code:T.VIDEO_TRACK_MISS_MEDIA_ELEMENT};this._element=i?e:this._element||new Audio,this._localMuted&&this._setLocalMuted(!1),this._element.srcObject&&this._element.srcObject===this._msStream||this._element.pause(),this._element.onloadstart=e=>{var t;C.debug(`HTMLMediaElement onloadstart -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`)},this._element.ondurationchange=e=>{var t;C.debug(`HTMLMediaElement ondurationchange -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`)},this._element.onloadedmetadata=e=>{var t;C.debug(`HTMLMediaElement onloadedmetadata -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`)},this._element.onloadeddata=e=>{var t;C.debug(`HTMLMediaElement onloadeddata -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`)},this._element.onabort=e=>{var t;C.info(`HTMLMediaElement onabort -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`)},this._element.oncanplay=e=>{var t;C.info(`HTMLMediaElement oncanplay -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`)},this._element.onvolumechange=e=>{var t;const r=Math.floor(100*(null===(t=e.target)||void 0===t?void 0:t.volume));C.info(`HTMLMediaElement onvolumechange -> volume: ${r}, trackId: ${this._id}`)},this._element.srcObject=this._msStream,this._element.autoplay=!0,i&&(this._element.playsInline=!0,this._element.x5PlaysInline=!0,this._element.webkitPlaysInline=!0),i||!(null==t?void 0:t.volume)&&0!==(null==t?void 0:t.volume)||(this._element.volume=(null==t?void 0:t.volume)/100);try{(null==t?void 0:t.audioDeviceId)&&!i?yield this._element.setSinkId(t.audioDeviceId):this._element.play()}catch(e){return"No permission to use requested device"===e.message?(C.error(`setSinkId failed -> ${e.message}`),{code:T.NO_PERMISSION_TO_USE_REQUESTED_DEVICE}):(C.error(e),{code:T.TRACK_PLAY_ERROR})}return{code:T.SUCCESS}}))}__innerDestroy(){this.__innerSetMediaStreamTrack(void 0)}__releaseMediaElement(){this._element&&(this._element.remove(),this._element.srcObject=null)}}class ze extends qe{constructor(e,t,r,i){super(e,t,r,!0),this._isPublished=!1,this.__innerSetMediaStreamTrack(i),i.onended=()=>{i.onended=null,this.emit(ze.EVENT_LOCAL_TRACK_END,this),this.removeAll(ze.EVENT_LOCAL_TRACK_END)}}_setLocalMuted(e){const t=this._localMuted!==e;super._setLocalMuted(e),this._remoteMuted=this._localMuted,t&&this.emit(ze.__INNER_EVENT_MUTED_CHANGE__,this)}__innerSetPublished(e){this._isPublished=e}isPublished(){return this._isPublished}destroy(){var e;C.info(`track is destroyed -> trackId: ${this.getTrackId()}`),null===(e=this._msTrack)||void 0===e||e.stop(),super.__innerDestroy(),this.isAudioTrack()&&super.__releaseMediaElement(),this.emit(ze.__INNER_EVENT_DESTROY__,this)}setBitrate(e=0,t=0,i=0){!r(e)||!r(t)||!r(i)||e<=0||t<=0||e<t?C.error("setBitrate params error ->"):this._bitrateInfo={max:e,min:t,start:i}}getBitrate(){var e,t;const{min:r,max:i}=this._msTrack?_t(this._msTrack):{min:0,max:0};return{min:(null===(e=this._bitrateInfo)||void 0===e?void 0:e.min)||r,max:(null===(t=this._bitrateInfo)||void 0===t?void 0:t.max)||i}}}ze.EVENT_LOCAL_TRACK_END="local-track-end",ze.__INNER_EVENT_MUTED_CHANGE__="inner-muted-change",ze.__INNER_EVENT_DESTROY__="inner-destroy";class Qe extends ze{constructor(e,t,r){super(e,t,"audio",r)}setBitrate(e,t,r){C.warn("`setBitrate` invalid for audio track")}getBitrate(){return{start:32,max:32,min:32}}}class Xe extends ze{constructor(e,t,r,i=!1){super(e,t,"video",r),this._isTiny=i}__isTiny(){return this._isTiny}getStreamId(){const e=super.getStreamId();return this._isTiny?`${e}_tiny`:e}getTrackId(){const e=super.getTrackId();return this._isTiny?`${e}_tiny`:e}}class Ze extends ze{constructor(e,t,r,i,n){super(e,t,r,i),this._resource=n,Ze.__innerSetMapping(this.getTrackId(),n)}static __innerSetMapping(e,t){const r=this._mapping.get(t)||[];r.push(e),this._mapping.set(t,r)}static __innerRemoveMapping(e,t){var r,i;const n=null===(r=this._mapping.get(t))||void 0===r?void 0:r.filter((t=>t!==e));n&&n.length>0?this._mapping.set(t,n):(this._mapping.delete(t),t.pause(),t.src="",null===(i=t.parentNode)||void 0===i||i.removeChild(t))}destroy(){this.isAudioTrack()&&this.mute(),Ze.__innerRemoveMapping(this.getTrackId(),this._resource),super.destroy()}}Ze._mapping=new Map;class et extends Ze{constructor(e,t,r,i){super(e,t,"video",r,i)}}class tt extends Ze{constructor(e,t,r,i){super(e,t,"audio",r,i)}_setLocalMuted(e){this._resource&&(this._resource.muted=e),super._setLocalMuted(e)}play(){return this._setLocalMuted(!1),Promise.resolve({code:T.SUCCESS})}}class rt extends Qe{}class it extends Xe{}class nt extends Xe{}class st extends qe{constructor(e,t,r,i){super(e,t,r,!1,i),this._isSubscribed=!1}__innerSetRemoteMuted(e){this._remoteMuted=e}__innerSetSubscribed(e){this._isSubscribed=e}isSubscribed(){return this._isSubscribed}}class ot extends st{constructor(e,t,r){super(e,t,"audio",r)}}class at extends st{constructor(e,t,r){super(e,t,"video",r)}}const ct=(e,t)=>({name:e,content:JSON.stringify({uris:t,ignore:!0})}),dt=e=>JSON.stringify(e),ut=e=>/^[a-zA-Z\d-=]+$/g.test(e),lt="http:"!==location.protocol||["localhost","127.0.0.1"].includes(location.hostname),ht=e=>{if(void 0===e)return 0;if(r(e))return e;const t=e;return t.exact||t.ideal||t.max||0},pt=e=>{const t=e.getConstraints();return{width:ht(t.width),height:ht(t.height),frameRate:ht(t.frameRate)}},_t=e=>{const{width:t,height:r,frameRate:i}=pt(e),n=Ge(t,r),s=We(i);return{min:n.minBitrate*s,max:n.maxBitrate*s}},mt=e=>[e.msid,e.mediaType].join("_"),ft=e=>{const t=e.split("_");return{mediaType:parseInt(t.pop()),tag:t.pop(),userId:t.join("_")}},vt=(e,t)=>[e,t].join("_"),Rt=e=>e.map((e=>Object.assign({},e))),gt=(e,t,r=!1)=>{e=e.slice();const i=[],n=[],s=[];return t.forEach((t=>{const n=mt(t);let o=e.findIndex((e=>mt(e)===n));if(r&&(o=e.findIndex((e=>e.uri===t.uri))),-1===o)return void i.push(t);const a=e[o];a.uri!==t.uri?i.push(t):a.state!==t.state&&s.push(t),e.splice(o,1)})),n.push(...e),{publishedList:i,unpublishedList:n,modifiedList:s}},St=()=>{let e="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}));return e=e.replace(/-/g,"")+"0",e=parseInt(e,16),e=(e=>{const t="0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ+/".split(""),r=t.length+1;let i=+e;const n=[];do{const e=i%r;i=(i-e)/r,n.unshift(t[e])}while(i);return n.join("")})(e),e.length>22&&(e=e.slice(0,22)),e},Ct=e=>{const[t,r]=e.split("_").map((e=>parseInt(e.replace(/[^\d]/g,""))));return{width:t,height:r}},Tt=e=>!!He[e],It=e=>!!Be[e],Et=e=>parseInt(e.replace("FPS_","")),yt=(()=>{const{browser:e,version:t,supportsUnifiedPlan:r}=Ve.browserDetails;return{browser:e,version:t,supportsUnifiedPlan:!1!==r}})();function kt(){return"captureStream"in HTMLMediaElement.prototype||"mozCaptureStream"in HTMLMediaElement.prototype}function bt(){return"mediaDevices"in navigator&&"getDisplayMedia"in navigator.mediaDevices}const Pt=e=>"[object Null]"===Object.prototype.toString.call(e),Ot=e=>1===e.type,Lt=e=>{const t={},r=Object.keys(e.users);return r.length&&r.forEach((r=>{const i=[],n=e.users[r];if(n.uris)try{i.push(...JSON.parse(n.uris))}catch(e){C.warn(`invalid user data -> userId: ${r}, userData: ${n}`)}t[r]=i})),t};var Nt,Dt;!function(e){e.PUBLISH="RCRTC:PublishResource",e.UNPUBLISH="RCRTC:UnpublishResource",e.MODIFY="RCRTC:ModifyResource",e.TOTAL_CONTENT_RESOURCE="RCRTC:TotalContentResources",e.STATE="RCRTC:state",e.ROOM_NOTIFY="RCRTC:RoomNtf",e.USER_NOTIFY="RCRTC:UserNtf",e.KICK="RCRTC:kick",e.PK_INVITE="RCRTC:invite",e.PK_INVITE_TIMEOUT="RCRTC:inviteTimeout",e.PK_CANCEL_INVITE="RCRTC:cancelInvite",e.PK_INVITE_ANSWER="RCRTC:answerInvite",e.PK_END="RCRTC:endInvite",e.OTHER_ROOM_OFFLINE="RCRTC:otherRoomOffline"}(Nt||(Nt={})),function(e){e.SUCCESS="Success",e.FAIL="Fail"}(Dt||(Dt={}));class At{constructor(e,t,r,i=1e4){this._roomId=e,this._roomMode=t,this._context=r,this._gap=i,this._latestTimestamp=Date.now(),this._timer=null}start(){return S(this,void 0,void 0,(function*(){this._timer||(this._timer=setInterval(this._loop.bind(this),this._gap))}))}_loop(){var e,t,r;return S(this,void 0,void 0,(function*(){const n=yield new Promise((e=>{this._context.rtcPing(this._roomId,this._roomMode).then(e).catch((t=>{C.error(`rtcping receive unknown error -> ${t}`),e(i.UNKNOWN)})),setTimeout(e,1e4,i.TIMEOUT)})),s=Date.now();if(n===i.SUCCESS)return this._latestTimestamp=s,void(null===(e=this.onPingResult)||void 0===e||e.call(this,Dt.SUCCESS));null===(t=this.onPingResult)||void 0===t||t.call(this,Dt.FAIL),C.warn(`rtcping failed -> code: ${n}`),(40003===n||s-this._latestTimestamp>6e4)&&(this.stop(),null===(r=this.onFailed)||void 0===r||r.call(this,40003===n))}))}stop(){this._timer&&(clearInterval(this._timer),this._timer=null)}}var Mt;!function(e){e[e.NORMAL=1]="NORMAL",e[e.TINY=2]="TINY"}(Mt||(Mt={}));const xt=(e,t)=>Math.round(8*t/e),Ut=(e,t=2)=>{const r=10**t;return Math.round(e*r)/r},wt=(e,t=2)=>{e>1&&(e/=32767);const r=10**t;return Math.ceil(e*r)},$t=(e,t,r,i)=>{if(0===t)return 0;if(!r||!i)return Ut(e/t,3);const n=t-i;if(0===n)return 0;const s=e-r;return s<0||n<0?0:Ut(s/n,3)},jt=e=>{const{jitter:t,rtt:r,packetsLostRate:i}=e;return!Pt(t)||!Pt(r)||0!==i};class Vt{constructor(e,t){this._rtcPeerConn=e,this._sdpSemantics=t,this._latestPacketsSent={},this._latestBytesSent={},this._latestBytesRecv={},this._latestPacketsRecv={}}updateBytesSent(e,t,r){let i,n;if(this._latestBytesSent[e]&&t<this._latestBytesSent[e].bytesSent&&this.clearLatestpacketsSent([e]),this._latestBytesSent[e]){const{bytesSent:s,timestamp:o}=this._latestBytesSent[e];i=t-s,n=r-o,this._latestBytesSent[e]={bytesSent:t,timestamp:r}}else i=t,n=1e3,this._latestBytesSent[e]={bytesSent:t,timestamp:r};return xt(n,i)}updateBytesRecv(e,t,r){let i,n;if(this._latestBytesRecv[e]&&t<this._latestBytesRecv[e].bytesRecv&&this.clearLatestPacketsRecv([e]),this._latestBytesRecv[e]){const{bytesRecv:s,timestamp:o}=this._latestBytesRecv[e];i=t-s,n=r-o,this._latestBytesRecv[e]={bytesRecv:t,timestamp:r}}else i=t,n=1e3,this._latestBytesRecv[e]={bytesRecv:t,timestamp:r};return xt(n,i)}updateSenderPacketsLost(e,t,r){let i;if(Object.prototype.hasOwnProperty.call(this._latestPacketsSent[e],"packetsSent")){const{packetsLost:n,packetsSent:s}=this._latestPacketsSent[e];i=$t(t,r,n,s),this._latestPacketsSent[e].packetsLost=t,this._latestPacketsSent[e].packetsSent=n===t?s:r}else i=$t(t,r),this._latestPacketsSent[e].packetsLost=t,this._latestPacketsSent[e].packetsSent=r;return i}updateReceiverPacketsLost(e,t,r){let i;if(this._latestPacketsRecv[e]){const{packetsLost:n,packetsRecv:s}=this._latestPacketsRecv[e];i=$t(t,r+t,n,s+n)}else i=$t(t,r);return this._latestPacketsRecv[e]={packetsLost:t,packetsRecv:r},i}clearLatestpacketsSent(e){e.forEach((e=>{if(parseInt(e.split("_").pop())===Fe.VIDEO_ONLY){const t=`${e}_tiny`;delete this._latestPacketsSent[t],delete this._latestBytesSent[t]}delete this._latestPacketsSent[e],delete this._latestBytesSent[e]}))}clearLatestPacketsRecv(e){e.forEach((e=>{delete this._latestPacketsRecv[e],delete this._latestBytesRecv[e]}))}parseRTCStatsReport(e){const t=e.keys(),r={};let i=t.next();for(;!i.done;){const n=i.value,s=e.get(n);/^RTCCodec_/.test(n)||(r[n]=s),i=t.next()}return r}formatRCRTCStateReport(e){return{senders:[],receivers:[]}}getAudioLevelList(e){return[]}getResourceIdByParseSdp(e){var t,r;const i=e.ssrc,n=e.kind||e.mediaType,s=null===(t=this._rtcPeerConn.currentLocalDescription)||void 0===t?void 0:t.sdp,o=null===(r=this._rtcPeerConn.currentRemoteDescription)||void 0===r?void 0:r.sdp;let a;a="unified-plan"===this._sdpSemantics?new RegExp("a=msid:(.*?) "):new RegExp(`a=ssrc:${i} msid:(.*?) `);const c=null==s?void 0:s.split("\r\nm="),d=null==c?void 0:c.filter((e=>e.includes(`a=ssrc:${i}`)))[0],u=null==d?void 0:d.match(a);let l=u?u[1]:"";if(l)return`${l}_${"video"===n?1:0}`;const h=null==o?void 0:o.split("\r\nm="),p=null==h?void 0:h.filter((e=>e.includes(`a=ssrc:${i}`)))[0],_=null==p?void 0:p.match(a);return l=_?_[1]:"",`${l}_${"video"===n?1:0}`}isValidSender(e){var t;const r=null===(t=this._rtcPeerConn.currentLocalDescription)||void 0===t?void 0:t.sdp,{ssrc:i}=e;return!(null==r?void 0:r.split("\r\nm=").some((e=>e.includes(i)&&e.includes("a=inactive"))))}isValidReceiver(e){var t;const r=null===(t=this._rtcPeerConn.currentRemoteDescription)||void 0===t?void 0:t.sdp,{ssrc:i}=e;return!(null==r?void 0:r.split("\r\nm=").some((e=>e.includes(i)&&e.includes("a=inactive"))))}}class Bt extends Vt{formatRCRTCStateReport(e){const t={senders:[],receivers:[]},r=Math.floor(e.RTCPeerConnection.timestamp);t.timestamp=r;const i=Object.keys(e);let n=0,s=0;i.filter((e=>/^RTCOutboundRTP(Video|Audio)Stream_/.test(e))).forEach((i=>{const o=e[i];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(o))return;const{id:a,kind:c,transportId:d,mediaSourceId:u,remoteId:l,packetsSent:h,bytesSent:p,trackId:_,encoderImplementation:m,pliCount:f,nackCount:v,firCount:R}=o;if(!_)return;let{framesPerSecond:g,frameWidth:S,frameHeight:C}=o;"video"!==c||S||C||g||(S=e[_].frameWidth,C=e[_].frameHeight,g=u?e[u].framesPerSecond:null);const T=e[l];let I=null,E=null,y=0;T&&(I=T.jitter,E=T.roundTripTime,y=T.packetsLost),n+=y;const k=this.getResourceIdByParseSdp(o),b=u?e[u].audioLevel:e[_].audioLevel;let P=null;!this._latestPacketsSent[k]&&(this._latestPacketsSent[k]={}),T?P=this.updateSenderPacketsLost(k,y,h):this._latestPacketsSent[k].crtPacketsSent=h;let O=this.updateBytesSent(k,p,r);O<0&&(O=0),s+=O,t.senders.push({id:a,trackId:k,kind:c,packetsLostRate:P,remoteResource:!1,audioLevel:b||0===b?wt(b):null,frameWidth:S,frameHeight:C,frameRate:g,bitrate:O,jitter:I?Math.round(1e3*I):I,rtt:E,encoderImplementation:m,pliCount:f,nackCount:v,googFirsSent:-1,samplingRate:-1,googRenderDelayMs:-1,trackState:-1})}));i.filter((e=>/RTCRemoteInboundRtp(Video|Audio)Stream_/.test(e))).forEach((r=>{const{localId:i,jitter:n,roundTripTime:s,packetsLost:o}=e[r],a=t.senders.filter((e=>e.id===i))[0];if(a&&!jt(a)){const t=this.getResourceIdByParseSdp(e[a.id]);a.jitter=Math.round(1e3*n),a.rtt=s;const r=this._latestPacketsSent[t].crtPacketsSent;a.packetsLostRate=this.updateSenderPacketsLost(t,o,r)}}));let o=0;i.filter((e=>/^RTCInboundRTP(Video|Audio)Stream_/.test(e))).forEach((i=>{const s=e[i];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(s))return;const{trackId:a,packetsLost:c,packetsReceived:d,jitter:u,bytesReceived:l,framesPerSecond:h,kind:p,codecImplementationName:_,nackCount:m,pliCount:f}=s;if(!a)return;let{frameWidth:v,frameHeight:R,audioLevel:g}=s;"video"===p?v||R||(v=e[a].frameWidth,R=e[a].frameHeight):g||(g=e[a].audioLevel),n+=c;const S=this.getResourceIdByParseSdp(s),C=this.updateReceiverPacketsLost(S,c,d);let T=this.updateBytesRecv(S,l,r);T<0&&(T=0),o+=T,t.receivers.push({trackId:S,kind:p,packetsLostRate:C,remoteResource:!0,audioLevel:g||0===g?wt(g):null,frameWidth:v,frameHeight:R,frameRate:h,bitrate:T,jitter:u?Math.round(1e3*u):0,codecImplementationName:_,nackCount:m,pliCount:f,rtt:null,samplingRate:-1,googFirsReceived:-1,googRenderDelayMs:-1,trackState:-1})}));const a=i.filter((e=>/^RTCTransport_/.test(e)))[0];if(a){const r=e[a],{selectedCandidatePairId:i}=r;if(i){const r=e[i],{availableOutgoingBitrate:a,availableIncomingBitrate:c,currentRoundTripTime:d,localCandidateId:u,remoteCandidateId:l}=r,h=e[u],{ip:p,port:_,networkType:m}=h,f=e[l],{ip:v,port:R,protocol:g}=f;t.iceCandidatePair={IP:p,port:_,networkType:m,remoteIP:v,remotePort:R,protocol:g,bitrateRecv:o,bitrateSend:s,rtt:1e3*d,availableOutgoingBitrate:a,availableIncomingBitrate:c,totalPacketsLost:n},t.receivers.forEach((e=>{e.rtt=d}))}}return t}getAudioLevelList(e){const t=[],r=Object.keys(e);r.filter((e=>/^RTCOutboundRTPAudioStream_/.test(e))).forEach((r=>{var i;const n=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(n))return;const{mediaSourceId:s,trackId:o}=n,a=this.getResourceIdByParseSdp(n),c=s&&e[s]?e[s].audioLevel:(null===(i=e[o])||void 0===i?void 0:i.audioLevel)||null;t.push({trackId:a,audioLevel:c||0===c?wt(c):null})}));return r.filter((e=>/^RTCInboundRTPAudioStream_/.test(e))).forEach((r=>{const i=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(i))return;const{trackId:n}=i,s=i.audioLevel||e[n].audioLevel,o=this.getResourceIdByParseSdp(i);t.push({trackId:o,audioLevel:s||0===s?wt(s):null})})),t}}class Ht extends Vt{formatRCRTCStateReport(e){const t=+new Date,r={senders:[],receivers:[],timestamp:t};let i=0,n=0,s=0;for(const o in e){const a=e[o],c=a.type;if("outbound-rtp"===c){if("unified-plan"===this._sdpSemantics&&!this.isValidSender(a))continue;const{id:s,kind:o,bytesSent:c,packetsSent:d,bitrateMean:u,framerateMean:l,nackCount:h,pliCount:p,remoteId:_}=a,{jitter:m,roundTripTime:f,packetsLost:v}=_?e[_]:{jitter:null,roundTripTime:null,packetsLost:0},R=this.getResourceIdByParseSdp(a);i+=v;let g=null;!this._latestPacketsSent[R]&&(this._latestPacketsSent[R]={}),_?g=this.updateSenderPacketsLost(R,v,d):this._latestPacketsSent[R].crtPacketsSent=d;let S=0;"video"===o?u&&(S=Math.floor(u/1e3)):S=this.updateBytesSent(R,c,t),S<0&&(S=0),n+=S,r.senders.push({trackId:R,kind:o,packetsLostRate:g,remoteResource:!1,audioLevel:null,frameWidth:null,frameHeight:null,frameRate:Math.floor(l),bitrate:S,jitter:m?Math.round(1e3*m):null,rtt:f,encoderImplementation:null,pliCount:p,nackCount:h,googFirsSent:-1,samplingRate:-1,googRenderDelayMs:-1,trackState:-1})}if("remote-inbound-rtp"===c){const{localId:t}=a,i=this.getResourceIdByParseSdp(e[t]),n=r.senders.filter((e=>e.trackId===i))[0];n&&jt(n)&&(n.jitter=Math.round(1e3*a.jitter),n.rtt=a.rtt,n.packetsLostRate=this.updateSenderPacketsLost(i,a.packetsLost,this._latestPacketsSent[i].crtPacketsSent))}if("inbound-rtp"===c){if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(a))continue;const{id:e,packetsLost:n,bytesReceived:o,packetsReceived:c,jitter:d,framerateMean:u,kind:l,bitrateMean:h,nackCount:p,pliCount:_}=a,m=this.getResourceIdByParseSdp(a);i+=n;const f=this.updateReceiverPacketsLost(m,n,c);let v=0;"video"===l?h&&(v=Math.floor(h/1e3)):v=this.updateBytesRecv(m,o,t),v<0&&(v=0),s+=v,r.receivers.push({trackId:m,kind:l,packetsLostRate:f,remoteResource:!0,audioLevel:null,frameWidth:null,frameHeight:null,frameRate:Math.floor(u),bitrate:v,jitter:d?Math.round(1e3*d):null,codecImplementationName:null,nackCount:p,pliCount:_,rtt:null,samplingRate:-1,googFirsReceived:-1,googRenderDelayMs:-1,trackState:-1})}if("candidate-pair"===c&&"succeeded"===a.state){const t=e[a.localCandidateId],{address:o,port:c}=t,d=e[a.remoteCandidateId],{address:u,port:l,protocol:h}=d;r.iceCandidatePair={IP:o,port:c,networkType:null,remoteIP:u,remotePort:l,protocol:h,bitrateRecv:s,bitrateSend:n,rtt:null,availableOutgoingBitrate:null,availableIncomingBitrate:null,totalPacketsLost:i}}}return r.iceCandidatePair&&(r.iceCandidatePair.bitrateSend=n),r.iceCandidatePair&&(r.iceCandidatePair.bitrateRecv=s),r}getAudioLevelList(e){const t=[];for(const r in e){const i=e[r],n=i.type;if("outbound-rtp"===n){if("unified-plan"===this._sdpSemantics&&!this.isValidSender(i))continue;const{kind:e}=i;if("video"===e)continue;const r=this.getResourceIdByParseSdp(i);t.push({trackId:r,audioLevel:null})}if("inbound-rtp"===n){if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(i))continue;const{kind:e}=i;if("video"===e)continue;const r=this.getResourceIdByParseSdp(i);t.push({trackId:r,audioLevel:null})}}return t}}class Ft extends Vt{formatRCRTCStateReport(e){const t={senders:[],receivers:[]},r=Math.floor(e.RTCPeerConnection.timestamp);t.timestamp=r;const i=Object.keys(e);let n=0,s=0;i.filter((e=>/^RTCOutboundRTP(Video|Audio)Stream_/.test(e))).forEach((i=>{const n=e[i];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(n))return;const o=this.getResourceIdByParseSdp(n),{mediaType:a,transportId:c,remoteId:d,packetsSent:u,bytesSent:l,trackId:h,encoderImplementation:p,pliCount:_,nackCount:m,firCount:f}=n;if(!h)return;const{audioLevel:v,frameHeight:R,frameWidth:g}=e[h];let S=this.updateBytesSent(o,l,r);S<0&&(S=0),s+=S,t.senders.push({trackId:o,kind:a,packetsLostRate:null,remoteResource:!1,audioLevel:v||0===v?wt(v):null,frameWidth:g,frameHeight:R,frameRate:null,bitrate:S,jitter:null,rtt:null,encoderImplementation:p,pliCount:_,nackCount:m,googFirsSent:-1,samplingRate:-1,googRenderDelayMs:-1,trackState:-1})}));let o=0;i.filter((e=>/^RTCInboundRTP(Video|Audio)Stream_/.test(e))).forEach((i=>{const s=e[i];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(s))return;const{trackId:a,packetsLost:c,packetsReceived:d,jitter:u,bytesReceived:l,mediaType:h,nackCount:p,pliCount:_}=s,m=this.getResourceIdByParseSdp(s);if(!a)return;const{frameHeight:f,frameWidth:v,audioLevel:R}=e[a];n+=c;const g=this.updateReceiverPacketsLost(m,c,d);let S=this.updateBytesRecv(m,l,r);S<0&&(S=0),o+=S,t.receivers.push({trackId:m,kind:h,packetsLostRate:g,remoteResource:!0,audioLevel:R||0===R?wt(R):null,frameWidth:v,frameHeight:f,frameRate:null,bitrate:S,jitter:u,codecImplementationName:null,nackCount:p,pliCount:_,rtt:null,samplingRate:-1,googFirsReceived:-1,googRenderDelayMs:-1,trackState:-1})}));const a=i.filter((e=>/^RTCTransport_/.test(e)))[0];if(a){const r=e[a],{selectedCandidatePairId:i}=r;if(i){const r=e[i],{availableOutgoingBitrate:a,availableIncomingBitrate:c,currentRoundTripTime:d,localCandidateId:u,remoteCandidateId:l}=r,h=e[u],{address:p,port:_}=h,m=e[l],{address:f,port:v,protocol:R}=m;t.iceCandidatePair={IP:p||null,port:_,networkType:null,remoteIP:f,remotePort:v,protocol:R,bitrateRecv:o,bitrateSend:s,rtt:1e3*d,availableOutgoingBitrate:a,availableIncomingBitrate:c,totalPacketsLost:n},t.receivers.forEach((e=>{e.rtt=d}))}}return t}getAudioLevelList(e){const t=[],r=Object.keys(e);r.filter((e=>/^RTCOutboundRTP(Video|Audio)Stream_/.test(e))).forEach((r=>{const i=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(i))return;const{trackId:n,mediaType:s}=i;if("video"===s)return;const o=this.getResourceIdByParseSdp(i),a=e[n];t.push({trackId:o,audioLevel:a||0===a?wt(a):null})}));return r.filter((e=>/^RTCInboundRTP(Video|Audio)Stream_/.test(e))).forEach((r=>{const i=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(i))return;const{trackId:n,mediaType:s}=i;if(!n||"video"===s)return;const{audioLevel:o}=e[n],a=this.getResourceIdByParseSdp(i);t.push({trackId:a,audioLevel:o||0===o?wt(o):null})})),t}}class Kt{constructor(e){this._peer=e,this._outboundStreams={}}static setSdpSemantics(e){const{browser:t,version:r,supportsUnifiedPlan:i}=yt;i?/chrome/i.test(t)?this._sdpSemantics=r>92?"unified-plan":r<72?"plan-b":e:/firefox/i.test(t)?this._sdpSemantics="unified-plan":/safari/i.test(t)?this._sdpSemantics=r<12?"plan-b":"unified-plan":this._sdpSemantics="unified-plan":this._sdpSemantics="plan-b"}static getSdpSemantics(){return Kt._sdpSemantics}getOutboundVideoInfo(){const e=[];for(const t in this._outboundStreams){const r=this._outboundStreams[t].getVideoTracks()[0];if(!r)continue;const i=/_tiny$/.test(t),{width:n,height:s}=pt(r);e.push({trackId:r.id,simulcast:i?Mt.TINY:Mt.NORMAL,resolution:`${n}x${s}`})}return e}setRemoteAnswer(e){return S(this,void 0,void 0,(function*(){e=e.replace(/\s+\r\n/g,"\r\n");try{yield this._peer.setRemoteDescription({type:"answer",sdp:e})}catch(e){return C.error(e),T.SET_REMOTE_DESCRIPTION_FAILED}return T.SUCCESS}))}getStatParsr(e,t){return/chrome/i.test(yt.browser)?new Bt(e,t):/Firefox/i.test(yt.browser)?new Ht(e,t):/Safari/i.test(yt.browser)?new Ft(e,t):null}}class Gt extends Kt{constructor(){super(...arguments),this.senders={},this._localTracks=[]}addLocalTrack(e){this._localTracks.includes(e)||this._localTracks.push(e);const t=e.getStreamId(),r=e.__innerGetMediaStreamTrack(),i=this._outboundStreams[t]||(this._outboundStreams[t]=new MediaStream);i.getTracks().forEach((e=>{e.kind===r.kind&&i.removeTrack(e)})),i.addTrack(r);const n=e.getTrackId(),s=this.senders[n];s?s.replaceTrack(r):this.senders[n]=this._peer.addTrack(r,i)}removeLocalTrack(e){const t=this._localTracks.findIndex((t=>t===e));t>=0&&this._localTracks.splice(t,1);const r=e.getTrackId(),i=this.senders[r];i&&(i.replaceTrack(null),this._peer.removeTrack(i),delete this.senders[r])}updateSubRemoteTracks(e){}updateRecvTransceiverMap(e,t){}setBitrate(e,t,r){this._maxBitrate=e,this._minBitrate=t,this._startBitrate=r||.7*e}createOffer(e){return S(this,void 0,void 0,(function*(){const t=yield this._peer.createOffer({iceRestart:e,offerToReceiveAudio:!0,offerToReceiveVideo:!0});for(const e in this._outboundStreams){const r=this._outboundStreams[e].id;t.sdp=t.sdp.replace(new RegExp(r,"g"),e)}return yield this._peer.setLocalDescription(t),{type:"offer",semantics:"plan-b",sdp:t.sdp}}))}setRemoteAnswer(e){let t=0,r=0;this._localTracks.forEach((e=>{const{min:i,max:n}=e.getBitrate();r+=i,t+=n})),t=this._maxBitrate&&this._maxBitrate>0?Math.min(t,this._maxBitrate):t,r=this._minBitrate&&this._minBitrate>0?Math.max(r,this._minBitrate):r;const i=this._startBitrate||Math.round(.7*t),n=`b=AS:${t}`;e=e.replace(/[\r\n]+m=video[^\r\n]+/,(e=>`${e}\r\n${n}`));const s=[`;x-google-min-bitrate=${r}`,`;x-google-max-bitrate=${t}`,`;x-google-start-bitrate=${i}`].join("");return e=e.replace(/[\r\n]+[^\r\n]+profile-level-id[^\r\n]+/g,(e=>e+s)),super.setRemoteAnswer(e)}}class Jt extends Kt{constructor(){super(...arguments),this._sendTransceiver={},this._localTracks={},this._recvAudio=[],this._recvVideo=[],this._recvTransceiver={},this._subedTracks=[]}setBitrate(e,t,r){C.warn("the interface named `setBitrate` is invalid while sdpSemantics value is `unified-plan`")}addLocalTrack(e){const t=e.getTrackId(),r=e.getStreamId(),i=e.__innerGetMediaStreamTrack();this._localTracks[t]=e;const n=this._outboundStreams[r]||(this._outboundStreams[r]=new MediaStream);n.getTracks().forEach((e=>{e.kind===i.kind&&n.removeTrack(e)})),n.addTrack(i);const s=this._sendTransceiver[t];s?(s.sender.replaceTrack(i),s.direction="sendonly"):this._sendTransceiver[t]=this._peer.addTransceiver(i,{direction:"sendonly",streams:[n]})}removeLocalTrack(e){const t=e.getTrackId(),r=e.getStreamId();e.__innerGetMediaStreamTrack(),delete this._localTracks[t];const i=this._sendTransceiver[t];if(!i)return;i.direction="inactive",this._peer.removeTrack(i.sender),i.sender.replaceTrack(null);const n=this._outboundStreams[r];(e.isAudioTrack()?n.getAudioTracks():n.getVideoTracks()).forEach((e=>n.removeTrack(e)));const s=this._sendTransceiver[`${t}_tiny`];if(!s||"inactive"===s.direction)return;s.direction="inactive";const o=s.sender,a=o.track;this._peer.removeTrack(o),o.replaceTrack(null);this._outboundStreams[`${r}_tiny`].removeTrack(a),a.stop()}updateRecvTransceiverMap(e,t){const{mediaType:r}=ft(e);this._recvTransceiver[e]=t;const i=r===Fe.AUDIO_ONLY?this._recvAudio:this._recvVideo,n=i.findIndex((e=>e===t));n>=0&&i.splice(n,1)}updateSubRemoteTracks(e){const t=e.slice(),r=this._subedTracks.slice();this._subedTracks=e.slice();for(let e=t.length-1;e>=0;e-=1){const i=t[e],n=r.findIndex((e=>e===i));n>=0&&(t.splice(e,1),r.splice(n,1))}r.length&&r.forEach((e=>{const t=e.getTrackId();e.__innerSetMediaStreamTrack(void 0);const r=this._recvTransceiver[t];r&&(r.direction="inactive")}));const i={audio:0,video:0};t.length&&t.forEach((e=>{const t=e.isAudioTrack()?"audio":"video",r=this._recvTransceiver[e.getTrackId()];r?r.direction="recvonly":i[t]+=1}));for(let e=this._recvAudio.length;e<i.audio;e+=1)this._recvAudio.push(this._peer.addTransceiver("audio",{direction:"recvonly"}));for(let e=this._recvVideo.length;e<i.video;e+=1)this._recvVideo.push(this._peer.addTransceiver("video",{direction:"recvonly"}))}createOffer(e){return S(this,void 0,void 0,(function*(){const t=yield this._peer.createOffer({iceRestart:e});let r=t.sdp;for(const e in this._outboundStreams){const t=this._outboundStreams[e].id;r=r.replace(new RegExp(t,"g"),e)}return r=(e=>e.split(/\r\n(?=m=)/).map((e=>(e=>/a=(recvonly|inactive)/.test(e)?e.replace(/\r\na=(ssrc|msid)[^\r\n]+/g,""):e)(e))).join("\r\n"))(r),r=r.replace(/a=ice-options:trickle/g,"a=ice-options:trickle\r\na=ice-options:renomination"),t.sdp=r,yield this._peer.setLocalDescription(t),{type:"offer",semantics:"unified-plan",sdp:r}}))}setRemoteAnswer(e){e=e.split(/\r\n(?=m=)/).map((e=>{var t;const r=e.match(/a=mid:[^\s]+/);if(!r)return e;const i=r[0].replace("a=mid:","");let n="";for(const e in this._sendTransceiver){if(this._sendTransceiver[e].mid===i){n=e;break}}if(!n)return e;const s=null===(t=this._localTracks[n])||void 0===t?void 0:t.getBitrate();if(!s)return e;const{max:o,min:a}=s,c=o&&o>0?s.start||.7*o:0,d=[];if(o&&o>0&&d.push(`;x-google-max-bitrate=${o}`),a&&a>0&&d.push(`;x-google-min-bitrate=${a}`),c>0&&d.push(`;x-google-start-bitrate=${c}`),0===d.length)return e;const u=d.join("");return e.replace(/[\r\n]+[^\r\n]+profile-level-id[^\r\n]+/g,(e=>e+u))})).join("\r\n");const t=/[\r\n]+\r\n[\r\n]+/g;return t.test(e)&&(C.warn(`answer sdp invalid -> ${JSON.stringify(e)}`),e=e.replace(t,"\r\n")),super.setRemoteAnswer(e)}}class Wt extends t{constructor(e,t){super(),this._reTryExchange=e,this._polarisReport=t,this.pubLocalTracks={},this._reTryExchangeTimer=null,this._reportStatsTimer=null,this._reportListener=null;const r=Kt.getSdpSemantics(),i=this._rtcPeerConn=new RTCPeerConnection({sdpSemantics:r});this._sdpStrategy="plan-b"===r?new Gt(i):new Jt(i),this._rtcPeerConn.oniceconnectionstatechange=this._onICEConnectionStateChange.bind(this),this._rtcPeerConn.onconnectionstatechange=this._onConnectionStateChange.bind(this),this._rtcPeerConn.ontrack=this._onTrackReady.bind(this),this.reportParser=this._sdpStrategy.getStatParsr(this._rtcPeerConn,r)}getLocalTracks(){return Object.values(this.pubLocalTracks)}_onConnectionStateChange(){C.info(`onconnectionstatechange -> ${this._rtcPeerConn.connectionState}`)}_onICEConnectionStateChange(){var e,t;C.info(`oniceconnectionstatechange -> ${this._rtcPeerConn.iceConnectionState}`),"connected"===this._rtcPeerConn.iceConnectionState&&(this._reportStatsTimer&&clearInterval(this._reportStatsTimer),this._reportStatsTimer=setInterval(this._reportHandle.bind(this),1e3)),"failed"!==this._rtcPeerConn.iceConnectionState&&"disconnected"!==this._rtcPeerConn.iceConnectionState||(C.warn("iceconenction state is `failed`, exchange SDP to try again."),this._reTryExchange(),this._reTryExchangeTimer=setInterval(this._reTryExchange,15e3));try{null===(t=null===(e=this._reportListener)||void 0===e?void 0:e.onICEConnectionStateChange)||void 0===t||t.call(e,this._rtcPeerConn.iceConnectionState)}catch(e){C.error("onICEConnectionStateChange error",e)}}_onTrackReady(e){if(!e.streams.length)return;const t=[e.streams[0].id,"audio"===e.receiver.track.kind?Fe.AUDIO_ONLY:Fe.VIDEO_ONLY].join("_");this._updateRecvTransceiverMap(t,e.transceiver),this.emit(Wt.__INNER_EVENT_TRACK_READY__,e)}setBitrate(e,t,r){return S(this,void 0,void 0,(function*(){this._sdpStrategy.setBitrate(e,t,r)}))}createOffer(e){return S(this,void 0,void 0,(function*(){const t=yield this._sdpStrategy.createOffer(e);return C.debug(`offer -> ${JSON.stringify(t.sdp)}`),t}))}setRemoteAnswer(e){return S(this,void 0,void 0,(function*(){return C.debug(`answer -> ${JSON.stringify(e)}`),this._sdpStrategy.setRemoteAnswer(e)}))}getLocalTrack(e){return this.pubLocalTracks[e]||null}addLocalTrack(e){this.pubLocalTracks[e.getTrackId()]=e,this._sdpStrategy.addLocalTrack(e),e.off(ze.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.off(ze.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this),e.on(ze.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.on(ze.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this)}removeLocalTrackById(e){const t=this.getLocalTrack(e);t&&this.removeLocalTrack(t)}removeAllLocalTrack(){Object.keys(this.pubLocalTracks).forEach((e=>{/_tiny$/.test(e)||this.removeLocalTrackById(e)}))}removeLocalTrack(e){const t=e.getTrackId();delete this.pubLocalTracks[t],this._sdpStrategy.removeLocalTrack(e),e.__innerSetPublished(!1),e.off(ze.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.off(ze.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this);const r=`${t}_tiny`,i=this.getLocalTrack(r);i&&(this._sdpStrategy.removeLocalTrack(i),delete this.pubLocalTracks[r],i.destroy())}_updateRecvTransceiverMap(e,t){this._sdpStrategy.updateRecvTransceiverMap(e,t)}updateSubRemoteTracks(e){this._sdpStrategy.updateSubRemoteTracks(e)}getOutboundVideoInfo(){return this._sdpStrategy.getOutboundVideoInfo()}_onLocalTrackMuted(e){const t=this.getLocalTrack(`${e.getTrackId()}_tiny`);t&&(t.__innerGetMediaStreamTrack().enabled=!e.isLocalMuted()),this.emit(ze.__INNER_EVENT_MUTED_CHANGE__,e)}_onLocalTrackDestroied(e){this.emit(ze.__INNER_EVENT_DESTROY__,e)}registerReportListener(e){this._reportListener=e}_createRCRTCStateReport(e){const{timestamp:t,iceCandidatePair:r,senders:i,receivers:n}=JSON.parse(JSON.stringify(e));null==r||delete r.totalPacketsLost;for(const e in r)Pt(r[e])&&delete r[e];return{timestamp:t,iceCandidatePair:r,senders:i.map((e=>{const t={};return e.trackId&&(t.trackId=e.trackId),e.kind&&(t.kind=e.kind),(e.packetsLostRate||0===e.packetsLostRate)&&(t.packetsLostRate=e.packetsLostRate),t.remoteResource=e.remoteResource,(e.audioLevel||0===e.audioLevel)&&(t.audioLevel=e.audioLevel),e.frameWidth&&(t.frameWidth=e.frameWidth),e.frameHeight&&(t.frameHeight=e.frameHeight),e.frameRate&&(t.frameRate=e.frameRate),(e.bitrate||0===e.bitrate)&&(t.bitrate=e.bitrate),e.jitter&&(t.jitter=e.jitter),t})),receivers:n.map((e=>{const t={};return e.trackId&&(t.trackId=e.trackId),e.kind&&(t.kind=e.kind),(e.packetsLostRate||0===e.packetsLostRate)&&(t.packetsLostRate=e.packetsLostRate),t.remoteResource=e.remoteResource,(e.audioLevel||0===e.audioLevel)&&(t.audioLevel=e.audioLevel),e.frameWidth&&(t.frameWidth=e.frameWidth),e.frameHeight&&(t.frameHeight=e.frameHeight),e.frameRate&&(t.frameRate=e.frameRate),(e.bitrate||0===e.bitrate)&&(t.bitrate=e.bitrate),e.jitter&&(t.jitter=e.jitter),t}))}}_getStatsData(){var e,t;return S(this,void 0,void 0,(function*(){const r=yield this._rtcPeerConn.getStats(),i=null===(e=this.reportParser)||void 0===e?void 0:e.parseRTCStatsReport(r);return null===(t=this.reportParser)||void 0===t?void 0:t.formatRCRTCStateReport(i)}))}getAudioLevelReportData(){var e,t;return S(this,void 0,void 0,(function*(){const r=yield this._rtcPeerConn.getStats(),i=null===(e=this.reportParser)||void 0===e?void 0:e.parseRTCStatsReport(r);if(!i)return[];return null===(t=this.reportParser)||void 0===t?void 0:t.getAudioLevelList(i)}))}_reportHandle(){var e,t,r;return S(this,void 0,void 0,(function*(){const i=yield this._getStatsData();if(!i)return;(i.senders.length||i.receivers.length)&&(null===(e=this._polarisReport)||void 0===e||e.sendR3R4Data(i));const n=this._createRCRTCStateReport(i);null===(r=null===(t=this._reportListener)||void 0===t?void 0:t.onStateReport)||void 0===r||r.call(t,n)}))}getRTCPeerConn(){return this._rtcPeerConn}destroy(){this.clear(),this.clearReTryExchangeTimer(),this._reportStatsTimer&&(clearInterval(this._reportStatsTimer),this._reportStatsTimer=null),this.registerReportListener(null),this._rtcPeerConn.close(),this.reportParser=null}clearReTryExchangeTimer(){clearInterval(this._reTryExchangeTimer),this._reTryExchangeTimer=null}}var Yt,qt,zt,Qt,Xt;Wt.__INNER_EVENT_TRACK_READY__="inner-track-ready",function(e){e[e.DISABLE=0]="DISABLE",e[e.ENABLE=1]="ENABLE"}(Yt||(Yt={})),function(e){e[e.MeetingOrAnchor=1]="MeetingOrAnchor",e[e.Audience=2]="Audience"}(qt||(qt={}));class Zt{constructor(e,t,r,i,n=qt.MeetingOrAnchor){this._context=e,this._runtime=t,this._roomId=r,this._crtRTCRoom=i,this._userRole=n}_send(e){this._context.getConnectionStatus()===n.CONNECTED&&this._context.setRTCState(this._roomId,e)}_getClientID(){const e="uuid";let t=this._runtime.localStorage.getItem(e);return t||(t=St(),this._runtime.localStorage.setItem(e,t)),t}_getRealResourceId(e){let t=e;const r=e.indexOf("_tiny");return r>-1&&(t=e.slice(0,r)),t}_getPolarisTrackId(e){let t="";const r=e.split("_");if(e.includes("_tiny")){const e=r.pop(),i=parseInt(r.pop())===Fe.AUDIO_ONLY?"audio":"video",n=r.pop();t=[r.join("_"),n,e,i].join("_")}else{const e=parseInt(r.pop())===Fe.AUDIO_ONLY?"audio":"video",i=r.pop();t=[r.join("_"),i,e].join("_")}return t}sendR3R4Data(e){const{iceCandidatePair:t,senders:r,receivers:i}=e,n=(null==t?void 0:t.bitrateSend)||-1,s=(null==t?void 0:t.bitrateRecv)||-1,o=(null==t?void 0:t.networkType)||"unknown",a=(null==t?void 0:t.rtt)||-1,c=`${(null==t?void 0:t.IP)||-1}:${null==t?void 0:t.port}`,d=(null==t||t.remoteIP,null==t||t.remotePort,(null==t?void 0:t.availableIncomingBitrate)||-1),u=(null==t?void 0:t.availableOutgoingBitrate)||-1,l=(null==t?void 0:t.totalPacketsLost)||-1,h=this._context.getCurrentId();let p=`R3\t${n}\t-1\t-1\t-1\t${o}\t${a}\t${c}\t${d}\t${u}\t${l}\t${h}\r`,_=`R4\t${s}\t-1\t-1\t-1\t${o}\t${a}\t${c}\t${d}\t${u}\t${l}\t${h}\r`;const m=r.map((e=>{var t;const{trackId:r,audioLevel:i,samplingRate:n,bitrate:s,packetsLostRate:o,frameRate:a,frameWidth:c,frameHeight:d,googRenderDelayMs:u,jitter:l,nackCount:h,pliCount:p,rtt:_,googFirsSent:m,encoderImplementation:f}=e,v=this._getPolarisTrackId(r),R=this._getRealResourceId(r);return{trackId:v,googCodecName:f||String(-1),audioLevel:i||0===i?i:-1,bitrate:s||0===s?s:-1,packetsLostRate:o||0===o?o:-1,frameRate:a||-1,resolution:c&&d?`${c} * ${d}`:"-1",jitter:l||-1,nackCount:h||0===h?h:-1,pliCount:p||0===p?p:-1,rtt:_||-1,googFirsSent:m,samplingRate:n,googRenderDelayMs:u,encoderImplementation:f||String(-1),trackState:(null===(t=this._crtRTCRoom.getLocalTrack(R))||void 0===t?void 0:t.isLocalMuted())?Yt.DISABLE:Yt.ENABLE}})),f=i.filter((e=>!!e.trackId)).map((e=>{var t;const{trackId:r,audioLevel:i,samplingRate:n,bitrate:s,packetsLostRate:o,frameRate:a,frameWidth:c,frameHeight:d,googRenderDelayMs:u,jitter:l,nackCount:h,pliCount:p,rtt:_,googFirsReceived:m,codecImplementationName:f}=e,v=this._getPolarisTrackId(r),R=this._getRealResourceId(r);return{trackId:v,googCodecName:f||String(-1),audioLevel:i||0===i?i:-1,bitrate:s||0===s?s:-1,packetsLostRate:o||0===o?o:-1,frameRate:a||-1,resolution:c&&d?`${c} * ${d}`:"-1",jitter:l||-1,nackCount:h||0===h?h:-1,pliCount:p||0===p?p:-1,rtt:_||-1,googFirsReceived:m,samplingRate:n,googRenderDelayMs:u,codecImplementationName:f||String(-1),trackState:(null===(t=this._crtRTCRoom.getRemoteTrack(R))||void 0===t?void 0:t.isLocalMuted())?Yt.DISABLE:Yt.ENABLE}}));p+=m.map((e=>`${e.trackId}\t${e.googCodecName}\t${e.audioLevel}\t${e.samplingRate}\t${e.bitrate}\t${e.packetsLostRate}\t${e.frameRate}\t${e.resolution}\t${e.googRenderDelayMs}\t${e.jitter}\t${e.nackCount}\t${e.pliCount}\t${e.rtt}\t${e.googFirsSent}\t${e.encoderImplementation}\t${e.trackState}`)).join("\n"),e.senders.length&&this._send(p+`\r${this._userRole}`),_+=f.map((e=>`${e.trackId}\t${e.googCodecName}\t${e.audioLevel}\t${e.samplingRate}\t${e.bitrate}\t${e.packetsLostRate}\t${e.frameRate}\t${e.resolution}\t${e.googRenderDelayMs}\t${e.jitter}\t${e.nackCount}\t${e.pliCount}\t${e.rtt}\t${e.googFirsReceived}\t${e.codecImplementationName}\t${e.trackState}`)).join("\n"),e.receivers.length&&this._send(_+`\r${this._userRole}`)}sendR1(){const e=`R1\t5.3.1\t${this._context.getCoreVersion()}\tweb\t${navigator.platform}\t-1\t${yt.browser}\t${yt.version}\t${this._getClientID()}\t${this._userRole}`;this._send(e)}sendR2(e,t,r){const i=`R2\t${e}\t${t}\t${this._getClientID()}\r${r.join("\t")}\r${this._userRole}`;this._send(i)}}!function(e){e.PUBLISH="publish",e.SUBSCRIBE="subscribe"}(zt||(zt={})),function(e){e.BEGIN="begin",e.END="end"}(Qt||(Qt={}));class er{constructor(e){this._room=e,this._audioLevelChangeHandler=null,this._timer=null,this._pc=this._room.__getPC()}_audioLevelReport(){return S(this,void 0,void 0,(function*(){if("new"===this._pc.getRTCPeerConn().iceConnectionState||!this._audioLevelChangeHandler)return;const e=(yield this._pc.getAudioLevelReportData()).map((e=>{const{userId:t}=Pr.parseTrackId(e.trackId);return{track:this._room.getCrtUserId()===t?this._room.getLocalTrack(e.trackId):this._room.getRemoteTrack(e.trackId),audioLevel:e.audioLevel||0}})).filter((e=>e.track));this._audioLevelChangeHandler(e)}))}onAudioLevelChange(e,t){t<300||t>1e3?C.error('the valid range of onAudioLevelChange params "gap" is: > 300 && < 1000'):e?(this._audioLevelChangeHandler=e,this._timer=setInterval(this._audioLevelReport.bind(this),t)):this._audioLevelChangeHandler=null}clearAudioLevelReportTimer(){this._timer&&(clearInterval(this._timer),this._timer=null)}}!function(e){e[e.ANCHOR=1]="ANCHOR",e[e.AUDIENCE=2]="AUDIENCE"}(Xt||(Xt={}));const tr=e=>e instanceof qe?e.getTrackId():e.track.getTrackId();class rr{constructor(e,t,r,i,n,s,o,a,c,d){this._context=e,this._runtime=t,this._roomId=r,this._roomMode=n,this._service=s,this._initOptions=o,this._ntfClearRoomItem=a,this._isMainRoom=d,this._remoteTracks={},this._subscribedList=[],this._destroyed=!1,this.msgTaskQueue=new E,this._appListener=null,this._onRecvPKMsg=null,this._token=i.token,this._sessionId=i.sessionId,this._roomResources=c?{}:Lt(i),this._initRemoteTracks();const u=this._context.getCurrentId(),l=this._roomResources[u]=this._roomResources[u]||[];C.debug(`room data -> ${JSON.stringify(this._roomResources)}`),l.length>0&&k((()=>this._unpublishPrev(l))),c&&this._afterChangedRole(i),this._pinger=new At(r,this._roomMode,e,this._initOptions.pingGap),this._pinger.onFailed=this._kickoff.bind(this),this._pinger.onPingResult=this._handlePingResult.bind(this),this._pinger.start(),this._polarisReport=new Zt(this._context,this._runtime,this._roomId,this),this._polarisReport.sendR1(),this._pc=new Wt(this._reTryExchange.bind(this),this._polarisReport),this._pc.on(Wt.__INNER_EVENT_TRACK_READY__,this._onTrackReady,this),this._pc.on(ze.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),this._pc.on(ze.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this)}_initRemoteTracks(){const e=this._context.getCurrentId();for(const t in this._roomResources){const r=this._roomResources[t];t!==e&&0!==r.length&&r.forEach((e=>{const t=mt(e),{tag:r,userId:i,mediaType:n}=ft(t),s=n===Fe.AUDIO_ONLY?new ot(r,i):new at(r,i);s.__innerSetRemoteMuted(0===e.state),this._remoteTracks[t]=s}))}}_handlePingResult(e){this._callAppListener("onPing",e)}setBitrate(e,t,i){C.warn("`RCAbstractRoom.setBitrate` will be deprecated, use `RCLocalTrack.setBitrate` instead."),s("max",e,(e=>r(e)&&e>Math.max(t||1,200)),!0),s("min",t,(t=>r(t)&&t>=1&&(!r(e)||t<e)),!0),s("start",i,(i=>r(i)&&i>t&&i<=e)),this._pc.setBitrate(e,t,i)}_onTrackReady(e){const t=e.streams[0].id,r=e.receiver.track,i=[t,"audio"===r.kind?Fe.AUDIO_ONLY:Fe.VIDEO_ONLY].join("_"),n=this._remoteTracks[i];n?(n.__innerSetMediaStreamTrack(r),this._callAppListener("onTrackReady",n)):C.warn(`cannot found remote track ${r.id}`)}_callAppListener(e,...t){var r;const i=null===(r=this._appListener)||void 0===r?void 0:r[e];if(i)try{i(...t)}catch(e){C.error(e)}}_onUserUnpublish(e){return S(this,void 0,void 0,(function*(){yield this.unsubscribe(e),e.forEach((e=>{e.__innerDestroy(),delete this._remoteTracks[e.getTrackId()]})),this._onTrackUnpublish(e)}))}_onTrackUnpublish(e){this._callAppListener("onTrackUnpublish",e)}_unpublishPrev(e){return S(this,void 0,void 0,(function*(){const t=e.slice();e.length=0,C.info(`unpublish uris prev login: ${JSON.stringify(t)}`);const r=yield this._context.setRTCTotalRes(this._roomId,ct(Nt.UNPUBLISH,t),dt([]),Nt.TOTAL_CONTENT_RESOURCE,dt([]));r!==i.SUCCESS?C.error(`unpublish prev uris failed -> code: ${r}`):C.debug("unpublish uris prev login succeed")}))}__parseInnerMessage(e){const{targetId:t,conversationType:r}=e;if(r!==o.RTC_ROOM)return!1;if(t!==this._roomId)return!0;C.info(`recv inner msg -> message: ${JSON.stringify(e)} | roomid: ${this._roomId}`);const i=e.content;switch(e.messageType){case Nt.KICK:this._kickoff(!0,i);break;case Nt.STATE:this.msgTaskQueue.push((()=>this._stateHandle(i)));break;case Nt.MODIFY:case Nt.PUBLISH:case Nt.UNPUBLISH:case Nt.TOTAL_CONTENT_RESOURCE:this.msgTaskQueue.push((()=>this._resourceHandle(i,e.messageType,e.senderUserId)));break;case Nt.ROOM_NOTIFY:this._callAppListener("onRoomAttributeChange",e.messageType,e.content);break;case Nt.USER_NOTIFY:C.warn(`TODO: ${Nt.USER_NOTIFY}`);break;case Nt.PK_INVITE:case Nt.PK_CANCEL_INVITE:case Nt.PK_INVITE_TIMEOUT:case Nt.PK_INVITE_ANSWER:case Nt.PK_END:this._onRecvPKMsg&&this._onRecvPKMsg(e);break;case Nt.OTHER_ROOM_OFFLINE:break;default:this._callAppListener("onMessageReceive",e.messageType,e.content,e.senderUserId,e.messageUId)}return!0}_kickoff(e,t){let r;C.warn(`onKickOff -> byServer: ${e}`),this._ntfClearRoomItem(),this._leaveHandle(!e),e&&((null==t?void 0:t.users)||[]).forEach((e=>{e.userId===this._context.getCurrentId()&&(r=e.type)})),this._callAppListener("onKickOff",e,r)}_rtcpeerClosed(){this._ntfClearRoomItem(),this._leaveHandle(!0),this._callAppListener("onRTCPeerConnectionCloseByException")}_resourceHandle(e,t,r){return S(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return void C.warn(`room has been destroyed. -> roomId: ${this._roomId}`);const{uris:i,ignore:n}=e;if(n||!i)return;const s=[],o=[],a=[];let c;const d=this._roomResources[r]||(this._roomResources[r]=[]);switch(t){case Nt.MODIFY:a.push(...i);break;case Nt.PUBLISH:s.push(...i);break;case Nt.UNPUBLISH:o.push(...i);break;case Nt.TOTAL_CONTENT_RESOURCE:c=gt(d,i),s.push(...c.publishedList),o.push(...c.unpublishedList),a.push(...c.modifiedList)}if(s.length>0){const e=d.map(mt),t=[],r=[];if(s.forEach((i=>{const n=mt(i),s=e.indexOf(n),{userId:o,tag:a,mediaType:c}=ft(n);s>-1?d[s]=i:d.push(i);let u=this._remoteTracks[n];u?u.isSubscribed()&&t.push(u):(u=c===Fe.AUDIO_ONLY?new ot(a,o):new at(a,o),this._remoteTracks[n]=u,r.push(u)),u.__innerSetRemoteMuted(0===i.state)})),t.length){const e=t.map((e=>e.getTrackId()));C.debug(`resub tracks -> ${JSON.stringify(e)}`);const{code:r}=yield k((()=>this.__subscribe(t,!0)));r!==T.SUCCESS&&C.error(`resub tracks failed -> code: ${r}, ids: ${JSON.stringify(e)}`)}this._onTrackPublish(r)}if(o.length>0){const e=o.map(mt);for(let t=d.length-1;t>=0;t-=1){const r=d[t];e.includes(mt(r))&&d.splice(t,1)}const t=o.map((e=>{const t=mt(e);return this._remoteTracks[t]}));yield this._onUserUnpublish(t)}if(a.length>0){const e=d.map(mt);for(let t=0;t<a.length;t+=1){const r=a[t],i=mt(r),n=e.indexOf(i);d[n].state=r.state;const s=this._remoteTracks[i];s.__innerSetRemoteMuted(0===r.state),s.isAudioTrack()?this._onAudioMuteChange(s):this._onVideoMuteChange(s)}}}))}_onTrackPublish(e){this._callAppListener("onTrackPublish",e)}_stateHandle(e){var t;return S(this,void 0,void 0,(function*(){const{users:r}=e;if(0===r.length)return;const i=[],n=[],s=[],o=[];r.forEach((e=>{0==+e.state?(C.debug(`user joined -> ${e.userId}`),this._roomResources[e.userId]||(e.switchRoleType?s.push(e.userId):i.push(e.userId)),this._roomResources[e.userId]=this._roomResources[e.userId]||[]):(C.debug(`user left -> ${e.userId}`),e.switchRoleType?o.push(e.userId):n.push(e.userId))}));const a=[...i,...s],c=[...n,...o];if(c.length){const e=[],t=[];c.forEach((r=>{e.push(...this.getRemoteTracksByUserId(r)),t.push(r)})),e.length&&(yield this.unsubscribe(e),e.forEach((e=>delete this._remoteTracks[e.getTrackId()]))),t.length&&t.forEach((e=>delete this._roomResources[e]))}if(null===(t=this._appListener)||void 0===t?void 0:t.onSwitchRole)return s.length&&s.forEach((e=>this._callAppListener("onSwitchRole",e,Xt.ANCHOR))),o.length&&o.forEach((e=>this._callAppListener("onSwitchRole",e,Xt.AUDIENCE))),i.length&&this._callAppListener("onUserJoin",i),void(n.length&&this._callAppListener("onUserLeave",n));a.length&&this._callAppListener("onUserJoin",a),c.length&&this._callAppListener("onUserLeave",c)}))}getRoomId(){return this._roomId}getCrtUserId(){return this._context.getCurrentId()}__getPC(){return this._pc}getRemoteUserIds(){const e=this._context.getCurrentId();return Object.keys(this._roomResources).filter((t=>t!==e))}getRemoteTracks(){const e=[];return this.getRemoteUserIds().forEach((t=>{e.push(...this.getRemoteTracksByUserId(t))})),e}getRemoteTracksByUserId(e){const t=[];for(const r in this._remoteTracks){const i=this._remoteTracks[r];i.getUserId()===e&&t.push(i)}return t}getSessionId(){return this._sessionId}sendMessage(e,t){return S(this,void 0,void 0,(function*(){const{code:r}=yield this._context.sendMessage(o.RTC_ROOM,this._roomId,{messageType:e,content:t,isStatusMessage:!0});return r!==i.SUCCESS?(C.error(`send message failed -> code: ${r}`),{code:T.SIGNAL_ERROR}):{code:T.SUCCESS}}))}setRoomAttribute(e,t,r,n=!1){return S(this,void 0,void 0,(function*(){const s=yield this._context.setRTCData(this._roomId,e,t,n,a.ROOM,r);return s!==i.SUCCESS?(C.error(`SetRoomAttributeValue Failed: ${s}`),{code:T.SIGNAL_ERROR}):{code:T.SUCCESS}}))}deleteRoomAttributes(e,t,r=!1){return S(this,void 0,void 0,(function*(){const n=yield this._context.removeRTCData(this._roomId,e,r,a.ROOM,t);return n!==i.SUCCESS?(C.error(`DeleteRoomAttribute Failed: ${n}`),{code:T.SIGNAL_ERROR}):{code:T.SUCCESS}}))}getRoomAttributes(e=[],t=!1){return S(this,void 0,void 0,(function*(){const{code:r,data:n}=yield this._context.getRTCData(this._roomId,e,t,a.ROOM);return r!==i.SUCCESS?(C.error(`GetRoomAttributes Failed: ${r}`),{code:T.SIGNAL_ERROR}):{code:T.SUCCESS,data:n}}))}_setUserAttributeValue(e,t,r){return this._context.setRTCData(this._roomId,e,t,!1,a.PERSON,r)}_deleteUserAttributes(e,t){return this._context.removeRTCData(this._roomId,e,!1,a.PERSON,t)}_getUserAttributes(e){return this._context.getRTCData(this._roomId,e,!1,a.PERSON)}isDestroyed(){return this._destroyed}__destroy(e){return this._leaveHandle(e)}_leaveHandle(e){var t;return S(this,void 0,void 0,(function*(){this._destroyed||(this._destroyed=!0,null===(t=this._audioLevelReport)||void 0===t||t.clearAudioLevelReportTimer(),e&&(yield this._context.quitRTCRoom(this._roomId)),this._isMainRoom&&this._quitAllPKRoom(),this._pc.removeAllLocalTrack(),this._pinger.stop(),this._isMainRoom&&(yield this._service.exit(this._getRTCReqestHeaders())),this._pc.destroy(),this._polarisReport=null,this._removeRemoteTracks())}))}_onLocalTrackDestroied(e){e instanceof Xe&&e.__isTiny()||this.unpublish([e])}_onLocalTrackMuted(e){return S(this,void 0,void 0,(function*(){const t=e.getTrackId(),r=this._context.getCurrentId(),n=[{resourceId:t,enabled:!e.isLocalMuted()}],s=this._roomResources[r]||[],o=[];for(let e=0;e<s.length;e+=1){const t=s[e],r=mt(t),i=n.findIndex((e=>e.resourceId===r));if(i>=0){const{enabled:e}=n[i];t.state=e?1:0,o.push(t);break}}const a=yield k((()=>this._context.setRTCTotalRes(this._roomId,ct(Nt.MODIFY,o),dt(s),Nt.TOTAL_CONTENT_RESOURCE)));a!==i.SUCCESS&&C.error("notice `track.enabled` change failed -> code: "+a)}))}_removePubFailedTracks(e){e.forEach((e=>{const t=e instanceof ze?e:e.track;C.debug(`remove pub failed track from peerconnection -> trackId: ${t.getTrackId()}`),this._pc.removeLocalTrackById(t.getTrackId())}))}publish(e){return S(this,void 0,void 0,(function*(){return k((()=>this.__publish(e)))}))}__publish(e){return S(this,void 0,void 0,(function*(){if(!this._isMainRoom&&this instanceof _r)return C.error("the `publish` is disabled in PK room "),{code:T.THE_FUNCTION_IS_DISABLED_IN_PKROOM};if(this._assertRoomDestroyed())return C.error(`publish failed, room has been destroyed. -> roomId: ${this._roomId}`),{code:T.ROOM_HAS_BEEN_DESTROYED};if(!c("tracks",e,(()=>d(e)&&e.length>0&&e.every((e=>e instanceof ze||e.track instanceof ze))),!0))return C.error(`publish failed, tracks is invalid -> roomId: ${this._roomId}`),{code:T.PARAMS_ERROR};const t=this._context.getCurrentId();if(this._pc.getLocalTracks().length+(e=>{let t=0;return e.forEach((e=>{e instanceof ze?t++:e.pubTiny&&e.track.isVideoTrack()?t+=2:t++})),t})(e)>10)return C.error(`publish failed, tracks limit exceeded -> roomId: ${this._roomId}`),{code:T.PUBLISH_TRACK_LIMIT_EXCEEDED};C.debug(`publish tracks -> roomId: ${this._roomId}, tracks: ${e.map(tr)}`),e.forEach((e=>{const{track:t,pubTiny:r}=e instanceof ze?{pubTiny:!1,track:e}:e;if(this._pc.addLocalTrack(t),t.isVideoTrack()&&r){let e;try{e=t.__innerGetMediaStreamTrack().clone();const i=r.frameRate||Be.FPS_15,n=r.resolution||He.W176_H144,{width:s,height:o}=Ct(n),a=Et(i);e.applyConstraints({width:s,height:o,frameRate:a})}catch(r){return null==e||e.stop(),void C.warn(`pubTiny failed -> id: ${t.getTrackId()}, msg: ${r.message}`)}this._pc.addLocalTrack(new Xe(t.getTag(),t.getUserId(),e,!0))}})),this._pc.clearReTryExchangeTimer();const r=yield this._createExchangeParams(this._subscribedList,!1),n=this._getPushOtherRoomsParams();n&&(r.pushOtherRooms=n);const s=yield this._exchangeHandle(r);if(s.code!==T.SUCCESS)return C.error(`publish failed -> roomId: ${this._roomId}, code: ${s.code}`),this._removePubFailedTracks(e),{code:s.code};const{publishList:o,sdp:a,resultCode:l,message:h,urls:p,mcuPublishList:_}=s.data;if(l!==T.SUCCESS)return C.error(`publish failed -> roomId: ${this._roomId}, code: ${l}, msg: ${h}`),this._removePubFailedTracks(e),{code:l};const m=yield this._pc.setRemoteAnswer(a.sdp);if(m!==T.SUCCESS)return{code:m};const f=this._roomResources[t],v=o.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:this._getResourceState(mt(e))},e))),{publishedList:R}=gt(f,v),g=(null==_?void 0:_.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:1},e))))||[],S=yield this._context.setRTCTotalRes(this._roomId,ct(Nt.PUBLISH,R),dt(v),Nt.TOTAL_CONTENT_RESOURCE,dt(g));if(S!==i.SUCCESS)return C.error(`send publish streams notification failed: ${S}`),{code:T.SIGNAL_ERROR};this._roomResources[t]=v;const I=R.map((e=>mt(e)));return this._polarisReport&&this._polarisReport.sendR2(zt.PUBLISH,Qt.BEGIN,I),e.forEach((e=>{const{track:t}=e instanceof ze?{track:e}:e;t.__innerSetPublished(!0)})),C.debug(`publish success: ${I.join(",")}`),this._roomMode===u.LIVE?{code:T.SUCCESS,liveUrl:null==p?void 0:p.liveUrl}:{code:T.SUCCESS}}))}_getPushOtherRoomsParams(){if(this instanceof _r){const{code:e,roomPKHandler:t}=this.getRoomPKHandler(),r=[];if(e===T.SUCCESS&&t){const e=t.getJoinedPKRooms();for(const i in e){const n=e[i].getSessionId(),s=t.getPKInfo(i);if(!s)return;const{inviterUserAutoMix:o,inviteeUserAutoMix:a,inviterUserId:c}=s,d=this._context.getCurrentId()===c;r.push({roomId:i,sessionId:n,autoMix:d?!!o:!!a})}}return r}}_reTryExchange(){return S(this,void 0,void 0,(function*(){k((()=>S(this,void 0,void 0,(function*(){const e=yield this._createExchangeParams(this._subscribedList,!0),t=this._getPushOtherRoomsParams();t&&(e.pushOtherRooms=t);const r=yield this._exchangeHandle(e);if(r.code!==T.SUCCESS)return C.error(`reTryExchange failed: ${r.code}`),{code:r.code};const{sdp:i,resultCode:n}=r.data;if(n!==T.SUCCESS)return C.error(`reTryExchange failed: ${n}`),{code:n};this._pc.clearReTryExchangeTimer();const s=yield this._pc.setRemoteAnswer(i.sdp);return s!==T.SUCCESS?{code:s}:void 0}))))}))}_exchangeHandle(e){return this._service.exchange(this._getRTCReqestHeaders(),e)}_getRTCReqestHeaders(){return{"App-Key":this._context.getAppkey(),RoomId:this._roomId,Token:this._token,RoomType:this._roomMode,UserId:this._context.getCurrentId()}}_createExchangeParams(e,t){return S(this,void 0,void 0,(function*(){return{sdp:yield this._pc.createOffer(t),extend:JSON.stringify({resolutionInfo:this._pc.getOutboundVideoInfo()}),subscribeList:e.filter((e=>{const t=e.track.getTrackId(),{userId:r}=ft(t);if(!this._roomResources[r])return!1;const i=this._roomResources[r].filter((e=>t===`${e.msid}_${e.mediaType}`)).length;return i})).map((e=>({simulcast:e.subTiny?Mt.TINY:Mt.NORMAL,resolution:"",uri:this._getResourceById(e.track.getTrackId()).uri}))),switchstream:!1}}))}_getResourceState(e){var t;return(null===(t=this.getLocalTrack(e))||void 0===t?void 0:t.isLocalMuted())?0:1}unpublish(e){return S(this,void 0,void 0,(function*(){return k((()=>this.__unpublish(e)))}))}__unpublish(e){var t;return S(this,void 0,void 0,(function*(){if(!this._isMainRoom&&this instanceof _r)return C.error("the `unpublish` is disabled in PK room "),{code:T.THE_FUNCTION_IS_DISABLED_IN_PKROOM};if(this._assertRoomDestroyed())return C.warn(`room has been destroyed, no need to unpublish tracks -> roomId: ${this._roomId}`),{code:T.SUCCESS};const r=this._context.getCurrentId();if(!c("tracks",e,(()=>e.every((e=>e.getUserId()===r&&e instanceof ze))),!0))return C.warn(`unpublish failed, tracks is invalid -> roomId: ${this._roomId}, tracks: ${e.map(tr)}`),{code:T.PARAMS_ERROR};const n=e.map((e=>e.getTrackId())),s=n.map(this._getResourceById.bind(this)).filter((e=>!!e));if(0===s.length)return{code:T.SUCCESS};const o=this._roomResources[r].filter((e=>!s.includes(e)));n.forEach((e=>this._pc.removeLocalTrackById(e))),null===(t=this._polarisReport)||void 0===t||t.sendR2(zt.PUBLISH,Qt.END,n),this._pc.clearReTryExchangeTimer();const a=yield this._createExchangeParams(this._subscribedList,!1),d=this._getPushOtherRoomsParams();d&&(a.pushOtherRooms=d);const u=yield this._exchangeHandle(a);if(u.code!==T.SUCCESS)return C.error(`exchange failed -> code: ${u.code}`),{code:u.code};const{publishList:l,sdp:h,resultCode:p,message:_,mcuPublishList:m}=u.data;p!==T.SUCCESS&&C.error(`unpublish streams failed -> code: ${p}, msg: ${_}`);const f=m?m.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:1},e))):[],v=yield this._context.setRTCTotalRes(this._roomId,ct(Nt.UNPUBLISH,s),dt(o),Nt.TOTAL_CONTENT_RESOURCE,dt(f));if(v!==i.SUCCESS)return C.error("send unpublish notification failed:",v),{code:T.SIGNAL_ERROR};C.debug(`unpublish success -> tracks: ${n.join(",")}`);const R=yield this._pc.setRemoteAnswer(h.sdp);if(R!==T.SUCCESS)return{code:R};const g=l.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:this._getResourceState(mt(e))},e)));return this._roomResources[r]=g,{code:T.SUCCESS}}))}_getResourceById(e){const{userId:t}=ft(e);return this._roomResources[t].find((t=>mt(t)===e))}_isValidResourceId(e){var t;const{userId:r}=ft(e);return!!(null===(t=this._roomResources[r])||void 0===t?void 0:t.find((t=>mt(t)===e)))}subscribe(e){return S(this,void 0,void 0,(function*(){return k((()=>this.__subscribe(e,!1)))}))}__subscribe(e,t=!1){var r;return S(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return C.error(`subscribe failed, room has been destroyed -> roomId: ${this._roomId}`),{code:T.ROOM_HAS_BEEN_DESTROYED};if(!c("tracks",e,(()=>d(e)&&e.length>0&&e.every((e=>e instanceof st||e.track instanceof st))),!0))return C.error(`subscribe failed, tracks is invalid -> roomId: ${this._roomId}`),{code:T.PARAMS_ERROR};C.info(`subscribe -> roomId: ${this._roomId}, tracks: ${e.map(tr)}`);const i=this._subscribedList.map((e=>Object.assign({},e))),n=e.map((e=>e instanceof st?{track:e}:e));let s=!1;const o=[];return n.forEach((e=>{const t=e.track.getTrackId();o.push(t);const r=i.find((e=>e.track.getTrackId()===t));r&&r.subTiny===e.subTiny||(r?r.subTiny=e.subTiny:i.push(e),s=!0)})),s||t?(null===(r=this._polarisReport)||void 0===r||r.sendR2(zt.SUBSCRIBE,Qt.BEGIN,o),this._updateSubListHandle(i,!0)):{code:T.SUCCESS}}))}unsubscribe(e){return S(this,void 0,void 0,(function*(){return k((()=>this.__unsubscribe(e)))}))}__unsubscribe(e){var t;return S(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return C.warn(`room has beed destroyed, no need to unsubscribe tracks -> roomId: ${this._roomId}`),{code:T.SUCCESS};if(!c("tracks",e,(()=>d(e)&&e.length>0&&e.every((e=>e instanceof st))),!0))return C.error(`unsubscribe failed, tracks is invalid -> roomId: ${this._roomId}`),{code:T.PARAMS_ERROR};C.info(`unsubscribe -> roomId: ${this._roomId}, tracks: ${e.map(tr)}`);const r=this._subscribedList.map((e=>Object.assign({},e))).filter((t=>!e.includes(t.track)));return null===(t=this._polarisReport)||void 0===t||t.sendR2(zt.SUBSCRIBE,Qt.END,e.map((e=>e.getTrackId()))),this._updateSubListHandle(r,!1)}))}_assertRoomDestroyed(){if(this._destroyed){const e="This room has been destroyed. Please use `RCRTCClient.joinRTCRoom` or `RCRTCClient.joinLivingRoom` to catch another instance.";return C.warn(e),T.ROOM_HAS_BEEN_DESTROYED}}getLocalTrack(e){return this._pc.getLocalTrack(e)}getLocalTracks(){return this._pc.getLocalTracks()}getRemoteTrack(e){return this._remoteTracks[e]||null}updateSubList(e){return S(this,void 0,void 0,(function*(){return k((()=>this._updateSubListHandle(e,!1)))}))}_updateSubListHandle(e,t=!1){return S(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return{code:T.ROOM_HAS_BEEN_DESTROYED};if(!c("resources",e,(()=>d(e)&&e.every((e=>e instanceof st||e.track instanceof st))),!0))return C.error(`update sublist failed, tracks is invalid -> roomId: ${this._roomId}`),{code:T.PARAMS_ERROR};C.info(`update subscribe list -> roomId: ${this._roomId}, forceReq: ${t}, tracks: ${e.map(tr)}`);let r=e.map((e=>e instanceof st?{track:e}:Object.assign({},e)));const i={};r=r.filter((e=>{const t=e.track.getTrackId();return this._remoteTracks[t]?!i[t]&&(i[t]=!0):(C.warn(`track cannot found in room -> trackId: ${t}`),!1)})).map((e=>Object.assign({},e)));const n=this._subscribedList.map((e=>Object.assign({},e)));if(!t){let e=!1;if(r.forEach((t=>{const r=n.findIndex((e=>e.track===t.track));if(-1===r)return void(e=!0);n.splice(r,1)[0].subTiny!==t.subTiny&&(e=!0)})),n.length&&(e=!0),!e)return{code:T.SUCCESS}}this._pc.clearReTryExchangeTimer(),this._pc.updateSubRemoteTracks(r.map((e=>e.track)));const s=yield this._createExchangeParams(r,!1),o=this._getPushOtherRoomsParams();o&&(s.pushOtherRooms=o);const a=yield this._exchangeHandle(s),u=r.map((e=>e.track.getTrackId()));if(a.code!==T.SUCCESS)return{code:a.code};const{sdp:l,resultCode:h,message:p,subscribedList:_}=a.data;if(h!==T.SUCCESS)return C.error(`change subscribe list failed: ${h}`),{code:h};C.debug(`subscribe success: ${u.join(",")}`);const m=yield this._pc.setRemoteAnswer(l.sdp);if(m!==T.SUCCESS)return{code:m};const f=null==_?void 0:_.map((e=>`${e.msid}_${e.mediaType}`)),v=r.filter((e=>null==f?void 0:f.includes(e.track.getTrackId()))),R=r.filter((e=>!(null==f?void 0:f.includes(e.track.getTrackId()))));for(const e in this._remoteTracks){const t=v.some((t=>t.track.getTrackId()===e));this._remoteTracks[e].__innerSetSubscribed(t)}return this._subscribedList.splice(0,this._subscribedList.length,...v),R.length?{code:T.SUCCESS,failedList:R}:{code:T.SUCCESS}}))}registerRoomEventListener(e){this._appListener=e}registerReportListener(e){this._pc.registerReportListener(e)}onAudioLevelChange(e,t){var r;null===(r=this._audioLevelReport)||void 0===r||r.clearAudioLevelReportTimer(),this._audioLevelReport=new er(this),this._audioLevelReport.onAudioLevelChange(e,t||1e3)}__onReconnected(e){return S(this,void 0,void 0,(function*(){if("closed"===this._pc.getRTCPeerConn().connectionState)return C.warn("RTCPeerConnection closed. Please rejoin room to restore services."),void this._rtcpeerClosed();const{code:t,data:r}=yield this._context.joinRTCRoom(this._roomId,this._roomMode,e);if(t!==i.SUCCESS)return void C.error(`RTC __onReconnected getRTCRoomInfo failed: ${t}`);C.debug(`RTC __onReconnected getRTCRoomInfo success: ${JSON.stringify(r)}`);const n=[],s={},o={},a={},c=Lt(r),d=Object.keys(c),u=Object.keys(this._roomResources);for(let e=d.length-1;e>=0;e-=1){const t=d[e],r=u.indexOf(t);if(-1===r){n.push(t),s[t]=Rt(c[t]);continue}const i=this._roomResources[t],l=c[t],{publishedList:h,modifiedList:p,unpublishedList:_}=gt(i,l,!0);s[t]=Rt(h),o[t]=Rt(_),a[t]=Rt(p),u.splice(r,1)}u.length&&u.forEach((e=>{delete this._roomResources[e]})),Object.assign(this._roomResources,c),u.length&&this._callAppListener("onUserLeave",u),n.length&&this._callAppListener("onUserJoin",n);for(const e in o){const t=o[e];if(t.length){const e=t.map((e=>this._remoteTracks[mt(e)]));yield this._onUserUnpublish(e)}}return Object.keys(s).forEach((e=>{const t=s[e];if(0===t.length)return;const r=t.map((e=>{const t=mt(e),{userId:r,tag:i,mediaType:n}=ft(t),s=this._remoteTracks[t]=n===Fe.AUDIO_ONLY?new ot(i,r):new at(i,r);return s.__innerSetRemoteMuted(0===e.state),s}));this._onTrackPublish(r)})),Object.keys(a).forEach((e=>{a[e].forEach((e=>{const t=mt(e),r=this._remoteTracks[t];r.__innerSetRemoteMuted(0===e.state),r.isAudioTrack()?this._onAudioMuteChange(r):this._onVideoMuteChange(r)}))})),{data:r}}))}_onAudioMuteChange(e){this._callAppListener("onAudioMuteChange",e)}_onVideoMuteChange(e){this._callAppListener("onVideoMuteChange",e)}_afterChangedRole(e){}_removeRemoteTracks(){const e=Object.values(this._remoteTracks);e.length&&(e.forEach((e=>{e.isAudioTrack()&&e.__releaseMediaElement()})),this._remoteTracks={})}_registerPKMsgListener(e){this._onRecvPKMsg=e}_quitAllPKRoom(){}}var ir,nr,sr;!function(e){e[e.CROP=1]="CROP",e[e.WHOLE=2]="WHOLE"}(ir||(ir={})),function(e){e[e.CUSTOMIZE=1]="CUSTOMIZE",e[e.SUSPENSION=2]="SUSPENSION",e[e.ADAPTATION=3]="ADAPTATION"}(nr||(nr={})),function(e){e[e.CROP=1]="CROP",e[e.WHOLE=2]="WHOLE"}(sr||(sr={}));const or=()=>({version:1,mode:nr.SUSPENSION});class ar{constructor(e,t,r){this._onFlush=e,this._isValidTrackId=t,this._sendCDNInfoSignal=r,this._values=or()}setHostVideoTrack(e){if(!this._isValidTrackId(e))return C.error(`setHostVideoTrack failed: videoTrackId is invalid -> ${e}`),this;const{mediaType:t,tag:r,userId:i}=ft(e);return t!==Fe.VIDEO_ONLY?(C.error(`setHostVideoTrack failed: kind of resource is not 'video' -> ${e}`),this):(this._values.host_stream_id=vt(i,r),this)}setMixLayoutMode(e){return[nr.CUSTOMIZE,nr.SUSPENSION,nr.ADAPTATION].includes(e)?(this._values.mode=e,this):(C.error(`layout mode is invalid: ${e}`),this)}_addOutputValue(e,t,r="normal"){const i=this._values.output||(this._values.output={video:{normal:{width:640,height:480}}});if("cdn"===e)return void(i.cdn=t);if("audio"===e)return void(i.audio={bitrate:t});const n=i.video;if("normal"!==r&&"tiny"!==r)if("backgroundColor"!==r)if("exparams"!==r){if("backgroundPicture"===r){const e=n.backgroundPicture||(n.backgroundPicture={fillMode:ir.CROP,picture:[]});Object.assign(e,t)}}else n.exparams={renderMode:t};else n.backgroundColor=t;else{const e=n[r]||(n[r]={});Object.assign(e,t)}}setOutputVideoResolution(e){if(!Tt(e))return C.warn("setOutputVideoResolution failed: `resolution` is invalid"),this;const{width:t,height:r}=Ct(e);return this._addOutputValue("video",{width:t,height:r},"normal"),this}setOutputVideoFPS(e){if(!It(e))return C.warn("setOutputVideoFPS failed: `fps` is invalid"),this;const t=Et(e);return this._addOutputValue("video",{fps:t},"normal"),this}setOutputVideoBitrate(e){return!r(e)||e<=0?C.error(`bitrate is invalid: ${e}`):this._addOutputValue("video",{bitrate:e},"normal"),this}setOutputTinyVideoResolution(e){if(!Tt(e))return C.warn("setOutputTinyVideoResolution failed: `resolution` is invalid"),this;const{width:t,height:r}=Ct(e);return this._addOutputValue("video",{width:t,height:r},"tiny"),this}setOutputTinyVideoFPS(e){if(!It(e))return C.warn("setOutputTinyVideoFPS failed: `fps` is invalid"),this;const t=Et(e);return this._addOutputValue("video",{fps:t},"tiny"),this}setOutputTinyVideoBitrate(e){return!r(e)||e<=0?C.error(`bitrate is invalid: ${e}`):this._addOutputValue("video",{bitrate:e},"tiny"),this}setOutputVideoRenderMode(e){return[sr.CROP,sr.WHOLE].includes(e)?this._addOutputValue("video",e,"exparams"):C.error(`renderMode is invalid: ${e}`),this}setOutputAudioBitrate(e){return r(e)&&e>0?this._addOutputValue("audio",e):C.error(`bitrate is invalid: ${e}`),this}setOutputBackgroundColor(e){return/^0x[a-fA-F0-9]{6}$/.test(e)?this._addOutputValue("video",e,"backgroundColor"):C.error(`color is invalid: ${e}`),this}addOutputBackgroundPicture(e,t,i,n,s){var o,a,c;if(!l(e))return C.error(`uri is invalid: ${e}`),this;if([t,i,n,s].some((e=>!r(e)||e<0||e>1)))return C.error(`some attrs of (x, y, w, h) is invalid: ${t}, ${i}, ${n}, ${s}`),this;const d=(null===(c=null===(a=null===(o=this._values.output)||void 0===o?void 0:o.video)||void 0===a?void 0:a.backgroundPicture)||void 0===c?void 0:c.picture)||[];return d.push({uri:e,w:n,h:s,x:t,y:i}),this._addOutputValue("video",{picture:d},"backgroundPicture"),this}removeOutputBackgroundPicture(e){var t,r,i;if(!l(e))return C.error(`uri is invalid: ${e}`),this;let n=null===(i=null===(r=null===(t=this._values.output)||void 0===t?void 0:t.video)||void 0===r?void 0:r.backgroundPicture)||void 0===i?void 0:i.picture;return n&&(n=n.filter((t=>t.uri!==e)),this._addOutputValue("video",{pictures:n},"backgroundPicture")),this}clearOutputBackgroundPicture(){return this._addOutputValue("video",{pictures:[]},"backgroundPicture"),this}setOutputBackgroundPictureFillMode(e){return[ir.CROP,ir.WHOLE].includes(e)?this._addOutputValue("video",{fillMode:e},"backgroundPicture"):C.error(`fillMode is invalid: ${e}`),this}addPublishStreamUrls(e){var t,r;const i=/^rtmp:\/\/.+/;if(!d(e)||0===e.length||e.some((e=>!i.test(e))))return C.error(`urls is invalid: ${e}`),this;const n=(null===(r=null===(t=this._values.output)||void 0===t?void 0:t.cdn)||void 0===r?void 0:r.concat())||[];let s=!1;return e.forEach((e=>{n.some((t=>t.pushurl===e))||(s=!0,n.push({pushurl:e}))})),n.length>5?(C.error("publish stream url no more than 5"),this):(s&&this._addOutputValue("cdn",n),this)}removePublishStreamUrls(e){var t,r;const i=/^rtmp:\/\/.+/;if(!d(e)||0===e.length||e.some((e=>!i.test(e))))return C.error(`urls is invalid: ${e}`),this;const n=(null===(r=null===(t=this._values.output)||void 0===t?void 0:t.cdn)||void 0===r?void 0:r.concat())||[];for(let t=n.length-1;t>=0;t-=1){const{pushurl:r}=n[t],i=e.indexOf(r);i>=0&&(e.splice(i,1),n.splice(t,1))}return this._addOutputValue("cdn",n),this}clearPublishStreamUrls(){return this._addOutputValue("cdn",[]),this}addCustomizeLayoutVideo(e,t,i,n,s){if(!this._isValidTrackId(e))return C.error(`trackId is invalid: ${e}`),this;if(!r(t)||!r(i))return C.error(`some attrs of (x, y) is invalid: ${t}, ${i}`),this;if([n,s].some((e=>!r(e)||e<0)))return C.error(`some attrs of (width, height) is invalid: ${n}, ${s}`),this;const{userId:o,tag:a,mediaType:c}=ft(e);if(c!==Fe.VIDEO_ONLY)return C.error(`kind of resource is not 'video': ${e}`),this;const d=vt(o,a);return(this._values.input||(this._values.input={video:[]})).video.push({user_id:o,stream_id:d,x:t,y:i,width:n,height:s}),this}removeCustomizeLayoutVideo(e){if(!this._isValidTrackId(e))return C.error(`trackId is invalid: ${e}`),this;const{userId:t,tag:r,mediaType:i}=ft(e);if(i!==Fe.VIDEO_ONLY)return C.error(`kind of resource is not 'video': ${e}`),this;const n=vt(t,r),s=this._values.input||(this._values.input={video:[]});return s.video=s.video.filter((e=>e.stream_id===n)),this}clearCustomizeLayoutVideo(){return(this._values.input||(this._values.input={video:[]})).video=[],this}flush(){var e,t,r,i;return S(this,void 0,void 0,(function*(){const n=JSON.parse(JSON.stringify(this._values)),{code:s}=yield this._onFlush(n);return s===T.SUCCESS&&((null===(t=null===(e=this._values.output)||void 0===e?void 0:e.video.normal)||void 0===t?void 0:t.width)||(null===(i=null===(r=this._values.output)||void 0===r?void 0:r.video.normal)||void 0===i?void 0:i.fps))&&this._sendCDNInfoSignal(),this._values=or(),{code:s}}))}}var cr,dr,ur,lr;!function(e){e[e.OPEN=1]="OPEN",e[e.STOP=2]="STOP"}(cr||(cr={})),function(e){e[e.SPREAD=0]="SPREAD",e[e.NO_SPREAD=-1]="NO_SPREAD"}(dr||(dr={})),function(e){e[e.AUTOMATIC=0]="AUTOMATIC",e[e.MANUAL=1]="MANUAL"}(ur||(ur={})),function(e){e[e.VIDEO=0]="VIDEO",e[e.AUDIO=1]="AUDIO"}(lr||(lr={}));const hr=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}));class pr{constructor(e,t,r,i,n,s,o,a){this._context=e,this._runtime=t,this._service=r,this._initOptions=i,this._mainLivingRoom=n,this._registerPKMsgListener=s,this._onJoinedPKRoom=o,this._onLeavePKRoom=a,this._inviteTimeout=30,this._PKInfo={},this._appListener=null,this._joinedPKRooms={},this._registerPKMsgListener(this._onRecvPKMsg.bind(this)),this._mainRoomId=this._mainLivingRoom.getRoomId()}_callAppListener(e,...t){var r;const i=null===(r=this._appListener)||void 0===r?void 0:r[e];if(i)try{i(...t)}catch(e){C.error(e)}}_onInvite(e){const t=e.inviteInfo||{},{inviterRoomId:r,inviterUserId:i,extra:n}=t,s={inviterRoomId:r,inviterUserId:i};n&&Object.assign(s,{extra:n}),this._PKInfo[r]=t,this._callAppListener("onRequestJoinOtherRoom",s)}_onCancelInvite(e){const{inviterRoomId:t,inviterUserId:r,extra:i}=e.inviteInfo||{},n={inviterRoomId:t,inviterUserId:r};i&&Object.assign(n,{extra:i}),delete this._PKInfo[t],this._callAppListener("onCancelRequestOtherRoom",n)}_onInviteTimeout(e){}_onInviteAnswer(e){const{answerCode:t,inviteContent:r,inviteeUserAutoMix:i}=e,{inviterUserId:n,inviterRoomId:s,inviteeUserId:o,inviteeRoomId:a,extra:c}=r,d={agree:1===t,inviterRoomId:s,inviterUserId:n,inviteeRoomId:a,inviteeUserId:o};this._PKInfo[a].inviteeUserAutoMix=i,this._callAppListener("onResponseJoinOtherRoom",d)}_onPKEnd(e){return S(this,void 0,void 0,(function*(){const{inviteeRoomId:t,inviterRoomId:r,userId:i}=e.inviteInfo,n=r===this._mainRoomId?t:r,s={endRoomId:n,endUserId:i};yield this.leaveOtherRoom(this._joinedPKRooms[n]),delete this._PKInfo[n],this._callAppListener("onFinishOtherRoom",s)}))}_onRecvPKMsg(e){const{targetId:t,content:r,messageType:i}=e;switch(i){case Nt.PK_INVITE:this._onInvite(r);break;case Nt.PK_CANCEL_INVITE:this._onCancelInvite(r);break;case Nt.PK_INVITE_TIMEOUT:this._onInviteTimeout(r);break;case Nt.PK_INVITE_ANSWER:this._onInviteAnswer(r);break;case Nt.PK_END:this._onPKEnd(r)}}registerRoomPKEventListener(e){this._appListener=e}requestJoinOtherRoom(e,t,r){return S(this,void 0,void 0,(function*(){if(!c("inviteeRoomId",e,h,!0)||!c("inviteeUserId",t,h,!0))return{code:T.PARAMS_ERROR};C.debug(`requestRoomPK -> inviteeRoomId: ${e}; inviteeUserId: ${t}; options: ${JSON.stringify(r||{})}`);const n=hr(),s=!p(null==r?void 0:r.autoMix)||(null==r?void 0:r.autoMix),o={inviteSessionId:n,inviterRoomId:this._mainRoomId,inviterUserId:this._context.getCurrentId(),inviterUserAutoMix:s,inviteeRoomId:e,inviteeUserId:t,inviteeTimeoutTime:this._inviteTimeout,extra:(null==r?void 0:r.extra)||""},a={roomId:this._mainRoomId,invitedRoomId:e,invitedUserId:t,inviteTimeout:this._inviteTimeout,inviteInfo:JSON.stringify(o),inviteSessionId:n};C.debug(`requestRoomPK -> params: ${JSON.stringify(a)}`);const d=yield this._context.requestRoomPK(a);return d!==i.SUCCESS?(C.error(`requestRoomPK failed: ${d}`),{code:d}):(C.debug("requestRoomPK success"),this._PKInfo[e]={inviteSessionId:n,inviterRoomId:this._mainRoomId,inviterUserId:this._context.getCurrentId(),inviterUserAutoMix:s,inviteeRoomId:e},{code:T.SUCCESS})}))}cancelRequestJoinOtherRoom(e,t,r){return S(this,void 0,void 0,(function*(){if(!c("inviteeRoomId",e,h,!0)||!c("inviteeUserId",t,h,!0))return{code:T.PARAMS_ERROR};if(!this._PKInfo[e])return C.error(`未发起过与 ${e} 房间内 ${t} 连麦的请求`),{code:T.PARAMS_ERROR};C.debug(`canceRequestJoinPK -> inviteeRoomId: ${e}; inviteeUserId: ${t}; extra: ${r}`);const n={inviterRoomId:this._mainRoomId,inviterUserId:this._context.getCurrentId(),inviteeRoomId:e,inviteeUserId:t,extra:r||""},s={roomId:this._mainRoomId,invitedRoomId:e,invitedUserId:t,inviteSessionId:this._PKInfo[e].inviteSessionId,inviteInfo:JSON.stringify(n)};C.debug(`canceRequestJoinPK -> params: ${JSON.stringify(s)}`);const o=yield this._context.cancelRoomPK(s);return o!==i.SUCCESS?(C.error(`canceRequestJoinPK failed: ${o}`),{code:o}):(C.debug("canceRequestJoinPK success"),delete this._PKInfo[e],{code:T.SUCCESS})}))}responseJoinOtherRoom(e,t,r,n){return S(this,void 0,void 0,(function*(){if(!c("inviterRoomId",e,h,!0)||!c("inviterUserId",t,h,!0))return{code:T.PARAMS_ERROR};if(!this._PKInfo[e])return C.error(`${e} 房间内的 ${t} 未发起过连麦请求`),{code:T.PARAMS_ERROR};C.debug(`responseRoomPK -> inviterRoomId: ${e}; inviterUserId: ${t}; agree: ${r}; options: ${JSON.stringify(n||{})}`);const{inviteSessionId:s,inviterUserAutoMix:o}=this._PKInfo[e],a=!p(null==n?void 0:n.autoMix)||(null==n?void 0:n.autoMix),d={inviteSessionId:s,inviterRoomId:e,inviterUserId:t,inviteeRoomId:this._mainRoomId,inviteeUserId:this._context.getCurrentId(),inviteeUserAutoMix:a},u=Object.assign(d,{inviterUserAutoMix:o}),l=r?Object.assign(d,{MultiRoomKey:`${e}|${this._mainRoomId}`,MultiRoomValue:JSON.stringify(u)}):d;!_(null==n?void 0:n.extra)&&Object.assign(l,{extra:n.extra});const m={agree:r,roomId:this._mainRoomId,inviteSessionId:s,inviteRoomId:e,inviteUserId:t,content:JSON.stringify(l),key:`${e}|${t}`,value:JSON.stringify(d)};C.debug(`responseRoomPK -> params: ${JSON.stringify(m)}`);const f=yield this._context.responseRoomPK(m);return f!==i.SUCCESS?(C.error(`responseRoomPK failed: ${f}`),{code:f}):(C.debug("responseRoomPK success"),this._PKInfo[e].inviteeUserAutoMix=a,{code:T.SUCCESS})}))}_quitRoomPK(e){return S(this,void 0,void 0,(function*(){const{inviterRoomId:t,inviteeRoomId:r,inviterUserId:n}=this._PKInfo[e],s={inviteeRoomId:r,inviterRoomId:t,userId:this._context.getCurrentId()},o={roomId:this._mainRoomId,endRoomId:e,sessionId:this._PKInfo[e].inviteSessionId,content:JSON.stringify(s),keys:[`${t}|${n}`]};C.debug(`quitRoomPK -> params: ${JSON.stringify(o)}`);const a=yield this._context.endRoomPK(o);return a!==i.SUCCESS?(C.error(`quitRoomPK failed: ${a}`),{code:T.SIGNAL_ERROR}):(C.debug("quitRoomPK success"),delete this._PKInfo[e],{code:T.SUCCESS})}))}_relaseCrtRoom(){}joinOtherRoom(e){return S(this,void 0,void 0,(function*(){if(!c("roomId",e,h,!0))return{code:T.PARAMS_ERROR};if(this._context.getConnectionStatus()!==n.CONNECTED)return{code:T.SIGNAL_DISCONNECTED};if(C.debug(`joinPKRoom, roomId: ${e}`),this._joinedPKRooms[e])return{code:T.REPERT_JOIN_ROOM};const t=lr.VIDEO,{code:r,data:s}=yield this._context.joinRTCRoom(e,u.LIVE,t);if(r!==i.SUCCESS)return C.error(`joinRoom failed -> code: ${r}`),{code:r};C.debug(`JoinPKRoom success -> userId: ${this._context.getCurrentId()}, roomId: ${e}, data: ${JSON.stringify(s)}`);const o=new _r(this._context,this._runtime,e,s,this._service,this._initOptions,this._relaseCrtRoom.bind(this),t,!1,!1);return this._joinedPKRooms[e]=o,this._onJoinedPKRoom(e,o),{room:o,code:T.SUCCESS,userIds:o.getRemoteUserIds(),tracks:o.getRemoteTracks()}}))}leaveOtherRoom(e,t){return S(this,void 0,void 0,(function*(){return k((()=>S(this,void 0,void 0,(function*(){const r=e.getRoomId();return C.debug(`leavePKRoom -> userId: ${this._context.getCurrentId()} , roomId: ${r}`),yield e.__destroy(!0),delete this._joinedPKRooms[r],this._onLeavePKRoom(r),this._PKInfo[r]?(t&&this._quitRoomPK(r),{code:T.SUCCESS}):{code:T.SUCCESS}}))))}))}getPKInfo(e){return this._PKInfo[e]}getJoinedPKRooms(){return this._joinedPKRooms}}class _r extends rr{constructor(e,t,r,i,n,s,o,a,c=!1,d){var l;super(e,t,r,i,u.LIVE,n,s,o,c,d),this._livingType=a,this._isMainRoom=d,this._CDNUris=null,this._CDNEnable=!1,this._mcuConfigBuilder=new ar(this._onMCUConfigFlush.bind(this),this._isValidResourceId.bind(this),this._sendCDNInfoSignal.bind(this)),this._isMainRoom&&(this._roomPKHandler=new pr(e,t,n,s,this,super._registerPKMsgListener.bind(this),this._onJoinedPKRoom.bind(this),this._onLeavePKRoom.bind(this)));const h=null===(l=i.roomInfo.filter((e=>"cdn_uris"===e.key))[0])||void 0===l?void 0:l.value;h&&(this._CDNUris=JSON.parse(h)[0])}_isValidResourceId(e){var t;const{userId:r}=ft(e),i=!!(null===(t=this._roomResources[r])||void 0===t?void 0:t.find((t=>mt(t)===e)));let n=!1;const{code:s,roomPKHandler:o}=this.getRoomPKHandler();if(s!==T.SUCCESS||!o)return i;const a=o.getJoinedPKRooms(),c=[];return Object.values(a).map((e=>{c.push(...e.getRemoteTracks())})),n=c.some((t=>e===t.getTrackId())),i||n}getLivingType(){return this._livingType}getMCUConfigBuilder(){return this._isMainRoom?this._mcuConfigBuilder:(C.error("the `getMCUConfigBuilder` is disabled in PK room "),{code:T.THE_FUNCTION_IS_DISABLED_IN_PKROOM})}_onMCUConfigFlush(e){return S(this,void 0,void 0,(function*(){const t={"App-Key":this._context.getAppkey(),Token:this._token,RoomId:this.getRoomId(),UserId:this._context.getCurrentId(),SessionId:this.getSessionId()},{code:r,res:i}=yield this._service.setMcuConfig(t,e);return r!==T.SUCCESS?(C.error(`set MCU config failed: ${r}`),{code:r}):(C.info("set MCU config success"),i.pull_url&&(this._CDNUris=JSON.parse(i.pull_url)),{code:r,res:i})}))}__onReconnected(){const e=Object.create(null,{__onReconnected:{get:()=>super.__onReconnected}});var t,r;return S(this,void 0,void 0,(function*(){const i=yield e.__onReconnected.call(this,this._livingType);if(!i||!i.data)return;const n=i.data.roomInfo,s=null===(t=n.filter((e=>"cdn_uris"===e.key))[0])||void 0===t?void 0:t.value;if(!s)return;const o=JSON.parse(s);(null===(r=this._CDNUris)||void 0===r?void 0:r.enableInnerCDN)!==o.enableInnerCDN&&this._callAppListener("onCDNEnableChange",o.enableInnerCDN),this._CDNUris=o}))}enableInnerCDN(e){return S(this,void 0,void 0,(function*(){if(!this._isMainRoom)return C.error("the `enableInnerCDN` is disabled in PK room "),{code:T.THE_FUNCTION_IS_DISABLED_IN_PKROOM};if(!p(e))return C.error("`enable` is invalid"),{code:T.PARAMS_ERROR};this._CDNEnable=e;const t={version:2,output:{inCDNModel:e?cr.OPEN:cr.STOP}},{code:r}=yield this._onMCUConfigFlush(t);if(r!==T.SUCCESS)return C.error(`enableInnerCDN failed -> code: ${r}`),{code:T.SIGNAL_ERROR};if(this._CDNUris&&this._CDNUris.broadcast!==dr.SPREAD)return C.info("enableInnerCDN succeed"),{code:T.SUCCESS};const{code:i}=yield k((()=>S(this,void 0,void 0,(function*(){return this._sendCDNInfoSignal()}))));return i===T.SUCCESS?(C.info("enableInnerCDN succeed"),{code:T.SUCCESS}):(C.error(`enableInnerCDN failed -> code: ${i}`),{code:i})}))}_sendCDNInfoSignal(){return S(this,void 0,void 0,(function*(){this._CDNUris=Object.assign({},this._CDNUris,{enableInnerCDN:this._CDNEnable});return(yield Promise.all([this._spreadCDNInfo(this._CDNUris),this._setRoomCDNInfo(this._CDNUris)])).every((e=>e.code===T.SUCCESS))?{code:T.SUCCESS}:{code:T.SIGNAL_ERROR}}))}_spreadCDNInfo(e){return S(this,void 0,void 0,(function*(){const t=yield this._context.setRTCCDNUris(this._roomId,Nt.TOTAL_CONTENT_RESOURCE,JSON.stringify([e]));return t!==i.SUCCESS?(C.error(`spreadCDNInfo failed -> code: ${t}`),{code:T.SIGNAL_ERROR}):(C.info("spreadCDNInfo succeed"),{code:T.SUCCESS})}))}_setRoomCDNInfo(e){return S(this,void 0,void 0,(function*(){const t=yield this._context.setRTCData(this._roomId,"cdn_uris",JSON.stringify([e]),!0,a.ROOM);return t!==i.SUCCESS?(C.error(`setRoomCDNInfo failed -> code: ${t}`),{code:T.SIGNAL_ERROR}):(C.info("setRoomCDNInfo succeed"),{code:T.SUCCESS})}))}_resourceHandle(e,t,r){const i=Object.create(null,{_resourceHandle:{get:()=>super._resourceHandle}});var n;return S(this,void 0,void 0,(function*(){i._resourceHandle.call(this,e,t,r),e.cdn_uris&&((null===(n=this._CDNUris)||void 0===n?void 0:n.enableInnerCDN)!==e.cdn_uris[0].enableInnerCDN&&this._callAppListener("onCDNEnableChange",!this.__getCDNEnable()),this._CDNUris=e.cdn_uris[0])}))}_exchangeHandle(e){var t,r,i;return S(this,void 0,void 0,(function*(){const n=yield this._service.exchange(this._getRTCReqestHeaders(),e),s=null===(r=null===(t=n.data)||void 0===t?void 0:t.urls)||void 0===r?void 0:r.pull_url;return n.code===T.SUCCESS&&s?(this._CDNUris=JSON.parse(s),(null===(i=this._CDNUris)||void 0===i?void 0:i.broadcast)===dr.SPREAD&&(this._CDNEnable=!0,this._sendCDNInfoSignal()),n):n}))}_afterChangedRole(e){const t=Lt(e),r=this._context.getCurrentId(),i=Object.keys(t);setTimeout((()=>{var n,s,o;const a=i.filter((e=>e!==r));a.length>0&&this._callAppListener("onUserJoin",a);for(const e in t)e!==r&&this._resourceHandle({uris:t[e]},Nt.TOTAL_CONTENT_RESOURCE,e);(null===(n=e.roomInfo.filter((e=>"cdn_uris"===e.key))[0])||void 0===n?void 0:n.value)&&(null===(s=this._CDNUris)||void 0===s?void 0:s.push_mode)===ur.MANUAL&&this._callAppListener("onCDNEnableChange",null===(o=this._CDNUris)||void 0===o?void 0:o.enableInnerCDN)}))}__getCDNEnable(){var e;return null===(e=this._CDNUris)||void 0===e?void 0:e.enableInnerCDN}__getCDNPushMode(){var e;return null===(e=this._CDNUris)||void 0===e?void 0:e.push_mode}_onJoinedPKRoom(e,t){const{code:r,roomPKHandler:i}=this.getRoomPKHandler();if(r===T.SUCCESS&&i){if(!i.getPKInfo(e))return;this._exchangeWithPushOtherRoom()}}_onLeavePKRoom(e){const{code:t,roomPKHandler:r}=this.getRoomPKHandler();if(t===T.SUCCESS&&r){if(!r.getPKInfo(e))return;this._exchangeWithPushOtherRoom()}}_exchangeWithPushOtherRoom(){return S(this,void 0,void 0,(function*(){if(!this.getLocalTracks().length)return;const e=yield this._createExchangeParams(this._subscribedList,!1),t=this._getPushOtherRoomsParams();t&&(e.pushOtherRooms=t);const r=yield this._exchangeHandle(e);if(r.code!==T.SUCCESS)return C.error(`reTryExchange failed: ${r.code}`),{code:r.code};const{sdp:i,resultCode:n}=r.data;if(n!==T.SUCCESS)return C.error(`exchange with pushOtherRoom failed: ${n}`),{code:n};const s=yield this._pc.setRemoteAnswer(i.sdp);return s!==T.SUCCESS?{code:s}:void 0}))}getRoomPKHandler(){return this._isMainRoom?{code:T.SUCCESS,roomPKHandler:this._roomPKHandler}:(C.error("the `getRoomPKHandler` is disabled in PK room "),{code:T.THE_FUNCTION_IS_DISABLED_IN_PKROOM})}_quitAllPKRoom(){const e=this._roomPKHandler.getJoinedPKRooms();for(const t in e){const r=e[t];this._roomPKHandler.leaveOtherRoom(r)}}}class mr extends rr{constructor(e,t,r,i,n,s,o){super(e,t,r,i,u.RTC,n,s,o,!1)}}const fr=()=>({"Content-Type":"application/json;charset=UTF-8","Cache-Control":"no-cache",ClientType:`web|${yt.browser}|${yt.version}`,ClientVersion:"5.3.1","Client-Session-Id":hr(),"Request-Id":Date.now().toString()});class vr{constructor(e,t,r,i=5e3){this._runtime=e,this._context=t,this._msUrl=r,this._timeout=i,this._msInNavi=[],this._failedMs=[],this._rtcFinger=void 0,this._clusterId="",this._configUrl=""}getNaviMS(){return this._msUrl?[this._msUrl]:this._clusterId?[`https://${this._clusterId}`]:(0===this._msInNavi.length&&(0===this._failedMs.length?this._msInNavi.push(...(e=>{var t;if(!e)return[];let r;try{r=JSON.parse(e.voipCallInfo||'{ "strategy": 0 }')}catch(t){return C.warn("parse `voipCallInfo` of navi failed: "+e.voipCallInfo),[]}if(0===r.strategy)return[];const i=null===(t=r.callEngine)||void 0===t?void 0:t.filter((e=>4===e.engineType));if(!i||0===i.length)return[];const n=i[0],s=[];return n.mediaServer&&s.push(n.mediaServer.replace(/^(https?:\/\/)?/,"https://")),n.backupMediaServer&&n.backupMediaServer.forEach((e=>{s.push(e.replace(/^(https?:\/\/)?/,"https://"))})),s})(this._context.getNaviInfo())):(this._msInNavi.push(...this._failedMs),this._failedMs.length=0)),this._msInNavi.map((e=>e.trim())))}_request(e,t,r){return S(this,void 0,void 0,(function*(){const i=this.getNaviMS();if(0===i.length)return{code:T.NOT_OPEN_VIDEO_AUDIO_SERVER};this._rtcFinger&&(r.rtcFinger=this._rtcFinger);for(let n=0;n<i.length;n+=1){const s=`${i[n]}${e}`,o=fr();C.debug(`request -> Request-Id: ${o["Request-Id"]}, url: ${s}`);const{status:a,data:c}=yield this._runtime.httpReq({url:s,body:JSON.stringify(r),headers:Object.assign(Object.assign({},o),t),method:m.POST,timeout:this._timeout});if(200===a){const e=JSON.parse(c);return e.rtcFinger&&(this._rtcFinger=e.rtcFinger),e.clusterId&&(this._clusterId=e.clusterId),C.debug(`request success -> Request-Id: ${o["Request-Id"]}`),{code:T.SUCCESS,data:e}}C.warn(`request failed -> Request-Id: ${o["Request-Id"]}, status: ${a}, url: ${s}`),this._failedMs.push(...this._msInNavi.splice(n,1))}return{code:T.REQUEST_FAILED}}))}exchange(e,t){var r;return S(this,void 0,void 0,(function*(){const i=yield this._request("/exchange",e,t);if(i.code===T.SUCCESS&&(null===(r=i.data)||void 0===r?void 0:r.resultCode)===T.SUCCESS){const e=i.data.urls;e&&(this._configUrl=e.configUrl)}return i}))}exit(e){return S(this,void 0,void 0,(function*(){const{code:t}=yield this._request("/exit",e,{});return t}))}broadcastSubscribe(e,t){return this._request("/broadcast/subscribe",e,t)}broadcastExit(e){return S(this,void 0,void 0,(function*(){const{code:t}=yield this._request("/broadcast/exit",e,{});return{code:t}}))}setMcuConfig(e,t){return S(this,void 0,void 0,(function*(){if(!this._configUrl)return{code:T.MCU_SERVER_NOT_FOUND};const r=`${this._configUrl.replace(/^(https?:\/\/)?/,"https://")}/server/mcu/config`,i=fr();C.debug(`request -> Request-Id: ${i["Request-Id"]}, url: ${r}`);const{status:n,data:s}=yield this._runtime.httpReq({url:r,headers:Object.assign(Object.assign({},i),e),body:JSON.stringify(t),method:m.POST});if(200===n){C.debug(`request success -> Request-Id: ${i["Request-Id"]}`);const e=JSON.parse(s);return{code:e.resultCode,res:e}}return{code:T.REQUEST_FAILED}}))}getCDNResourceInfo(e,t){return S(this,void 0,void 0,(function*(){const r=fr(),{status:i,data:n}=yield this._runtime.httpReq({url:t,headers:Object.assign(Object.assign({},r),e),method:m.GET});if(200===i){const e=JSON.parse(n);return{code:e.resultCode,res:e}}return C.warn(`request failed -> Request-Id: ${r["Request-Id"]}, status: ${i}, url: ${t}`),{code:T.REQUEST_FAILED}}))}}class Rr{constructor(e,t,r){this._context=e,this._rtcToken="",this._liveUrl="",this._subTracks=[],this._livingType=null,this._mediaType=null,this._subTiny=!1,this._fromRetry=!1,this._appListener=null,this._service=new vr(t,e,r.mediaServer)}_getReqHeaders(e){return S(this,void 0,void 0,(function*(){const t=this._context.getCurrentId(),r=t;if(!this._rtcToken){const{code:t,data:n}=yield this._context.getRTCToken(r,u.LIVE,e);if(t!==i.SUCCESS)return C.error(`getRTCToken failed: ${t}`),{code:T.SIGNAL_ERROR};this._rtcToken=n.rtcToken}return{code:T.SUCCESS,headers:{"App-Key":this._context.getAppkey(),UserId:t,RoomId:r,RoomType:u.LIVE,Token:this._rtcToken}}}))}_clearSubscribeInfo(){var e;this._liveUrl="",this._livingType=null,this._mediaType=null,this._subTiny=!1,this._subTracks.length=0,null===(e=this._pc)||void 0===e||e.destroy(),this._pc=null}_reTryExchange(){var e;return S(this,void 0,void 0,(function*(){this._fromRetry=!0;const{code:t}=yield this.subscribe(this._liveUrl,this._livingType,this._mediaType,this._subTiny);t===T.SUCCESS&&(null===(e=this._pc)||void 0===e||e.clearReTryExchangeTimer())}))}subscribe(e,t,r,i=!1){return S(this,void 0,void 0,(function*(){return k((()=>this.__subscribe(e,t,r,i)))}))}__subscribe(e,t,r,i=!1){var n;return S(this,void 0,void 0,(function*(){const s=[];if(Ot(this._context.getNaviInfo()))return{code:T.PACKAGE_ENVIRONMENT_ERROR,tracks:s};if(!this._fromRetry&&(null===(n=this._pc)||void 0===n||n.clearReTryExchangeTimer()),this._fromRetry=!1,!f(e))return C.error(`liveUrl is invalid: ${e}`),{code:T.PARAMS_ERROR,tracks:s};if(![lr.AUDIO,lr.VIDEO].includes(t))return C.error(`livingType is invalid: ${t}`),{code:T.PARAMS_ERROR,tracks:s};if(![Fe.AUDIO_ONLY,Fe.VIDEO_ONLY,Fe.AUDIO_VIDEO].includes(r))return C.error(`mediaType is invalid: ${r}`),{code:T.PARAMS_ERROR,tracks:s};if(this._liveUrl&&this._liveUrl!==e)return{code:T.BROADCAST_SUB_LIST_NOT_EMPTY,tracks:s};this._pc||(this._pc=new Wt(this._reTryExchange.bind(this)),this._pc.on(Wt.__INNER_EVENT_TRACK_READY__,this._onTrackReady,this),this.registerReportListener(this._reportListener)),this._liveUrl=e;const{code:o,headers:a}=yield this._getReqHeaders(t);if(o!==T.SUCCESS)return{code:o,tracks:s};const c=`rc_mcu_${Date.now()}`,d="RongCloudRTC";0===this._subTracks.length&&(this._subTracks.push(new ot(d,c),new at(d,c)),this._pc.updateSubRemoteTracks(this._subTracks.slice()));const u={sdp:yield this._pc.createOffer(!0),liveUrl:e,mediaType:r,simulcast:i?Mt.TINY:Mt.NORMAL,switchstream:!1},l=yield this._service.broadcastSubscribe(a,u);if(l.code!==T.SUCCESS)return C.error(`andience subscribe failed: ${l.code}`),{code:l.code,tracks:s};const h=l.data;if(h.resultCode!==T.SUCCESS)return C.error(`andience subscribe failed! code: ${h.resultCode}; message: ${h.message}`),{code:h.resultCode,tracks:s};C.debug(`andience subscribe success: ${e}`),this._livingType=t,this._mediaType=r,this._subTiny=i;const{sdp:p,subscribedList:_}=h,m=[];return _.forEach((e=>{const{mediaType:t}=e,r=this._subTracks[t];m.push(r),r.__innerSetRemoteMuted(!0)})),this._pc.setRemoteAnswer(p.sdp),{code:T.SUCCESS,tracks:m}}))}unsubscribe(){return S(this,void 0,void 0,(function*(){return k((()=>this.__unsubscribe()))}))}__unsubscribe(){var e;return S(this,void 0,void 0,(function*(){if(null===(e=this._pc)||void 0===e||e.clearReTryExchangeTimer(),!this._rtcToken||!this._liveUrl)return{code:T.SUCCESS};const{headers:t}=yield this._getReqHeaders(),{code:r}=yield this._service.broadcastExit(t);return r!==T.SUCCESS?C.error(`broadcast unsubscribe failed: ${r}`):C.debug("broadcast unsubscribe success"),this._clearSubscribeInfo(),{code:r}}))}registerReportListener(e){var t;this._reportListener=e,null===(t=this._pc)||void 0===t||t.registerReportListener(e)}registerTrackEventListener(e){this._appListener=e}_onTrackReady(e){var t,r;const i=e.receiver.track,n="audio"===i.kind?Fe.AUDIO_ONLY:Fe.VIDEO_ONLY,s=this._subTracks[n];s.__innerSetMediaStreamTrack(i);try{null===(r=null===(t=this._appListener)||void 0===t?void 0:t.onTrackReady)||void 0===r||r.call(t,s)}catch(e){C.error(e)}}}var gr,Sr;!function(e){e.RTMP="rtmp",e.FLV="flv",e.HLS="hls"}(gr||(gr={})),function(e){e[e.NOT_HTTPS=0]="NOT_HTTPS",e[e.HTTPS=1]="HTTPS"}(Sr||(Sr={}));const Cr=Object.assign(Object.assign({},Ct(He.W176_H144)),{frameRate:Et(Be.FPS_15)});class Tr{constructor(e,t,r,i,n,s){this._context=e,this._runtime=t,this._initOptions=r,this._roomId=i,this._joinResData=n,this._livingType=s,this._roomAnchorList=[],this._roomRes={},this._roomAnchorRes={},this._remoteTracks={},this._appListener=null,this._subscribedList=[],this._sessionId="",this._destroyed=!1,this._setInitData(),this._service=new vr(this._runtime,this._context,this._initOptions.mediaServer,this._initOptions.timeout),this._polarisReport=new Zt(this._context,this._runtime,this._roomId,this,qt.Audience),this._polarisReport.sendR1(),this._pc=new Wt(this._reTryExchange.bind(this),this._polarisReport),this._pc.on(Wt.__INNER_EVENT_TRACK_READY__,(e=>{const t=e.streams[0].id,r=e.receiver.track,i=[t,"audio"===r.kind?Fe.AUDIO_ONLY:Fe.VIDEO_ONLY].join("_"),n=this._remoteTracks[i];n?(n.__innerSetMediaStreamTrack(r),this._callAppListener("onTrackReady",n)):C.warn("cannot found RCRemoteTrack:",r.id)})),this._context.onrtcdatachange=this.singalDataChange.bind(this)}_setInitData(){const{sessionId:e,remoteUserIds:t,remoteRTCUris:r,remoteMUCUris:i,remoteTracks:n,CDNUris:s}=((e,t)=>{const r=t.filter((e=>"RC_RTC_SESSIONID"===e.key))[0],i=r?r.value:"",n=t.filter((e=>"RC_ANCHOR_LIST"===e.key)).map((e=>JSON.parse(e.value||"[]")))[0],s=t.filter((e=>e.key.includes("RC_RES_"))).map((e=>JSON.parse(e.value||"{}"))),o=s.length?JSON.parse(s[0].mcu_uris||"[]"):[],a=[];o.forEach((t=>{const{mediaType:r,tag:i}=t,n=r===Fe.AUDIO_ONLY?new ot(i,"",e):new at(i,"",e);a.push(n)}));const c=[],d=[];s.forEach((e=>{const t=JSON.parse(e.uris||"[]");c.push(...t),t.forEach((e=>{const{mediaType:t,tag:r,msid:i}=e,n=i.split("_")[0],s=t===Fe.AUDIO_ONLY?new ot(r,n):new at(r,n);d.push(s)}))}));const u=t.filter((e=>"RC_CDN"===e.key)).map((e=>{const t=JSON.parse(e.value||"[]");return JSON.parse(t.cdn_uris)[0]}))[0];return{sessionId:i,remoteUserIds:n||[],remoteRTCUris:c,remoteMUCUris:o,remoteRTCTracks:d,remoteMCUTracks:a,remoteTracks:[...d,...a],CDNUris:u||{}}})(this._roomId,this._joinResData.kvEntries);this._sessionId=e,this._roomAnchorList=t,n.forEach((e=>{this._remoteTracks[e.getTrackId()]=e})),this._CDNUris=s,r.forEach((e=>{const t=e.msid.split("_")[0];this._roomAnchorRes[t]?this._roomAnchorRes[t].push(e):this._roomAnchorRes[t]=[e]})),i.forEach((e=>{const{mediaType:t,tag:r}=e,i=[this._roomId,r,t].join("_");this._roomRes[i]=e})),r.forEach((e=>{const t=mt(e);this._roomRes[t]=e}))}_assertRoomDestroyed(){if(this._destroyed){const e="This room has been destroyed. Please use `RCRTCClient.joinLivingRoomAsAudience` to catch another instance.";return C.warn(e),T.ROOM_HAS_BEEN_DESTROYED}}singalDataChange(e,t){var r;if(t!==this._roomId)return void C.warn(`singalDataChange -> not the current room data: data roomId: ${t}, current roomId: ${this._roomId}`);C.debug("singalDataChange -> singalData:",JSON.stringify(e||{}));const i=[],n=null===(r=e.filter((e=>"RC_CDN"===e.key))[0])||void 0===r?void 0:r.value;n&&this._diffCDNUris(JSON.parse(JSON.parse(n).cdn_uris)[0]),e.forEach((e=>{const{key:t,value:r,timestamp:n,uid:s}=e;if(-1!==t.indexOf("RC_RES_")){const e=JSON.parse(r||"{}"),t=JSON.parse(e.mcu_uris||"[]"),n=JSON.parse(e.uris||"[]");return i.push(...t),void this._diffAnchorResource(n,s)}if("RC_ANCHOR_LIST"===t){const e=JSON.parse(r||"[]"),{joinUserIds:t,leftUserIds:i}=this._diffAnchorList(e);t.length>0&&this._handleNewJoinedAnchor(t),i.length>0&&this._handleLeftedAnchor(i)}})),this._diffRoomResource(i)}_diffAnchorList(e){const t=e.filter((e=>this._roomAnchorList.indexOf(e)<0));return{leftUserIds:this._roomAnchorList.filter((t=>e.indexOf(t)<0)),joinUserIds:t}}_handleNewJoinedAnchor(e){this._roomAnchorList.push(...e),this._callAppListener("onAnchorJoin",e)}_handleLeftedAnchor(e){return S(this,void 0,void 0,(function*(){this._roomAnchorList=this._roomAnchorList.filter((t=>!(e.indexOf(t)>-1)));const t=[];e.forEach((e=>{t.push(...this.getRemoteTracksByUserId(e)),delete this._roomAnchorRes[e]})),t.length&&(yield this.unsubscribe(t),t.forEach((e=>delete this._remoteTracks[e.getTrackId()]))),this._callAppListener("onAnchorLeave",e)}))}_diffRoomResource(e){return S(this,void 0,void 0,(function*(){const t=[],r=[],i=[];e.forEach((e=>{const r=mt(e),{userId:n,tag:s,mediaType:o}=ft(r),a=[this._roomId,s,o].join("_");if(!this._remoteTracks[a]){const r=o===Fe.AUDIO_ONLY?new ot(s,"",this._roomId):new at(s,"",this._roomId);t.push(r),this._remoteTracks[a]=r,this._roomRes[r.getTrackId()]=e}i.push(a)})),Object.keys(this._remoteTracks).forEach((e=>{i.indexOf(e)<0&&this._remoteTracks[e].isMCUTrack()&&r.push(this._remoteTracks[e])})),t.length>0&&this._callAppListener("onTrackPublish",t),r.length>0&&this._onUserUnpublish(r,"onTrackUnpublish")}))}_diffAnchorResource(e,t){return S(this,void 0,void 0,(function*(){const r=this._roomAnchorRes[t]||(this._roomAnchorRes[t]=[]),{publishedList:i,unpublishedList:n,modifiedList:s}=gt(r,e);if(i.length){const e=r.map(mt),t=[],n=[];if(i.forEach((i=>{const s=mt(i),o=e.indexOf(s),{userId:a,tag:c,mediaType:d}=ft(s);o>-1?r[o]=i:r.push(i);let u=this._remoteTracks[s];this._roomRes[s]=i,u?u.isSubscribed()&&t.push(u):(u=d===Fe.AUDIO_ONLY?new ot(c,a):new at(c,a),this._remoteTracks[s]=u,n.push(u)),u.__innerSetRemoteMuted(0===i.state)})),t.length){const e=t.map((e=>e.getTrackId()));C.debug(`resub tracks -> ${JSON.stringify(e)}`);const{code:r}=yield k((()=>this._subscribeHandle(t,!0)));r!==T.SUCCESS&&C.error(`resub tracks failed -> code: ${r}, ids: ${JSON.stringify(e)}`)}this._callAppListener("onAnchorTrackPublish",n)}if(n.length){const e=n.map(mt);for(let t=r.length-1;t>=0;t-=1){const i=r[t];e.includes(mt(i))&&r.splice(t,1)}const t=n.map((e=>{const t=mt(e);return this._remoteTracks[t]}));yield this._onUserUnpublish(t,"onAnchorTrackUnpublish")}if(s.length){const e=r.map(mt);for(let t=0;t<s.length;t++){const i=s[t],n=mt(i),o=e.indexOf(n);r[o].state=i.state;const a=this._remoteTracks[n];a.__innerSetRemoteMuted(0===i.state),a.isAudioTrack()?this._callAppListener("onAudioMuteChange",a):this._callAppListener("onVideoMuteChange",a)}}}))}_onUserUnpublish(e,t){return S(this,void 0,void 0,(function*(){yield this.unsubscribe(e),e.forEach((e=>{this._subscribedList=this._subscribedList.filter((t=>t.track.getTrackId()!==e.getTrackId())),delete this._roomRes[e.getTrackId()],e.__innerDestroy(),delete this._remoteTracks[e.getTrackId()]})),this._callAppListener(t,e)}))}_callAppListener(e,...t){var r;const i=null===(r=this._appListener)||void 0===r?void 0:r[e];if(i)try{i(...t)}catch(e){C.error(e)}}_reTryExchange(){return S(this,void 0,void 0,(function*(){k((()=>S(this,void 0,void 0,(function*(){var e;const{reqBody:t}=yield this._createSubscribeParams(this._subscribedList,{},!0),r=yield this._exchangeHandle(t);if(r.code!==T.SUCCESS)return C.error(`reTryExchange failed: ${r.code}`),{code:r.code};const{sdp:i,resultCode:n}=r.data;if(n!==T.SUCCESS)return C.error(`reTryExchange failed: ${n}`),{code:n};this._pc.clearReTryExchangeTimer();const s=this._subscribedList.filter((e=>e.track.isMCUTrack()));if(s.length>0){const t=s[0].track.getTrackId(),r=null===(e=this._roomRes[t])||void 0===e?void 0:e.msid,n=[this._roomId,"RongCloudRTC"].join("_");i.sdp=i.sdp.replace(new RegExp(r,"g"),n)}const o=yield this._pc.setRemoteAnswer(i.sdp);return o!==T.SUCCESS?{code:o}:void 0}))))}))}_createSubscribeParams(e,t,r){return S(this,void 0,void 0,(function*(){const i=yield this._pc.createOffer(r),n={resolutionInfo:[]},s={min:0,max:0};Object.keys(t).forEach((e=>{const{mediaStream:r,tinyStream:o}=t[e];[r,o].forEach(((t,r)=>{var o;const a=1===r?[e,"tiny"].join("_"):e;i.sdp=null===(o=i.sdp)||void 0===o?void 0:o.replace(new RegExp(t.id,"g"),a);const c=t.getVideoTracks()[0];if(!c)return;const d=0===r,{width:u,height:l,frameRate:h}=d?pt(c):Cr;n.resolutionInfo.push({trackId:c.id,simulcast:d?Mt.NORMAL:Mt.TINY,resolution:`${u}x${l}`});const p=Ge(u,l),_=We(h);s.min+=p.minBitrate*_,s.max+=p.maxBitrate*_}))}));return{reqBody:{sdp:i,switchstream:!1,newVersionFlag:!0,subscribeList:e.map((e=>({simulcast:e.subTiny?Mt.TINY:Mt.NORMAL,resolution:"",uri:this._roomRes[e.track.getTrackId()].uri})))},dynamicBitrate:s,offer:i}}))}_subscribeHandle(e,t=!1){var r;return S(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return{code:T.ROOM_HAS_BEEN_DESTROYED};if(!c("tracks",e,(()=>d(e)&&e.length>0&&e.every((e=>e instanceof st||e.track instanceof st))),!0))return{code:T.PARAMS_ERROR};const i=this._subscribedList.map((e=>Object.assign({},e))),n=e.map((e=>e instanceof st?{track:e}:e));let s=!1;const o=[];return n.forEach((e=>{const t=e.track.getTrackId();o.push(t);const r=i.find((e=>e.track.getTrackId()===t));r&&r.subTiny===e.subTiny||(r?r.subTiny=e.subTiny:i.push(e),s=!0)})),s||t?(null===(r=this._polarisReport)||void 0===r||r.sendR2(zt.SUBSCRIBE,Qt.BEGIN,o),this._updateSubListHandle(i,!0)):{code:T.SUCCESS}}))}_getReqHeaders(){const e=this._context.getCurrentId();return{"App-Key":this._context.getAppkey(),RoomId:e,Token:this._joinResData.token,RoomType:u.LIVE,UserId:e,"Session-Id":this._sessionId}}_exchangeHandle(e){return this._service.broadcastSubscribe(this._getReqHeaders(),e)}_updateSubListHandle(e,t=!1){var r;return S(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return{code:T.ROOM_HAS_BEEN_DESTROYED};if(!c("resources",e,(()=>d(e)&&e.every((e=>e instanceof st||e.track instanceof st))),!0))return{code:T.PARAMS_ERROR};let i=e.map((e=>e instanceof st?{track:e}:Object.assign({},e)));const n={};i=i.filter((e=>{const t=e.track.getTrackId();return!n[t]&&(n[t]=!0)})).map((e=>Object.assign({},e)));const s=this._subscribedList.map((e=>Object.assign({},e)));if(!t){let e=!1;if(i.forEach((t=>{const r=s.findIndex((e=>e.track===t.track));if(-1===r)return void(e=!0);s.splice(r,1)[0].subTiny!==t.subTiny&&(e=!0)})),s.length&&(e=!0),!e)return{code:T.SUCCESS}}this._pc.clearReTryExchangeTimer(),this._pc.updateSubRemoteTracks(i.map((e=>e.track)));const{reqBody:o}=yield this._createSubscribeParams(i,{},!1),a=yield this._exchangeHandle(o);if(s.length){const e=[];s.forEach((t=>{e.push(t.track.getTrackId())})),null===(r=this._pc.reportParser)||void 0===r||r.clearLatestPacketsRecv(e)}if(a.code!==T.SUCCESS)return{code:a.code};const{sdp:u,resultCode:l,message:h,subscribedList:p}=a.data;if(l!==T.SUCCESS)return C.error("change subscribe list failed:",h,l),{code:l};i.forEach((e=>{const{track:t}=e;if(t.isMCUTrack()){const e=this._roomRes[t.getTrackId()].msid,{tag:r,userId:i}=ft(t.getTrackId()),n=[i,r].join("_");u.sdp=u.sdp.replace(new RegExp(e,"g"),n)}}));const _=yield this._pc.setRemoteAnswer(u.sdp);if(_!==T.SUCCESS)return{code:_};const m=null==p?void 0:p.map((e=>`${e.msid}_${e.mediaType}`)),f=i.filter((e=>{if(e.track.isMCUTrack()){const t=this._roomRes[e.track.getTrackId()],r=`${t.msid}_${t.mediaType}`;return m.includes(r)}return null==m?void 0:m.includes(e.track.getTrackId())})),v=null==f?void 0:f.map((e=>`${e.track.getTrackId()}`)),R=i.filter((e=>!(null==v?void 0:v.includes(e.track.getTrackId()))));for(const e in this._remoteTracks){const t=f.some((t=>t.track.getTrackId()===e));this._remoteTracks[e].__innerSetSubscribed(t)}return this._subscribedList.splice(0,this._subscribedList.length,...f),R.length?{code:T.SUCCESS,failedList:R}:{code:T.SUCCESS}}))}_diffCDNUris(e){return S(this,void 0,void 0,(function*(){if(this._CDNUris.url&&!e.url)return this._callAppListener("onCDNInfoDisable"),void(this._CDNUris=e);(!this._CDNUris||!this._CDNUris.url&&e.url)&&this._callAppListener("onCDNInfoEnable",{resolution:`W${e.w}_H${e.h}`,fps:`FPS_${e.fps}`});const t=this._CDNUris.w&&e.w&&this._CDNUris.w!==e.w,r=this._CDNUris.h&&e.h&&this._CDNUris.h!==e.h,i=this._CDNUris.fps&&e.fps&&this._CDNUris.fps!==e.fps;(t||r||i)&&this._callAppListener("onCDNInfoChange",{resolution:`W${e.w}_H${e.h}`,fps:`FPS_${e.fps}`}),this._CDNUris=e}))}_getCDNPlayUrl(e){return S(this,void 0,void 0,(function*(){const{w:t,h:r,fps:i}=e,n=this._initOptions.pullInnerCDNProtocol||gr.FLV,s=this._initOptions.pullInnerCDNUseHttps===Sr.NOT_HTTPS?Sr.NOT_HTTPS:Sr.HTTPS;if(!this._CDNUris.url)return C.error(`cdn_uris url is empty, the anchor need to open or push CDN, code: ${T.CDN_RESOURCE_IS_EMPTY}`),{code:T.CDN_RESOURCE_IS_EMPTY};const o={"App-Key":this._context.getAppkey(),Token:this._joinResData.token,RoomId:this.getRoomId(),UserId:this._context.getCurrentId(),SessionId:this.getSessionId()},a=[];t&&a.push(`w=${t}`),r&&a.push(`h=${r}`),i&&a.push(`fps=${i}`),a.push(`kind=${n}`),a.push(`is_https=${s}`);const c=a.join("&");let d=`${this._CDNUris.url}?`;c&&(d+=c);const{code:u,res:l}=yield this._service.getCDNResourceInfo(o,d);return u!==T.SUCCESS?(C.error(`getCDNPlayUrl failed: ${u}`),{code:u}):(C.info(`getCDNPlayUrl success: ${null==l?void 0:l.data.pull_url}`),{code:u,CDNPlayUrl:null==l?void 0:l.data.pull_url})}))}getCDNPlayUrl(e,t){return S(this,void 0,void 0,(function*(){if(e&&!Tt(e))return C.error("`resolution` is invalid"),{code:T.PARAMS_ERROR};if(t&&!It(t))return C.error("`fps` is invalid"),{code:T.PARAMS_ERROR};const{width:r,height:i}=e?Ct(e):{width:null,height:null},n=t?Et(t):null,s={};return r&&(s.w=r),i&&(s.h=i),n&&(s.fps=n),this._getCDNPlayUrl(s)}))}subscribe(e){return S(this,void 0,void 0,(function*(){return k((()=>this._subscribeHandle(e,!1)))}))}__unsubscribe(e){var t;return S(this,void 0,void 0,(function*(){if(!c("tracks",e,(()=>d(e)&&e.length>0&&e.every((e=>e instanceof st))),!0))return C.error(`unsubscribe failed, tracks is invalid -> roomId: ${this._roomId}`),{code:T.PARAMS_ERROR};const r=this._subscribedList.map((e=>Object.assign({},e))).filter((t=>!e.includes(t.track)));return null===(t=this._polarisReport)||void 0===t||t.sendR2(zt.SUBSCRIBE,Qt.END,e.map((e=>e.getTrackId()))),this._updateSubListHandle(r,!1)}))}unsubscribe(e){return S(this,void 0,void 0,(function*(){return k((()=>this.__unsubscribe(e)))}))}__destroy(e){var t;return S(this,void 0,void 0,(function*(){this._destroyed||(this._destroyed=!0,null===(t=this._audioLevelReport)||void 0===t||t.clearAudioLevelReportTimer(),e&&(yield this._context.quitLivingRoomAsAudience(this._roomId)),yield this._service.broadcastExit(this._getReqHeaders()),this._pc.destroy(),this._polarisReport=null,this._context.onrtcdatachange=()=>{})}))}getRemoteTrack(e){return this._remoteTracks[e]}__getPC(){return this._pc}getLocalTrack(e){return{}}__onReconnected(){return S(this,void 0,void 0,(function*(){const{code:e}=yield this._context.joinLivingRoomAsAudience(this._roomId,u.LIVE);e!==i.SUCCESS&&C.error("join living room error when on reconnected")}))}registerRoomEventListener(e){this._appListener=e}onAudioLevelChange(e,t){var r;null===(r=this._audioLevelReport)||void 0===r||r.clearAudioLevelReportTimer(),this._audioLevelReport=new er(this),this._audioLevelReport.onAudioLevelChange(e,t||1e3)}registerReportListener(e){var t;null===(t=this._pc)||void 0===t||t.registerReportListener(e)}getRoomId(){return this._roomId}getCrtUserId(){return this._context.getCurrentId()}getSessionId(){return this._sessionId}getRemoteUserIds(){return this._roomAnchorList}getRemoteTracksByUserId(e){const t=[];for(const r in this._remoteTracks){const i=this._remoteTracks[r];i.getUserId()===e&&t.push(i)}return t}getRemoteTracks(){const e=[],t=[];for(const e in this._remoteTracks){if(2===t.length)break;const r=this._remoteTracks[e];r.isMCUTrack()&&t.push(r)}return this._roomAnchorList.forEach((t=>{e.push(...this.getRemoteTracksByUserId(t))})),[...t,...e]}getRemoteRTCTracks(){const e=[];for(const t in this._remoteTracks){const r=this._remoteTracks[t];r.isMCUTrack()||e.push(r)}return e}getRemoteMCUTracks(){const e=[];for(const t in this._remoteTracks){const r=this._remoteTracks[t];r.isMCUTrack()&&e.push(r)}return e}getCDNInfo(){return this._CDNUris.w?{resolution:`W${this._CDNUris.w}_H${this._CDNUris.h}`,fps:`FPS_${this._CDNUris.fps}`,CDNEnable:this._CDNUris.enableInnerCDN}:{CDNEnable:!1}}}const Ir=(e,t)=>{const r=[];return r[0]=(null==t?void 0:t.withoutAudio)?void 0:e.getAudioTracks()[0],r[1]=(null==t?void 0:t.withoutVideo)?void 0:e.getVideoTracks()[0],r};class Er{constructor(e,t,r){this._context=e,this._runtime=t,this._options=r,this._crtRoom=null,this._audience=null,this._crtAudienceLivingRoom=null,Kt.setSdpSemantics(r.sdpSemantics||"plan-b"),this._service=new vr(this._runtime,this._context,this._options.mediaServer,this._options.timeout),this._context.onconnectionstatechange=this._onIMStatusChange.bind(this),this._context.ondisconnect=this._onIMDisconnect.bind(this),this._context.ondestroy=this._onIMUninit.bind(this),this._context.onmessage=this._handleMessage.bind(this)}_handleMessage(e){var t;if(e.conversationType!==o.RTC_ROOM)return!1;if(this._crtRoom instanceof _r){this._getJoinedPKRoomList().forEach((t=>{t.__parseInnerMessage(e)}))}return null===(t=this._crtRoom)||void 0===t||t.__parseInnerMessage(e),!0}_getJoinedPKRoomList(){const{code:e,roomPKHandler:t}=this._crtRoom.getRoomPKHandler();if(e===T.SUCCESS&&t){const e=t.getJoinedPKRooms()||{};return Object.values(e)}return[]}getCurrentId(){return this._context.getCurrentId()}joinRTCRoom(e,t){return k((()=>this._joinRTCRoom(e,t)))}_joinRTCRoom(e,t){return S(this,void 0,void 0,(function*(){if(Ot(this._context.getNaviInfo()))return{code:T.PACKAGE_ENVIRONMENT_ERROR};if(!c("roomId",e,h,!0))return{code:T.PARAMS_ERROR};if(this._crtRoom)return{code:T.REPERT_JOIN_ROOM};if(this._context.getConnectionStatus()!==n.CONNECTED)return{code:T.SIGNAL_DISCONNECTED};if(!this._service.getNaviMS().length)return{code:T.NOT_OPEN_VIDEO_AUDIO_SERVER};C.debug(`joinRoom -> roomId: ${e}; joinType: ${t||v.KICK}`);const{code:r,data:s}=yield this._context.joinRTCRoom(e,u.RTC,void 0,t);if(r!==i.SUCCESS){C.error(`joinRoom failed -> code: ${r}`);return{code:r===I.JOIN_REFUSED?T.SIGNAL_JOIN_RTC_ROOM_REFUSED:r}}C.debug(`joinRoom success -> userId: ${this._context.getCurrentId()}, roomId: ${e}, data: ${JSON.stringify(s)}`);const o=new mr(this._context,this._runtime,e,s,this._service,this._options,this._releaseCrtRoomObj.bind(this));return this._crtRoom=o,{room:o,code:T.SUCCESS,userIds:o.getRemoteUserIds(),tracks:o.getRemoteTracks()}}))}joinLivingRoom(e,t){return k((()=>this._joinLivingRoom(e,t)))}_joinLivingRoom(e,t){return S(this,void 0,void 0,(function*(){if(Ot(this._context.getNaviInfo()))return{code:T.PACKAGE_ENVIRONMENT_ERROR};if(!c("roomId",e,h,!0)||!c("livingType",t,(e=>e===lr.AUDIO||e===lr.VIDEO)))return{code:T.PARAMS_ERROR};if(this._crtRoom)return{code:T.REPERT_JOIN_ROOM};if(this._context.getConnectionStatus()!==n.CONNECTED)return{code:T.SIGNAL_DISCONNECTED};if(!this._service.getNaviMS().length)return{code:T.NOT_OPEN_VIDEO_AUDIO_SERVER};C.debug(`joinRoom, roomId: ${e}`);const{code:r,data:s}=yield this._context.joinRTCRoom(e,u.LIVE,t);if(r!==i.SUCCESS)return C.error(`joinRoom failed -> code: ${r}`),{code:r};C.debug(`JoinRoom success -> userId: ${this._context.getCurrentId()}, roomId: ${e}, data: ${JSON.stringify(s)}`);const o=new _r(this._context,this._runtime,e,s,this._service,this._options,this._releaseCrtRoomObj.bind(this),t,!1,!0);this._crtRoom=o;const a={room:o,code:T.SUCCESS,userIds:o.getRemoteUserIds(),tracks:o.getRemoteTracks()};return o.__getCDNPushMode()===ur.MANUAL&&Object.assign(a,{CDNEnable:o.__getCDNEnable()}),a}))}getAudienceClient(){return this._audience||(this._audience=new Rr(this._context,this._runtime,this._options)),this._audience}_onIMStatusChange(e){if(C.debug(`signal server connection state change: ${e}`),e===n.CONNECTED){if(this._crtRoom instanceof _r){this._getJoinedPKRoomList().forEach((e=>{e.__onReconnected()}))}this._crtRoom&&this._crtRoom.__onReconnected()}}_onIMDisconnect(){C.debug("TODO -> on IM disconnect")}_onIMUninit(){C.debug("TODO -> on IM client ondestroy")}leaveRoom(e){return k((()=>this._leaveRoom(e)))}_leaveRoom(e){return S(this,void 0,void 0,(function*(){return this._crtRoom?(yield this._crtRoom.__destroy(!0),C.debug(`quitRTCRoom -> userId: ${this._context.getCurrentId()} , roomId: ${this._crtRoom.getRoomId()}`),this._crtRoom=null,{code:T.SUCCESS}):{code:T.SUCCESS}}))}_releaseCrtRoomObj(){this._crtRoom=null}_getMediaStream(e,t="getUserMedia"){return S(this,void 0,void 0,(function*(){try{const r=yield navigator.mediaDevices[t](e);return{code:T.SUCCESS,stream:r}}catch(e){if("Permission denied"===e.message)return{code:T.PERMISSION_DENIED};C.error(`get user media failed -> ${e.message}`)}return{code:"getUserMedia"===t?T.GET_USER_MEDIA_FAILED:T.GET_DISPLAY_MEDIA_FAILED}}))}createMicrophoneAudioTrack(e="RongCloudRTC",t){return S(this,void 0,void 0,(function*(){if(!ut(e))return{code:T.INVALID_TAGS};const r=this._context.getCurrentId();if(!r)return{code:T.INVALID_USER_ID};const{stream:i,code:n}=yield this._getMediaStream({audio:{deviceId:null==t?void 0:t.micphoneId,sampleRate:null==t?void 0:t.sampleRate}});if(n!==T.SUCCESS)return{code:n};const s=i.getAudioTracks()[0];return{code:n,track:new rt(e,r,s)}}))}createCameraVideoTrack(e="RongCloudRTC",t){return S(this,void 0,void 0,(function*(){if(!ut(e))return{code:T.INVALID_TAGS};const r=this._context.getCurrentId();if(!r)return{code:T.INVALID_USER_ID};const i=Tt(null==t?void 0:t.resolution)?t.resolution:He.W640_H480,{width:n,height:s}=Ct(i),{stream:o,code:a}=yield this._getMediaStream({video:{deviceId:null==t?void 0:t.cameraId,frameRate:Et((null==t?void 0:t.frameRate)||Be.FPS_15),width:n,height:s,facingMode:null==t?void 0:t.faceMode}});if(a!==T.SUCCESS)return{code:a};const c=o.getVideoTracks()[0];return{code:a,track:new it(e,r,c)}}))}createMicrophoneAndCameraTracks(e="RongCloudRTC",t){var r,i,n,s,o,a;return S(this,void 0,void 0,(function*(){const c=[];if(!ut(e))return{code:T.INVALID_TAGS,tracks:c};const d=this._context.getCurrentId();if(!d)return{code:T.INVALID_USER_ID,tracks:c};const u=Tt(null===(r=null==t?void 0:t.video)||void 0===r?void 0:r.resolution)?t.video.resolution:He.W640_H480,{width:l,height:h}=Ct(u),{stream:p,code:_}=yield this._getMediaStream({video:{deviceId:null===(i=null==t?void 0:t.video)||void 0===i?void 0:i.cameraId,frameRate:Et((null===(n=null==t?void 0:t.video)||void 0===n?void 0:n.frameRate)||Be.FPS_15),width:l,height:h,facingMode:null===(s=null==t?void 0:t.video)||void 0===s?void 0:s.faceMode},audio:{deviceId:null===(o=null==t?void 0:t.audio)||void 0===o?void 0:o.micphoneId,sampleRate:null===(a=null==t?void 0:t.audio)||void 0===a?void 0:a.sampleRate}});return _!==T.SUCCESS||p.getTracks().forEach((t=>{"video"===t.kind?c.push(new it(e,d,t)):c.unshift(new rt(e,d,t))})),{code:_,tracks:c}}))}createScreenVideoTrack(e="screenshare",t){return S(this,void 0,void 0,(function*(){if(!ut(e))return{code:T.INVALID_TAGS};const r=this._context.getCurrentId();if(!r)return{code:T.INVALID_USER_ID};if(!bt())return{code:T.BROWSER_NOT_SUPPORT};const i=/Electron/.test(navigator.userAgent);if(i&&!(null==t?void 0:t.chromeMediaSourceId))return{code:T.PARAMS_ERROR};const n=Tt(null==t?void 0:t.resolution)?t.resolution:He.W1280_H720,{width:s,height:o}=Ct(n),a=i?{mandatory:{chromeMediaSourceId:t.chromeMediaSourceId,chromeMediaSource:"desktop",minWidth:s,maxWidth:s,minHeight:o,maxHeight:o}}:{frameRate:Et((null==t?void 0:t.frameRate)||Be.FPS_15),width:s,height:o},{stream:c,code:d}=yield this._getMediaStream({video:a,audio:!1},i?"getUserMedia":"getDisplayMedia");if(d!==T.SUCCESS)return{code:d};const u=c.getVideoTracks()[0];return{code:d,track:new nt(e,r,u)}}))}createLocalAudioTrack(e,t){return S(this,void 0,void 0,(function*(){if(!ut(e))return{code:T.INVALID_TAGS};if(!t||"[object MediaStreamTrack]"!==t.toString()||"audio"!==t.kind)return{code:T.CREATE_CUSTOM_TRACK_FAILED};const r=this._context.getCurrentId();return r?{code:T.SUCCESS,track:new Qe(e,r,t)}:{code:T.INVALID_USER_ID}}))}createLocalVideoTrack(e,t){return S(this,void 0,void 0,(function*(){if(!ut(e))return{code:T.INVALID_TAGS};if(!t||"[object MediaStreamTrack]"!==t.toString()||"video"!==t.kind)return{code:T.CREATE_CUSTOM_TRACK_FAILED};const r=this._context.getCurrentId();return r?{code:T.SUCCESS,track:new Xe(e,r,t)}:{code:T.INVALID_USER_ID}}))}createLocalFileTracks(e,t,r){return S(this,void 0,void 0,(function*(){if(!ut(e))return{code:T.INVALID_TAGS,tracks:[]};if(!kt())return{code:T.BROWSER_NOT_SUPPORT,tracks:[]};const i=t instanceof File?URL.createObjectURL(t):t;if(!l(i)&&!/^blob:/.test(i))return C.warn(`createLocalFileTracks failed: params error -> url: ${i}`),{code:T.PARAMS_ERROR,tracks:[]};const n=this._context.getCurrentId();return n?new Promise((t=>{const s=document.createElement("video");(null==r?void 0:r.withoutAudio)&&(s.muted=!0),s.onloadedmetadata=()=>{const o=[];let a;try{const e=s.mozCaptureStream?"mozCaptureStream":"captureStream";a=s[e]()}catch(e){C.error(`create RCLocalFileTrack failed, captureSteam error. -> url: ${i}`),C.error(e),t({code:T.CREATE_FILE_TRACK_FAILED,tracks:o})}const[c,d]=Ir(a,r);c&&o.push(new tt(e,n,c,s)),d&&o.push(new et(e,n,d,s)),0===o.length&&(s.pause(),s.src=""),s.onerror=null,t({code:T.SUCCESS,tracks:o})},s.onerror=()=>{C.error(`create RCLocalFileTrack failed -> url: ${i}`),t({code:T.CREATE_FILE_TRACK_FAILED,tracks:[]})},s.src=i,s.loop=!0,s.play()})):{code:T.INVALID_USER_ID,tracks:[]}}))}createLocalTracks(e,t,r){return S(this,void 0,void 0,(function*(){const i=[];if(!ut(e))return{code:T.INVALID_TAGS,tracks:i};if(!(t instanceof MediaStream))return{code:T.PARAMS_ERROR,tracks:i};const n=this._context.getCurrentId();if(!n)return{code:T.INVALID_USER_ID,tracks:i};const[s,o]=Ir(t,r);return s&&i.push(new Qe(e,n,s)),o&&i.push(new Xe(e,n,o)),{code:T.SUCCESS,tracks:i}}))}joinLivingRoomAsAudience(e,t){return S(this,void 0,void 0,(function*(){if(Ot(this._context.getNaviInfo()))return{code:T.PACKAGE_ENVIRONMENT_ERROR};if(!c("roomId",e,h,!0)||!c("livingType",t,(e=>e===lr.AUDIO||e===lr.VIDEO)))return{code:T.PARAMS_ERROR};if(this._crtAudienceLivingRoom)return{code:T.REPERT_JOIN_ROOM};if(!this._service.getNaviMS().length)return{code:T.NOT_OPEN_VIDEO_AUDIO_SERVER};const{code:r,data:n}=yield this._context.joinLivingRoomAsAudience(e,u.LIVE,t);if(r!==i.SUCCESS)return C.error("audienceJoinLivingRoomError:",r),{code:T.SIGNAL_AUDIENCE_JOIN_ROOM_FAILED};C.info(`joinLivingRoomAsAudience success, room data: ${JSON.stringify(n)}`);const s=new Tr(this._context,this._runtime,this._options,e,n,t);return this._crtAudienceLivingRoom=s,{room:s,code:T.SUCCESS,userIds:s.getRemoteUserIds(),RTCTracks:s.getRemoteRTCTracks(),MCUTracks:s.getRemoteMCUTracks(),CDNUris:s.getCDNInfo()}}))}leaveLivingRoomAsAudience(e){return S(this,void 0,void 0,(function*(){return this._crtAudienceLivingRoom?this._crtAudienceLivingRoom!==e?{code:T.PARAMS_ERROR}:(yield this._crtAudienceLivingRoom.__destroy(!0),this._crtAudienceLivingRoom=null,{code:T.SUCCESS}):{code:T.SUCCESS}}))}upgradeToAnchorRoom(e){return S(this,void 0,void 0,(function*(){if(!c("room._roomId",e._roomId,h,!0))return{code:T.PARAMS_ERROR};if(this._crtRoom)return{code:T.REPERT_JOIN_ROOM};const{code:t,data:r}=yield this._context.rtcIdentityChange(e._roomId,R.ViewerToAnchor,e._livingType);if(t!==i.SUCCESS)return C.error("change room identity error",t),{code:T.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED};yield this._crtAudienceLivingRoom.__destroy(!1);const n=new _r(this._context,this._runtime,e._roomId,r,this._service,this._options,this._releaseCrtRoomObj.bind(this),e._livingType,!0,!0);return this._crtRoom=n,this._crtAudienceLivingRoom=null,{room:n,code:T.SUCCESS,userIds:e.getRemoteUserIds(),tracks:n.getRemoteTracks()}}))}downgradeToAudienceRoom(e){return S(this,void 0,void 0,(function*(){if(!c("room._roomId",e._roomId,h,!0))return{code:T.PARAMS_ERROR};if(this._crtAudienceLivingRoom)return{code:T.REPERT_JOIN_ROOM};const{code:t,data:r}=yield this._context.rtcIdentityChange(e._roomId,R.AnchorToViewer,e.getLivingType());if(t!==i.SUCCESS)return C.error("change room identity error",t),{code:T.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED};C.info(`downgradeToAudienceRoom success, room data: ${JSON.stringify(r)}`);const n=new Tr(this._context,this._runtime,this._options,e._roomId,r,e.getLivingType());return this._crtAudienceLivingRoom=n,this._crtRoom.__destroy(!1),this._crtRoom=null,{room:n,code:T.SUCCESS,userIds:n.getRemoteUserIds(),RTCTracks:n.getRemoteRTCTracks(),MCUTracks:n.getRemoteMCUTracks(),CDNUris:n.getCDNInfo()}}))}getJoinedRoomInfo(){return S(this,void 0,void 0,(function*(){const{code:e,data:t}=yield this._context.getRTCJoinedUserInfo(this._context.getCurrentId());return e!==i.SUCCESS?(C.error("getJoinedUserInfo error",e),{code:T.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED}):{code:T.SUCCESS,data:t}}))}}var yr;!function(e){e[e.SERVER_KICK=1]="SERVER_KICK",e[e.OTHER_KICK=2]="OTHER_KICK"}(yr||(yr={}));const kr={tag:"RCRTC",verify:e=>"browser"!==e.tag?(C.error(`RCRTC Plugin is not support the runtime '${e.tag}'`),!1):lt?(g.add("plugin-rtc","5.3.1"),!!g.validEngine("5.1.0")||(C.error(`The current engine version '${g.getInfo().engine}' error, plugin-rtc required engine version at least '5.1.0'.`),!1)):(C.error("Please use the https protocol or use `http://localhost` to open the page!"),!1),setup:(e,t,i={})=>(C.setLogLevel(i.logLevel),C.setLogStdout(i.logStdout),C.warn("RCRTC Version: 5.3.1, Commit: e1af0f5ccb06a0084c94e1219d8af54c9793c06b"),C.warn(`browserInfo.browser -> ${yt.browser}`),C.warn(`browserInfo.supportsUnifiedPlan -> ${yt.supportsUnifiedPlan}`),C.warn(`browserInfo.version -> ${yt.version}`),s("options.mediaServer",i.mediaServer,(e=>!(!l(e)||"https:"===location.protocol&&!/^https/.test(e)))),s("options.timeout",i.timeout,(e=>r(e)&&e>=5e3&&e<=3e4)),s("options.pingGap",i.pingGap,(e=>r(e)&&e>=3e3&&e<=1e4)),new Er(e,t,i))},br={DEFAULT:"RongCloudRTC"},Pr={transResolution:Ct,transFrameRate:Et,parseTrackId:ft,ifSupportLocalFileTrack:kt,ifSupportScreenShare:bt};export{ir as BackgroundPictureFillMode,nr as MixLayoutMode,sr as MixVideoRenderMode,rr as RCAbstractRoom,Rr as RCAudienceClient,Tr as RCAudienceLivingRoom,it as RCCameraVideoTrack,Be as RCFrameRate,Sr as RCInnerCDNPullIsHttps,gr as RCInnerCDNPullKind,yr as RCKickReason,_r as RCLivingRoom,lr as RCLivingType,Qe as RCLocalAudioTrack,tt as RCLocalFileAudioTrack,Ze as RCLocalFileTrack,et as RCLocalFileVideoTrack,ze as RCLocalTrack,Xe as RCLocalVideoTrack,ar as RCMCUConfigBuilder,Fe as RCMediaType,rt as RCMicphoneAudioTrack,Er as RCRTCClient,T as RCRTCCode,Xt as RCRTCLiveRole,Dt as RCRTCPingResult,mr as RCRTCRoom,ot as RCRemoteAudioTrack,st as RCRemoteTrack,at as RCRemoteVideoTrack,He as RCResolution,nt as RCScreenVideoTrack,br as RCTag,qe as RCTrack,Ye as device,Pr as helper,kr as installer};