@byteplus/vepusher 1.1.1-rc.0 → 2.0.1-rc.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.
@@ -0,0 +1,93 @@
1
+ (function($,I){typeof exports=="object"&&typeof module<"u"?module.exports=I():typeof define=="function"&&define.amd?define(I):($=typeof globalThis<"u"?globalThis:$||self,$["ve-pusher"]=I())})(this,function(){"use strict";var ah=Object.defineProperty;var ch=($,I,Z)=>I in $?ah($,I,{enumerable:!0,configurable:!0,writable:!0,value:Z}):$[I]=Z;var m=($,I,Z)=>ch($,typeof I!="symbol"?I+"":I,Z);var ys,Ss,Ts,Es,bs,ks;function $(r,e){for(var t=0;t<e.length;t++){const i=e[t];if(typeof i!="string"&&!Array.isArray(i)){for(const s in i)if(s!=="default"&&!(s in r)){const n=Object.getOwnPropertyDescriptor(i,s);n&&Object.defineProperty(r,s,n.get?n:{enumerable:!0,get:()=>i[s]})}}}return Object.freeze(Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}))}function I(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Z={exports:{}},er;function Ys(){return er||(er=1,function(r){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(t=!1));function s(u,c,d){this.fn=u,this.context=c,this.once=d||!1}function n(u,c,d,h,p){if(typeof d!="function")throw new TypeError("The listener must be a function");var l=new s(d,h||u,p),f=t?t+c:c;return u._events[f]?u._events[f].fn?u._events[f]=[u._events[f],l]:u._events[f].push(l):(u._events[f]=l,u._eventsCount++),u}function a(u,c){--u._eventsCount===0?u._events=new i:delete u._events[c]}function o(){this._events=new i,this._eventsCount=0}o.prototype.eventNames=function(){var c=[],d,h;if(this._eventsCount===0)return c;for(h in d=this._events)e.call(d,h)&&c.push(t?h.slice(1):h);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(d)):c},o.prototype.listeners=function(c){var d=t?t+c:c,h=this._events[d];if(!h)return[];if(h.fn)return[h.fn];for(var p=0,l=h.length,f=new Array(l);p<l;p++)f[p]=h[p].fn;return f},o.prototype.listenerCount=function(c){var d=t?t+c:c,h=this._events[d];return h?h.fn?1:h.length:0},o.prototype.emit=function(c,d,h,p,l,f){var g=t?t+c:c;if(!this._events[g])return!1;var _=this._events[g],T=arguments.length,b,v;if(_.fn){switch(_.once&&this.removeListener(c,_.fn,void 0,!0),T){case 1:return _.fn.call(_.context),!0;case 2:return _.fn.call(_.context,d),!0;case 3:return _.fn.call(_.context,d,h),!0;case 4:return _.fn.call(_.context,d,h,p),!0;case 5:return _.fn.call(_.context,d,h,p,l),!0;case 6:return _.fn.call(_.context,d,h,p,l,f),!0}for(v=1,b=new Array(T-1);v<T;v++)b[v-1]=arguments[v];_.fn.apply(_.context,b)}else{var j=_.length,R;for(v=0;v<j;v++)switch(_[v].once&&this.removeListener(c,_[v].fn,void 0,!0),T){case 1:_[v].fn.call(_[v].context);break;case 2:_[v].fn.call(_[v].context,d);break;case 3:_[v].fn.call(_[v].context,d,h);break;case 4:_[v].fn.call(_[v].context,d,h,p);break;default:if(!b)for(R=1,b=new Array(T-1);R<T;R++)b[R-1]=arguments[R];_[v].fn.apply(_[v].context,b)}}return!0},o.prototype.on=function(c,d,h){return n(this,c,d,h,!1)},o.prototype.once=function(c,d,h){return n(this,c,d,h,!0)},o.prototype.removeListener=function(c,d,h,p){var l=t?t+c:c;if(!this._events[l])return this;if(!d)return a(this,l),this;var f=this._events[l];if(f.fn)f.fn===d&&(!p||f.once)&&(!h||f.context===h)&&a(this,l);else{for(var g=0,_=[],T=f.length;g<T;g++)(f[g].fn!==d||p&&!f[g].once||h&&f[g].context!==h)&&_.push(f[g]);_.length?this._events[l]=_.length===1?_[0]:_:a(this,l)}return this},o.prototype.removeAllListeners=function(c){var d;return c?(d=t?t+c:c,this._events[d]&&a(this,d)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,r.exports=o}(Z)),Z.exports}var Zs=Ys();const Q=I(Zs);var S=(r=>(r.Camera="camera",r.Screen="screen",r.VideoFile="videoFile",r.Microphone="microphone",r.AudioFile="audioFile",r.Image="image",r.MixAudio="mixAudio",r.MixVideo="mixVideo",r.CustomVideo="customVideo",r.CustomAudio="customAudio",r))(S||{}),z=(r=>(r.DeviceCaptured="deviceCaptured",r.DeviceStopCapture="deviceStopCapture",r.Error="error",r.Interrupted="interrupted",r))(z||{}),A=(r=>(r.PushStart="pushStart",r.PushStop="pushStop",r.PushError="pushError",r.RTCConnectStateChanged="rtcConnectStateChanged",r.CaptureFirstVideoFrame="capturefirstvideoframe",r.CaptureFirstAudioFrame="capturefirstaudioframe",r.NotAllowedAutoPlay="notallowedautoplay",r))(A||{}),tr=(r=>(r["120p"]="160x120x15x200",r["180p"]="320x180x15x350",r["240p"]="320x240x15x400",r["360p"]="640x360x15x800",r["480p"]="640x480x15x900",r["720p-1"]="1280x720x15x1500",r["720p-2"]="1280x720x25x1500",r["720p-3"]="1280x720x30x1500",r["1080p-1"]="1920x1080x15x2080",r["1080p-2"]="1920x1080x25x3000",r["1080p-3"]="1920x1080x30x3150",r))(tr||{}),rr=(r=>(r["120p"]="120x160x15x200",r["180p"]="180x320x15x350",r["240p"]="240x320x15x400",r["360p"]="360x640x15x800",r["480p"]="480x640x15x900",r["720p-1"]="720x1280x15x1500",r["720p-2"]="720x1280x25x1500",r["720p-3"]="720x1280x30x1500",r["1080p-1"]="1080x1920x15x2080",r["1080p-2"]="1080x1920x25x3000",r["1080p-3"]="1080x1920x30x3150",r))(rr||{}),ir=(r=>(r.STANDARD="48000x40",r.HIGH="48000x128",r))(ir||{}),ne=(r=>(r.VideoStreamChange="videoStreamChange",r.AudioStreamChange="audioStreamChange",r))(ne||{}),sr=(r=>(r[r.init=-1]="init",r[r.new=0]="new",r[r.connecting=1]="connecting",r[r.connected=2]="connected",r[r.disconnected=3]="disconnected",r[r.failed=4]="failed",r[r.closed=5]="closed",r))(sr||{}),rt=(r=>(r.SizeChange="sizeChange",r))(rt||{}),it=(r=>(r.Portrait="portrait",r.Landscape="landscape",r))(it||{});const nr="720p-1",or="STANDARD";var y=(r=>(r.TRACK_NOT_AVAILABLE="track-not-available",r.UNEXPECTED_TYPE="unexpected-type",r.PLAY_FAILED="play-failed",r.CAPTURE_FAILED="capture-failed",r.NOT_SUPPORTED="not-supported",r.UNEXPECTED_ERROR="unexpected-error",r))(y||{}),E=(r=>(r.AUDIO="audio",r.VIDEO="video",r))(E||{}),M=(r=>(r.ENDED="ended",r.MUTE="mute",r.UNMUTE="unmute",r.PLAY_FAILED="play-failed",r.SIZE_CHANGE="size-change",r))(M||{});const O=[];for(let r=0;r<256;++r)O.push((r+256).toString(16).slice(1));function Qs(r,e=0){return(O[r[e+0]]+O[r[e+1]]+O[r[e+2]]+O[r[e+3]]+"-"+O[r[e+4]]+O[r[e+5]]+"-"+O[r[e+6]]+O[r[e+7]]+"-"+O[r[e+8]]+O[r[e+9]]+"-"+O[r[e+10]]+O[r[e+11]]+O[r[e+12]]+O[r[e+13]]+O[r[e+14]]+O[r[e+15]]).toLowerCase()}let st;const en=new Uint8Array(16);function tn(){if(!st){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");st=crypto.getRandomValues.bind(crypto)}return st(en)}const ar={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function oe(r,e,t){var s;if(ar.randomUUID&&!r)return ar.randomUUID();r=r||{};const i=r.random??((s=r.rng)==null?void 0:s.call(r))??tn();if(i.length<16)throw new Error("Random bytes length must be >= 16");return i[6]=i[6]&15|64,i[8]=i[8]&63|128,Qs(i)}class cr{constructor(){m(this,"id",oe());m(this,"_nextNode");m(this,"_track");m(this,"_destNode")}gain(e){if(this._nextNode instanceof dr)return this._nextNode.g=e,this._nextNode;const t=new dr(this,{g:e});return this._nextNode=t,t}connect(e,t){if(!this.available())return;let{_node:i}=this;i||(i=this.createNode(e)),this._node=i,this.previousNode&&this.previousNode.connect(e,i),t&&i.connect(t)}available(){var e;return((e=this.previousNode)==null?void 0:e.available())??!1}destroy(){var e;(e=this._node)==null||e.disconnect(),delete this._node}}class dr extends cr{constructor(t,i){super();m(this,"previousNode");m(this,"_node");m(this,"_g");this.previousNode=t,this._g=i.g}createNode(t){return new GainNode(t,{gain:this._g})}set g(t){this._g=t,this._node&&(this._node.gain.value=t)}}class rn extends cr{constructor(t){super();m(this,"previousNode",null);m(this,"source");this.source=t}available(){return this.source.available()}destroy(){super.destroy()}}class sn extends rn{constructor(){super(...arguments);m(this,"_node")}createNode(t){if(this._node)return this._node;let i;if(this.source instanceof gr){const s=this.source.element();i=new MediaElementAudioSourceNode(t,{mediaElement:s}),s.muted=!1}else{const s=this.source.track();i=new MediaStreamAudioSourceNode(t,{mediaStream:new MediaStream([s])})}return i}}class C extends Error{constructor(t,i,s){super(i);m(this,"code");m(this,"message");m(this,"error");this.code=t,this.message=i,this.error=s,Object.setPrototypeOf(this,C.prototype)}toString(){return`VeCapture Error: ${this.code} ${this.message}`}}const ur={info:{color:"rgba(93, 173, 226, 0)",text:"INFO"},warn:{color:"rgba(255, 119, 0, 0.3)",text:"WARN"},err:{color:"rgba(255, 0, 0, 0.3)",text:"ERR "},succ:{color:"rgba(0, 119, 0, 0.3)",text:"SUCC"}},hr="__debug__",nn="[VE-CAPTURE]";function on(){if(typeof location>"u"||typeof localStorage>"u")return!1;let r=!1;return location.href.includes(hr)&&(r=!0),localStorage.getItem(hr)&&(r=!0),r}let L=class{constructor(e){m(this,"moduleName");this.moduleName=e}print(e,t,...i){const s=an();on()&&console.log(`${s}-${nn}%c[${ur[e].text}]%c[${this.moduleName}][${t}]`,`background-color:${ur[e].color};`,"background-color:rgba(0, 0, 0, 0)",...i)}info(e,...t){this.print("info",e,...t)}warn(e,...t){this.print("warn",e,...t)}error(e,...t){this.print("err",e,...t)}success(e,...t){this.print("succ",e,...t)}invoke(e,t){const i=this;return function(...n){i.info(`${t}-invoke`,...n);try{const a=e(...n);return typeof(a==null?void 0:a.then)=="function"?a.then(o=>(i.success(`${t}-result`,o),o)).catch(o=>{throw i.error(`${t}-result`,o),o}):(i.success(`${t}-result`,a),a)}catch(a){i.error(`[${t}-result`,a)}}}};function an(){const r=new Date;return`${r.toTimeString().split(" ")[0]}:${r.getMilliseconds().toString().padStart(3,"0")}`}function nt(r,e){const t=document.createElement(r);return e.id&&(t.id=e.id),e.classList&&e.classList.forEach(i=>{t.classList.add(i)}),e.style&&Object.assign(t.style,e.style),e.attributes&&Object.entries(e.attributes).forEach(([i,s])=>{i==="muted"&&(t instanceof HTMLVideoElement||t instanceof HTMLAudioElement)?t.muted=!0:t.setAttribute(i,s)}),t}function pr({width:r,height:e}){const t=document.createElement("canvas"),i=t.getContext("2d");if(!i)throw new C(y.NOT_SUPPORTED,"CanvasRenderingContext2D is not supported by user agent");return t.width=r,t.height=e,t.style.width="100%",t.style.height="100%",{context:i,canvas:t}}class ot{constructor(e){m(this,"target");m(this,"_eventDict",new Map);this.target=e}on(e,t){let i=this._eventDict.get(e);i||(i=[t]),this._eventDict.set(e,i),this.target.addEventListener(e,t)}off(e,t){let i=this._eventDict.get(e);i&&(i=i.filter(s=>s!==t),this._eventDict.set(e,i),this.target.removeEventListener(e,t))}once(e,t){const i=s=>{t(s),this.off(e,i)};this.on(e,i)}clear(e){const t=this._eventDict.get(e);t&&t.forEach(i=>{this.target.removeEventListener(e,i)})}clearAll(){for(const e of this._eventDict.keys())this.clear(e)}}const x=()=>typeof window>"u";function P(){return navigator.userAgent.toLowerCase()}function at(r=P()){let e="none";return x()||(r.match("firefox")!==null?e="firefox":r.match("Chrome")!==null?(e="chrome",r.match("Electron")!==null&&(e="electron")):(r.match("Safari")!==null||r.match("AppleWebKit")!==null)&&(e="safari")),e}const cn=at()==="firefox",ct=at()==="safari";at(),!x()&&/crios/i.test(P()),!x()&&/edg\//i.test(P()),!x()&&/edgA/i.test(P()),!x()&&/edgios/i.test(P()),!x()&&/dingtalk/i.test(P()),!x()&&/opr\//.test(P()),!x()&&/(iphone|ipod)/i.exec(P()),!x()&&(/(ipad)/i.exec(P())||/macintosh/i.test(P())&&"ontouchend"in document),!x()&&/macintosh/i.test(P()),!x()&&/micromessenger/i.test(P()),!x()&&P().includes("mobile"),!x()&&/sm-\w+/i.test(P()),!x()&&/(iphone|ipad|ipod)/i.exec(P()),!x()&&/android/i.test(P()),!x()&&/windows/i.test(P()),!x()&&/openharmony/i.test(P());let lr="0";const dn=!x()&&((ys=P().match(/version\/(\d+)/i))==null?void 0:ys[1]);ct&&dn&&(lr=(Ss=navigator.userAgent.match(/version\/(\d+\.\d+)/i))==null?void 0:Ss[1]),!x()&&((Ts=P().match(/firefox\/(\d+)/i))==null||Ts[1]);const dt=lr;!x()&&((bs=(Es=P().match(/ ([\d_]+) like mac os x/i))==null?void 0:Es[1])==null||bs.split("_").map(r=>parseInt(r))),!x()&&((ks=P().match(/chrome\/(\d+)/i))==null||ks[1]);function un(){var r;return!!((r=navigator==null?void 0:navigator.permissions)!=null&&r.query)}function ut(){return!!(navigator!=null&&navigator.mediaDevices)}function hn(){var r;return ut()&&!!((r=navigator==null?void 0:navigator.mediaDevices)!=null&&r.getUserMedia)}function pn(){return!!Promise.withResolvers}function ln(){return!(ct&&dt==="16.1")}function mn(){return!(ct&&dt&&["16.1","16.2","16.3"].includes(dt))}function fn(){return!cn}function _n(){return typeof CanvasCaptureMediaStreamTrack<"u"}function gn(r){return typeof r.requestFrame=="function"}function vn(){return!!ut()&&typeof navigator.mediaDevices.ondevicechange<"u"&&typeof navigator.mediaDevices.addEventListener=="function"}const q={permissionQuery:un,mediaDevices:ut,settingResolutionInGetDisplayMedia:ln,promiseWithResolvers:pn,getUserMedia:hn,isolateEnumerateDevices:fn,supportIdealParamsInGetDisplayMedia:mn,canvasCaptureMediaStreamTrack:_n,requestFrameOnMediaStream:gn,ondevicechange:vn};function Cn(){if(q.promiseWithResolvers())return Promise.withResolvers();let r,e;const t=new Promise((i,s)=>{r=i,e=s});if(!r||!e)throw Error("resolver and rejector working unexpected");return{promise:t,resolve:r,reject:e}}function mr(r={}){const{timeout:e,message:t}={timeout:0,message:new C(y.UNEXPECTED_ERROR,"unexpected timeout"),...r},{promise:i,resolve:s,reject:n}=Cn();if(e<=0)return{promise:i,resolve:s,reject:n};const a=setTimeout(()=>{n(t)},e);return{promise:i,resolve:u=>{clearTimeout(a),s(u)},reject:n}}const yn={playsinline:"","webkit-playsinline":"","x5-playsinline":"","x5-video-player-type":"h5","x-webkit-airplay":"allow",preload:"metadata",muted:"",crossOrigin:"anonymous"},Sn={playsinline:"","webkit-playsinline":"",preload:"metadata",muted:"",crossOrigin:"anonymous"};class Ee{constructor(e,t=[]){m(this,"id",oe());m(this,"_referenceTracks",[]);m(this,"_element");m(this,"_volumeMode",0);m(this,"_readyLock");m(this,"_releaseReadyLock");m(this,"_throwReadyLock");m(this,"_stream");let i;if(e instanceof MediaStreamTrack){const o=new MediaStream([e]);i=Tn(o),this._stream=o}else if(e.url)i=En(e);else throw new C(y.UNEXPECTED_TYPE,`got ${typeof e}, expected: MediaStreamTrack or constraints for creating element`);const{promise:s,resolve:n,reject:a}=mr({timeout:2e3,message:new C(y.PLAY_FAILED,"load media timeout")});this._readyLock=s,this._releaseReadyLock=n,this._throwReadyLock=a,this._element=new ot(i),this._bindPlayerEvent(this._element),this._referenceTracks=[...t]}addReferenceTrack(e){this._referenceTracks.push(e)}track(e){this._playElement();let t=this._stream;if((!t||!t.active)&&(t=this._element.target.captureStream(),this._stream=t),e===E.AUDIO){this._upgradeVolumeMode(1e-4);const i=t.getAudioTracks();if(i.length<1)throw new C(y.UNEXPECTED_TYPE,"got empty list of audio tracks");return i[0]}if(e===E.VIDEO){const i=t.getVideoTracks();if(i.length<1)throw new C(y.UNEXPECTED_TYPE,"got empty list of video tracks");return i[0]}throw new C(y.UNEXPECTED_TYPE,`got ${e}, expected: audio, video`)}async _playElement(){if(!(!this._element.target.muted&&this._element.target.volume===this._volumeMode&&!this._element.target.paused))try{this._element.target.muted=!1,this._element.target.volume=this._volumeMode,await this._element.target.play()}catch(e){throw this._handlePlayFailed(),new C(y.PLAY_FAILED,"play element failed",e)}}_bindPlayerEvent(e){e.on("loadedmetadata",()=>{this._releaseReadyLock()}),e.on("error",()=>{this._throwReadyLock(new C(y.PLAY_FAILED,"HTMLMediaElement got error when loading file"))})}_handlePlayFailed(){this._referenceTracks.forEach(e=>{e.handlePlayFailed()})}_upgradeVolumeMode(e){console.warn("update volume mode",e);const t=this._volumeMode>e?this._volumeMode:e;this._volumeMode=t,this._playElement()}element(e=!1){return e&&this._upgradeVolumeMode(1),this._playElement(),this._element.target}isReady(){return this._readyLock}removeReference(e){const t=this._referenceTracks.indexOf(e);this._referenceTracks.splice(t,1),this._referenceTracks.length===0&&this.destroy()}destroy(){this._element.target.srcObject=null,this._element.target.src="",this._element.target.load();const e=[...this._referenceTracks];this._referenceTracks=[],e.forEach(t=>{try{t.destroy()}catch{}})}}function Tn(r){let e="audio";r.getVideoTracks().length>0&&(e="video");const t=fr(e==="video"?E.VIDEO:E.AUDIO);return t.srcObject=r,t}function En(r){const{url:e,kind:t,loop:i}=r,s=fr(t);return s.src=e,s.loop=i,s}function fr(r){if(r===E.VIDEO)return nt(E.VIDEO,{style:{width:"100%",height:"100%"},attributes:yn});if(r===E.AUDIO)return nt(E.AUDIO,{style:{display:"none"},attributes:Sn});throw new C(y.UNEXPECTED_TYPE,`got ${r}, expected: audio, video`)}class ht extends Q{emit(e,...t){const i=this.listenerCount(e);return Promise.resolve().then(()=>{super.emit(e,...t)}),!!i}on(e,t,i){const s=(...n)=>{try{return t(...n)}catch(a){console.error(`[SafeEventEmitter] event listener threw an error when handling [${e}] event: `,a)}};return super.on(e,s,i)}once(e,t,i){const s=(...n)=>{try{return t(...n)}catch(a){console.error(`[SafeEventEmitter] event listener threw an error when handling [${e}] event: `,a)}};return super.once(e,s,i)}}function pt(r){if(typeof r=="number")return r;if(typeof(r==null?void 0:r.exact)=="number")return r.exact;if(typeof(r==null?void 0:r.ideal)=="number")return r.ideal;if(typeof(r==null?void 0:r.max)=="number")return r.max;if(typeof(r==null?void 0:r.min)=="number")return r.min;throw new C(y.UNEXPECTED_TYPE,"unexpected constraints type")}const lt=1e3;class _r{constructor(e){m(this,"id",oe());m(this,"_context");m(this,"_canvas");m(this,"_image");m(this,"_config");m(this,"_readyLock");m(this,"_releaseReadyLock");m(this,"_throwReadyLock");m(this,"_loopTimer");m(this,"_referenceTracks",[]);m(this,"_stream");const t=pt(e.width),i=pt(e.height),s=pt(e.frameRate);this._config={width:t,height:i,frameRate:s};const{context:n,canvas:a}=pr({width:t,height:i});this._context=n,this._canvas=a;const o=bn({url:e.url,width:t,height:i});this._image=new ot(o);const{promise:u,resolve:c,reject:d}=mr({timeout:2e3,message:new C(y.PLAY_FAILED,"load image timeout")});this._readyLock=u,this._releaseReadyLock=c,this._throwReadyLock=d,this._bindImageEvent(this._image)}track(){this._paint();const{frameRate:e}=this._config;let t=this._stream;(!t||!t.active)&&(t=this._canvas.captureStream(e),this._stream=t);const i=t.getVideoTracks();if(i.length<1)throw new C(y.UNEXPECTED_TYPE,"got empty list of video tracks");return i[0]}element(){return this._image.target}isReady(){return this._readyLock}_bindImageEvent(e){e.on("load",()=>{this._releaseReadyLock()}),e.on("error",()=>{this._throwReadyLock(new C(y.PLAY_FAILED,"HTMLMediaElement got error when loading file"))})}async _paint(){const{width:e,height:t,frameRate:i}=this._config;this._context.drawImage(this._image.target,0,0,e,t),this._loopTimer&&clearTimeout(this._loopTimer),this._loopTimer=setTimeout(this._paint.bind(this),lt/i)}addReferenceTrack(e){this._referenceTracks.push(e)}removeReference(e){const t=this._referenceTracks.indexOf(e);this._referenceTracks.splice(t,1),console.warn("reference length",this._referenceTracks),this._referenceTracks.length}}function bn({url:r,height:e,width:t}){const i=nt("img",{style:{width:`${t}px`,height:`${e}px`},attributes:{crossOrigin:"anonymous"}});return i.src=r,i}class mt extends ht{constructor(t){super();m(this,"id",oe());m(this,"_track");m(this,"_element");t instanceof MediaStreamTrack?(this._track=new ot(t),this._bindTrackEvent(this._track)):t instanceof Ee?(this._element=t,t.addReferenceTrack(this)):t instanceof _r&&(this._element=t)}_bindTrackEvent(t){t.on("ended",this._handleTrackEnded.bind(this)),t.on("mute",()=>{this.emit(M.MUTE)}),t.on("unmute",()=>{this.emit(M.UNMUTE)})}_handleTrackEnded(){this.emit(M.ENDED),this.destroy()}handlePlayFailed(){this.emit(M.PLAY_FAILED)}track(){if(this.logger.info("track"),!this.available())throw new C(y.TRACK_NOT_AVAILABLE,"track is not available when creating MediaStreamTrack");if(this._track)return this._track.target;if(!this._element)throw new C(y.UNEXPECTED_TYPE,"got this._element falsy");const t=this._element.track(this.kind);return this.logger.success("track",t),t}element(){if(this.logger.info("element"),!this.available())throw new C(y.TRACK_NOT_AVAILABLE,"track is not available when creating HTMLMediaElement");if(this._element)return this._element.element();if(!this._track)throw new C(y.UNEXPECTED_TYPE,"got this._track falsy");const t=new Ee(this._track.target,[this]);this._element=t;const i=t.element();return this.logger.success("element",i),i}available(){return!!(this._track||this._element)}destroy(){var t,i,s;(t=this._track)==null||t.clearAll(),(i=this._track)==null||i.target.stop(),this._track&&delete this._track,(s=this._element)==null||s.removeReference(this),delete this._element}}class Le extends mt{constructor(){super(...arguments);m(this,"kind",E.AUDIO);m(this,"_node")}node(){if(this.logger.info("node",this.id),!this.available())throw new C(y.TRACK_NOT_AVAILABLE,"track is not avaiable when creating node");if(this._node)return this._node;const t=new sn(this);return this._node=t,t}element(){if(this.logger.info("element",this.id),!this.available())throw new C(y.TRACK_NOT_AVAILABLE,"track is not available when creating HTMLMediaElement");if(this._element){const i=this._element.element(!0);if(!(i instanceof HTMLMediaElement))throw new C(y.UNEXPECTED_TYPE,"source should be HTMLMediaElement");return i}if(!this._track)throw new C(y.UNEXPECTED_TYPE,"got this._track falsy");const t=new Ee(this._track.target,[this]);return this._element=t,t.element()}destroy(){var t;this.logger.warn("destroy",this.id),(t=this._node)==null||t.destroy(),super.destroy()}}class kn extends Le{constructor(){super(...arguments);m(this,"logger",new L("MicrophoneAudioTrack"))}}class Pn extends Le{constructor(){super(...arguments);m(this,"logger",new L("ScreenAudioTrack"))}}class gr extends Le{constructor(){super(...arguments);m(this,"logger",new L("MediaAudioTrack"))}handlePlayFailed(){this.emit(M.PLAY_FAILED)}async play(){if(this._element){if(!(this._element instanceof Ee))throw new C(y.UNEXPECTED_TYPE,"element is not TrackMediaElement");return this._element._playElement()}}}class xn extends Le{constructor(){super(...arguments);m(this,"logger",new L("CustomAudioTrack"))}}let Rn=1;const ft=new L("PromiseQueue");class An{constructor(e){m(this,"lockingPromise",Promise.resolve());m(this,"locks",0);m(this,"name","");m(this,"lockId");m(this,"closeReason");this.lockId=Rn++,e&&(this.name=e),ft.info(`lock-${this.name}-${this.lockId}`,"is created.")}get isLocked(){return this.locks>0}lock(){this.locks+=1,ft.info(`lock-${this.name}-${this.lockId}`,`locked, current queue ${this.locks}.`);let e;const t=new Promise(s=>{e=()=>{this.locks-=1,ft.info(`lock-${this.name}-${this.lockId}`,`unlocked, current queue ${this.locks}.`),s()}}),i=this.lockingPromise.then(()=>e);return this.lockingPromise=this.lockingPromise.then(()=>t),i}}const wn=300,On=3e3,G=new L("Devices");class In extends ht{constructor(){super();m(this,"_deviceMap",{audioinput:[],audiooutput:[],videoinput:[]});m(this,"_permissions",{[E.AUDIO]:!1,[E.VIDEO]:!1});m(this,"_changedQueue",new An("device changed queue"));this._init()}async _init(){this._initDeviceChanged(),await this._initPermissionChanged();const t=Sr(this._permissions);t.length>0&&this._refreshDevices(t)}_initDeviceChanged(){if(G.info("_initDeviceChanged","invoked"),!q.ondevicechange()){G.error("_initDeviceChanged","no supported, use timer instead"),setInterval(()=>{this._handleDeviceChanged()},On);return}q.ondevicechange()&&navigator.mediaDevices.addEventListener("devicechange",()=>{G.info("devicechange"),setTimeout(()=>{this._handleDeviceChanged()},wn)})}async _initPermissionChanged(){if(!q.permissionQuery()){G.error("_initPermissionChanged","permission query not supported, silent return");return}try{const t=await navigator.permissions.query({name:"microphone"});this._permissions.audio=t.state==="granted",t.addEventListener("change",()=>{G.info("_initPermissionChanged","update permission for audio"),this._permissions.audio=t.state==="granted"})}catch(t){G.error("_initPermissionChanged",t)}try{const t=await navigator.permissions.query({name:"camera"});this._permissions.video=t.state==="granted",t.addEventListener("change",()=>{G.info("_initPermissionChanged","update permission for video"),this._permissions.video=t.state==="granted"})}catch(t){G.error("_initPermissionChanged",t)}}async _refreshDevices(t){if(!q.mediaDevices())throw new C(y.NOT_SUPPORTED,"mediaDevices is not supported");if(t.length===0)throw new C(y.UNEXPECTED_TYPE,"kinds expect to containt values");let i;if(!q.isolateEnumerateDevices()){const a={};t.forEach(o=>{a[o]=!0}),i=await navigator.mediaDevices.getUserMedia(a)}let s=await navigator.mediaDevices.enumerateDevices();i&&vr(i),s=s.filter(({deviceId:a})=>!!a);const n={audioinput:[],audiooutput:[],videoinput:[]};s.forEach(a=>{const{kind:o}=a;n[o].push(a)}),this._deviceMap=n}async _acquireUserPermission(t){let i=!1;if(t.forEach(s=>{i=i||!this._permissions[s]}),!i)return{grant:!0};if(!q.getUserMedia())return{grant:!1,reason:new C(y.NOT_SUPPORTED,"getUserMedia is not supported")};try{const s={};t.forEach(a=>{s[a]=!0});const n=await navigator.mediaDevices.getUserMedia(s);return n?(s.audio&&(this._permissions[E.AUDIO]=!0),s.video&&(this._permissions[E.VIDEO]=!0),vr(n),{grant:!0}):{grant:!1,reason:new C(y.UNEXPECTED_TYPE,"get stream falsy")}}catch(s){return{grant:!1,reason:new C(y.CAPTURE_FAILED,"acquire user permission failed",s)}}}async _handleDeviceChanged(){G.info("_handleDeviceChanged",this._deviceMap,this._permissions);const t=await this._changedQueue.lock();try{const i=yr(this._deviceMap);let s=[];const n=Sr(this._permissions);n.length===0?G.warn("_handleDeviceChanged","no permission, use empty list"):(await this._refreshDevices(n),s=yr(this._deviceMap)),s.forEach(a=>{i.findIndex(u=>Cr(u,a))!==-1||this.emit("onDeviceStateChanged",{deviceInfo:a,deviceState:"active"})}),i.forEach(a=>{s.findIndex(u=>Cr(u,a))!==-1||this.emit("onDeviceStateChanged",{deviceInfo:a,deviceState:"inactive"})})}finally{t()}}async enumerateDevices(t){const i=[];t.forEach(o=>{if(o==="audioinput"||o==="audiooutput")i.push(E.AUDIO);else if(o==="videoinput")i.push(E.VIDEO);else throw new C(y.UNEXPECTED_TYPE,"kind in kinds should be enum MediaDeviceKind")});const{grant:s,reason:n}=await this._acquireUserPermission(i);if(!s)throw n;await this._refreshDevices(i);const a=[];return t.forEach(o=>{a.push(...this._deviceMap[o])}),a}async enableDevices(t){return this._acquireUserPermission(t)}}function vr(r){r.getTracks().forEach(e=>e.stop())}function Cr(r,e){return r.deviceId===e.deviceId}function yr(r){return Array.from([...r.audioinput.values(),...r.videoinput.values(),...r.audiooutput.values()])}function Sr(r){const e=[];return r.audio&&e.push(E.AUDIO),r.video&&e.push(E.VIDEO),e}const _t=new In;class gt{constructor(){m(this,"id",oe())}position(e,t){return new Mn(this,{x:e,y:t})}scale(e){return new Dn(this,{s:e})}available(){var e;return((e=this.previousNode)==null?void 0:e.available())??!1}}class Mn extends gt{constructor(t,i){super();m(this,"previousNode");m(this,"_x");m(this,"_y");this.previousNode=t,this._x=i.x,this._y=i.y}paint(t){t.translate(this._x,this._y)}}class Dn extends gt{constructor(t,i){super();m(this,"previousNode");m(this,"_s");this.previousNode=t,this._s=i.s}paint(t){t.scale(this._s,this._s)}}class Ln extends gt{constructor(t){super();m(this,"previousNode",null);m(this,"_source");this._source=t}available(){return this._source.available()}}class Fe extends Ln{constructor(t,i){super(t);m(this,"_targetWidth");m(this,"_targetHeight");const{width:s,height:n}=i??{};this._targetWidth=s??this._source.width(),this._targetHeight=n??this._source.height()}size(t,i){return new Fe(this._source,{width:t,height:i})}paint(t){const i=this._targetWidth,s=this._targetHeight;t.drawImage(this._source.element(),-i/2,-s/2,i,s)}}class Fn extends mt{constructor(){super(...arguments);m(this,"logger",new L("PictureTrack"));m(this,"kind",E.VIDEO)}element(){const t=super.element();if(!(t instanceof HTMLImageElement))throw new C(y.UNEXPECTED_TYPE,"source should be HTMLVideoElement");return this.logger.info("element",t),t}height(){const{height:t}=this.element();return t??0}width(){const{width:t}=this.element();return t??0}node(){if(!this.available())throw new C(y.TRACK_NOT_AVAILABLE,"track is not avaiable when creating node");const t=new Fe(this);return this.logger.info("node",t),t}destroy(){this.logger.warn("destroy"),super.destroy()}}const Nn=500;class Ne extends mt{constructor(){super(...arguments);m(this,"kind",E.VIDEO);m(this,"sizeChangeTimer");m(this,"watchSizeChangeOnce",()=>{const t=this.width(),i=this.height();this.sizeChangeTimer=setTimeout(()=>{const s=this.width(),n=this.height();(i!==n||t!==s)&&this.emit(M.SIZE_CHANGE,{width:s,height:n})},Nn)})}element(){const t=super.element();if(!(t instanceof HTMLVideoElement))throw new C(y.UNEXPECTED_TYPE,"source should be HTMLVideoElement");return t}node(){if(!this.available())throw new C(y.TRACK_NOT_AVAILABLE,"track is not avaiable when creating node");return new Fe(this)}destroy(){clearTimeout(this.sizeChangeTimer),super.destroy()}}class Vn extends Ne{constructor(t){super(t);m(this,"logger",new L("CameraVideoTrack"));this.watchSizeChangeOnce()}height(){const{height:t}=this.track().getSettings();return t??0}width(){const{width:t}=this.track().getSettings();return t??0}}class Un extends Ne{constructor(t){super(t);m(this,"logger",new L("ScreenVideoTrack"));this.watchSizeChangeOnce()}height(){const{height:t}=this.track().getSettings();return t??0}width(){const{width:t}=this.track().getSettings();return t??0}}class $n extends Ne{constructor(){super(...arguments);m(this,"logger",new L("MediaVideoTrack"))}height(){const{videoHeight:t}=this.element();return t??0}width(){const{videoWidth:t}=this.element();return t??0}}class Bn extends Ne{constructor(){super(...arguments);m(this,"logger",new L("CustomVideoTrack"))}height(){const{height:t}=this.track().getSettings();return t??0}width(){const{width:t}=this.track().getSettings();return t??0}}function Tr(r,e){let t;if(e!=null&&e.frameRate&&typeof e.frameRate=="number"&&(t=e.frameRate),t)try{r.applyConstraints({...e,frameRate:{min:t,ideal:t}})}catch{}}const W=new L("Capture");async function jn(r){return _t.enumerateDevices(r)}async function zn(r){_t.removeAllListeners("onDeviceStateChanged"),_t.on("onDeviceStateChanged",r)}async function Gn(r){let e;try{const i={video:r??!0};typeof i.video=="object"&&i.video.facingMode&&delete i.video.deviceId,e=await navigator.mediaDevices.getUserMedia(i)}catch(i){throw new C(y.CAPTURE_FAILED,"got error when capturing camera",i)}const t=e.getVideoTracks()[0];if(r!=null&&r.frameRate&&Tr(t,r),!t)throw new C(y.UNEXPECTED_TYPE,"got falsy in track");return new Vn(t)}async function Hn(r,e){const{video:t,audio:i}=r;let s=t===!0?{}:t;e!=null&&e.displaySurface&&(s.displaySurface=e.displaySurface,delete e.displaySurface),q.settingResolutionInGetDisplayMedia()||(s=!0),!q.supportIdealParamsInGetDisplayMedia()&&typeof s!="boolean"&&(s.width&&typeof s.width=="number"&&(s.width={max:s.width}),s.height&&typeof s.height=="number"&&(s.height={max:s.height}));let n;try{n=await navigator.mediaDevices.getDisplayMedia({video:s,audio:i,...e})}catch(c){throw new C(y.CAPTURE_FAILED,"got error when capture screen",c)}const a=n.getVideoTracks()[0],o=n.getAudioTracks()[0];if(!a)throw new C(y.UNEXPECTED_TYPE,"got falsy in videoTrack");typeof s!="boolean"&&typeof s.frameRate=="number"&&Tr(a,s);const u=[];return u.push(new Un(a)),o&&u.push(new Pn(o)),u}async function qn(r){const{url:e,audio:t,video:i,loop:s}=r,n=new Ee({url:e,kind:i?E.VIDEO:E.AUDIO,loop:s}),a=[];return t&&a.push(new gr(n)),i&&a.push(new $n(n)),await n.isReady(),a}async function Wn(r){const e=new _r(r);return await e.isReady(),new Fn(e)}async function Xn(r){let e;try{const i={audio:r??!0};e=await navigator.mediaDevices.getUserMedia(i)}catch(i){throw new C(y.CAPTURE_FAILED,"got error when capturing microphone",i)}const t=e.getAudioTracks()[0];if(!t)throw new C(y.UNEXPECTED_TYPE,"got falsy in track");return new kn(t)}function Kn(r){if(!r||r.kind!=="video")throw new C(y.UNEXPECTED_TYPE,"error custom video track type");return new Bn(r)}function Jn(r){if(!r||r.kind!=="audio")throw new C(y.UNEXPECTED_TYPE,"error custom audio track type");return new xn(r)}const Yn=W.invoke(jn,"enumerateInputDevices"),Zn=W.invoke(Gn,"createCameraTrack"),Qn=W.invoke(Wn,"createPictureTrack"),Er=W.invoke(qn,"createMediaTracks"),eo=W.invoke(Xn,"createMicrophoneTrack"),to=W.invoke(Hn,"createScreenTracks"),ro=W.invoke(zn,"onDeviceChanged"),io=W.invoke(Kn,"createCustomVideoTrack"),so=W.invoke(Jn,"createCustomAudioTrack");var vt=(r=>(r.PAUSING="pausing",r))(vt||{});const no={sampleRate:48e3,keepAlive:!0},br=new Map,be=new L("Mixer");class oo extends ht{constructor(t){super();m(this,"id",oe());m(this,"_context");m(this,"_config");m(this,"_nodeList",[]);m(this,"_destNode");m(this,"_bufferNode");m(this,"_track");be.info("ctor",t),this._config={...no,...t},this._context=ao(this._config),this._bindContextEvent(this._context)}mix(t){be.info("mix",t),Ct(this._context);for(const i of this._nodeList)t.includes(i)||i.destroy();this._nodeList=t,this._connect(t,this._destNode),this._nodeList.length===0&&this._appendSlience(this._context,this._destNode)}resume(){return be.info("resume"),this._context.resume()}_connect(t,i){for(const s of t)s.connect(this._context,i)}_appendSlience(t,i){if(!i||this._bufferNode)return;const{sampleRate:s}=t,n=new AudioBuffer({length:100,sampleRate:s}),a=new AudioBufferSourceNode(t,{buffer:n,loop:!0});a.connect(i),this._bufferNode=a}_bindContextEvent(t){t.addEventListener("statechange",this._handleContextStateChange.bind(this))}_handleContextStateChange(){const t=this._context;(t.state==="suspended"||t.state==="interrupted")&&(be.info("_emit_",vt.PAUSING),this.emit(vt.PAUSING))}track(){if(be.info("track"),Ct(this._context),this._track)return this._track;let t=this._destNode;t||(t=new MediaStreamAudioDestinationNode(this._context)),this._nodeList.length===0&&this._appendSlience(this._context,t),this._connect(this._nodeList,t);const i=t.stream.getAudioTracks()[0];return this._destNode=t,this._track=i,i}}function ao(r){const{sampleRate:e,keepAlive:t}=r;let i=br.get(e);return(!i||i.state==="closed")&&(i=new AudioContext({sampleRate:e}),br.set(e,i)),t&&(i.onstatechange=()=>{Ct(i)}),i}function Ct(r){if(r.state==="suspended"||r.state==="interrupted")return r.resume()}const co=r=>(e,t)=>(r.set(e,t),t),kr=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,Pr=536870912,xr=Pr*2,uo=(r,e)=>t=>{const i=e.get(t);let s=i===void 0?t.size:i<xr?i+1:0;if(!t.has(s))return r(t,s);if(t.size<Pr){for(;t.has(s);)s=Math.floor(Math.random()*xr);return r(t,s)}if(t.size>kr)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;t.has(s);)s=Math.floor(Math.random()*kr);return r(t,s)},Rr=new WeakMap,ho=co(Rr),ee=uo(ho,Rr),po=r=>r.method!==void 0&&r.method==="call",lo=r=>typeof r.id=="number"&&typeof r.result=="boolean",Ar=((r,e)=>{let t=null;return()=>{if(t!==null)return t;const i=new Blob([e],{type:"application/javascript; charset=utf-8"}),s=URL.createObjectURL(i);return t=r(s),setTimeout(()=>URL.revokeObjectURL(s)),t}})(r=>{const e=new Map([[0,()=>{}]]),t=new Map([[0,()=>{}]]),i=new Map,s=new Worker(r);return s.addEventListener("message",({data:c})=>{if(po(c)){const{params:{timerId:d,timerType:h}}=c;if(h==="interval"){const p=e.get(d);if(typeof p===void 0)throw new Error("The timer is in an undefined state.");if(typeof p=="number"){const l=i.get(p);if(l===void 0||l.timerId!==d||l.timerType!==h)throw new Error("The timer is in an undefined state.")}else typeof p=="function"&&p()}else if(h==="timeout"){const p=t.get(d);if(typeof p===void 0)throw new Error("The timer is in an undefined state.");if(typeof p=="number"){const l=i.get(p);if(l===void 0||l.timerId!==d||l.timerType!==h)throw new Error("The timer is in an undefined state.")}else typeof p=="function"&&(p(),t.delete(d))}}else if(lo(c)){const{id:d}=c,h=i.get(d);if(h===void 0)throw new Error("The timer is in an undefined state.");const{timerId:p,timerType:l}=h;i.delete(d),l==="interval"?e.delete(p):t.delete(p)}else{const{error:{message:d}}=c;throw new Error(d)}}),{clearInterval:c=>{if(typeof e.get(c)=="function"){const d=ee(i);i.set(d,{timerId:c,timerType:"interval"}),e.set(c,d),s.postMessage({id:d,method:"clear",params:{timerId:c,timerType:"interval"}})}},clearTimeout:c=>{if(typeof t.get(c)=="function"){const d=ee(i);i.set(d,{timerId:c,timerType:"timeout"}),t.set(c,d),s.postMessage({id:d,method:"clear",params:{timerId:c,timerType:"timeout"}})}},setInterval:(c,d=0,...h)=>{const p=ee(e);return e.set(p,()=>{c(...h),typeof e.get(p)=="function"&&s.postMessage({id:null,method:"set",params:{delay:d,now:performance.timeOrigin+performance.now(),timerId:p,timerType:"interval"}})}),s.postMessage({id:null,method:"set",params:{delay:d,now:performance.timeOrigin+performance.now(),timerId:p,timerType:"interval"}}),p},setTimeout:(c,d=0,...h)=>{const p=ee(t);return t.set(p,()=>c(...h)),s.postMessage({id:null,method:"set",params:{delay:d,now:performance.timeOrigin+performance.now(),timerId:p,timerType:"timeout"}}),p}}},`(()=>{"use strict";const e=new Map,t=new Map,r=t=>{const r=e.get(t);return void 0!==r&&(clearTimeout(r),e.delete(t),!0)},s=e=>{const r=t.get(e);return void 0!==r&&(clearTimeout(r),t.delete(e),!0)},o=(e,t)=>{const r=performance.now(),s=e+t-r-performance.timeOrigin;return{expected:r+s,remainingDelay:s}},i=(e,t,r,s)=>{const o=r-performance.now();o>0?e.set(t,setTimeout(i,o,e,t,r,s)):(e.delete(t),postMessage({id:null,method:"call",params:{timerId:t,timerType:s}}))};addEventListener("message",(({data:n})=>{try{if("clear"===n.method){const{id:e,params:{timerId:t,timerType:o}}=n;if("interval"===o)postMessage({id:e,result:r(t)});else{if("timeout"!==o)throw new Error('The given type "'.concat(o,'" is not supported'));postMessage({id:e,result:s(t)})}}else{if("set"!==n.method)throw new Error('The given method "'.concat(n.method,'" is not supported'));{const{params:{delay:r,now:s,timerId:a,timerType:m}}=n;if("interval"===m)((t,r,s)=>{const{expected:n,remainingDelay:a}=o(t,s);e.set(r,setTimeout(i,a,e,r,n,"interval"))})(r,a,s);else{if("timeout"!==m)throw new Error('The given type "'.concat(m,'" is not supported'));((e,r,s)=>{const{expected:n,remainingDelay:a}=o(e,s);t.set(r,setTimeout(i,a,t,r,n,"timeout"))})(r,a,s)}}}}catch(e){postMessage({error:{message:e.message},id:n.id,result:null})}}))})();`),mo=r=>Ar().clearTimeout(r),fo=(...r)=>Ar().setTimeout(...r),_o=r=>r.method!==void 0&&r.method==="call",go=r=>typeof r.id=="number"&&typeof r.result=="boolean",vo=r=>{const e=new Map([[0,()=>{}]]),t=new Map([[0,()=>{}]]),i=new Map,s=new Worker(r,{credentials:"omit"});return s.addEventListener("message",({data:c})=>{if(_o(c)){const{params:{timerId:d,timerType:h}}=c;if(h==="interval"){const p=e.get(d);if(typeof p===void 0)throw new Error("The timer is in an undefined state.");if(typeof p=="number"){const l=i.get(p);if(l===void 0||l.timerId!==d||l.timerType!==h)throw new Error("The timer is in an undefined state.")}else typeof p=="function"&&p()}else if(h==="timeout"){const p=t.get(d);if(typeof p===void 0)throw new Error("The timer is in an undefined state.");if(typeof p=="number"){const l=i.get(p);if(l===void 0||l.timerId!==d||l.timerType!==h)throw new Error("The timer is in an undefined state.")}else typeof p=="function"&&(p(),t.delete(d))}}else if(go(c)){const{id:d}=c,h=i.get(d);if(h===void 0)throw new Error("The timer is in an undefined state.");const{timerId:p,timerType:l}=h;i.delete(d),l==="interval"?e.delete(p):t.delete(p)}else{const{error:{message:d}}=c;throw new Error(d)}}),{clearInterval:c=>{if(typeof e.get(c)=="function"){const d=ee(i);i.set(d,{timerId:c,timerType:"interval"}),e.set(c,d),s.postMessage({id:d,method:"clear",params:{timerId:c,timerType:"interval"}})}},clearTimeout:c=>{if(typeof t.get(c)=="function"){const d=ee(i);i.set(d,{timerId:c,timerType:"timeout"}),t.set(c,d),s.postMessage({id:d,method:"clear",params:{timerId:c,timerType:"timeout"}})}},setInterval:(c,d=0,...h)=>{const p=ee(e);return e.set(p,()=>{c(...h),typeof e.get(p)=="function"&&s.postMessage({id:null,method:"set",params:{delay:d,now:performance.timeOrigin+performance.now(),timerId:p,timerType:"interval"}})}),s.postMessage({id:null,method:"set",params:{delay:d,now:performance.timeOrigin+performance.now(),timerId:p,timerType:"interval"}}),p},setTimeout:(c,d=0,...h)=>{const p=ee(t);return t.set(p,()=>c(...h)),s.postMessage({id:null,method:"set",params:{delay:d,now:performance.timeOrigin+performance.now(),timerId:p,timerType:"timeout"}}),p}}},Co={width:640,height:480,frameRate:30,backgroundColor:"#000000"},Ve=new L("View");class yo{constructor(e){m(this,"id",oe());m(this,"_context");m(this,"_canvas");m(this,"_config");m(this,"_nodeList",[]);m(this,"_track");m(this,"_stopped",!0);m(this,"_nextTime",Date.now());m(this,"_workerTimeoutId");m(this,"_raqId");m(this,"_workerTimerScriptUrl");m(this,"_customSetTimeout");m(this,"_customClearTimeout");m(this,"_loopTimer");m(this,"_paintLoop",()=>{if(this._stopped){this._workerTimeoutId&&(this._customClearTimeout(this._workerTimeoutId),this._workerTimeoutId=void 0);return}this._drawOnCanvas(),this._workerTimeoutId&&this._customClearTimeout(this._workerTimeoutId),this._workerTimeoutId=this._customSetTimeout(()=>{this._paintLoop(),this._raqId&&(cancelAnimationFrame(this._raqId),this._raqId=void 0)},lt/this._config.frameRate),this._raqId=requestAnimationFrame(this._paintLoop)});Ve.info("ctor",e),this._config={...Co,...e};const{context:t,canvas:i}=pr(this._config);this._context=t,this._canvas=i,this._customSetTimeout=fo,this._customClearTimeout=mo}setWorkerTimerScriptUrl(e){if(this._workerTimerScriptUrl=e,this._workerTimerScriptUrl){const t=vo(this._workerTimerScriptUrl);this._customSetTimeout=(...i)=>t.setTimeout(...i),this._customClearTimeout=i=>t.clearTimeout(i)}}_shouldDraw(e){if(e<this._nextTime)return!1;for(;e>this._nextTime;)this._nextTime+=lt/this._config.frameRate;return!0}updateConfig(e){this._config={...this._config,...e},this._canvas.width=this._config.width,this._canvas.height=this._config.height}draw(e=[]){Ve.info("draw",e),this._nodeList=e}_drawOnCanvas(){if(this._shouldDraw(Date.now())){this._drawBackground();for(const e of this._nodeList){let t=e;if(t.available()){for(;t;)t.paint(this._context),t=t.previousNode;this._context.setTransform(1,0,0,1,0,0)}}}}_drawBackground(){const{backgroundColor:e,width:t,height:i}=this._config;this._context.clearRect(0,0,t,i),e&&(this._context.fillStyle=e,this._context.fillRect(0,0,t,i))}track(){if(Ve.info("track"),this._track)return this._track;this._stopped=!1,this._paintLoop();const{frameRate:e}=this._config,t=this._canvas.captureStream(e);return this._track=t.getVideoTracks()[0],this._track}updateFps(){if(this._track){const{frameRate:e}=this._config,t=this._canvas.captureStream(e);return this._track=t.getVideoTracks()[0],this._track}else return this.track()}element(){return Ve.info("element"),this._paintLoop(),this._canvas}stop(){this._stopped=!0}}function So(){return Math.random().toString(36).slice(-8)}const To=`
2
+ const SMOOTHING_FACTOR = 0.8;
3
+ const MINIMUM_VALUE = 0.00001;
4
+
5
+
6
+ registerProcessor('vumeter', class extends AudioWorkletProcessor {
7
+
8
+ _volume
9
+ _updateIntervalInMS
10
+ _nextUpdateFrame
11
+
12
+ constructor () {
13
+ super();
14
+ this._volume = 0;
15
+ this._updateIntervalInMS = 50;
16
+ this._nextUpdateFrame = this._updateIntervalInMS;
17
+ this.port.onmessage = event => {
18
+ if (event.data.updateIntervalInMS)
19
+ this._updateIntervalInMS = event.data.updateIntervalInMS;
20
+ }
21
+ }
22
+
23
+ get intervalInFrames () {
24
+ return this._updateIntervalInMS / 1000 * sampleRate;
25
+ }
26
+
27
+ process (inputs, outputs, parameters) {
28
+ const input = inputs[0];
29
+
30
+ // Note that the input will be down-mixed to mono; however, if no inputs are
31
+ // connected then zero channels will be passed in.
32
+ if (input.length > 0) {
33
+ const samples = input[0];
34
+ let sum = 0;
35
+ let rms = 0;
36
+
37
+ // Calculated the squared-sum.
38
+ for (let i = 0; i < samples.length; ++i)
39
+ sum += samples[i] * samples[i];
40
+
41
+ // Calculate the RMS level and update the volume. 均方根值
42
+ rms = Math.sqrt(sum / samples.length);
43
+ this._volume = Math.max(rms, this._volume * SMOOTHING_FACTOR);
44
+
45
+ // Update and sync the volume property with the main thread.
46
+ this._nextUpdateFrame -= samples.length;
47
+ if (this._nextUpdateFrame < 0) {
48
+ this._nextUpdateFrame += this.intervalInFrames;
49
+ this.port.postMessage({volume: this._volume});
50
+ }
51
+ }
52
+
53
+ return true;
54
+ }
55
+ });
56
+ `,Eo=URL.createObjectURL(new Blob([To],{type:"application/javascript"}));class bo{constructor(){this._audioCtx=null,this._volume=0}get volume(){return this._volume}async start(e,t){if(this._audioCtx)return;const i=new AudioContext;await i.audioWorklet.addModule(t||Eo);const s=new MediaStream;s.addTrack(e);const n=i.createMediaStreamSource(s),a=new AudioWorkletNode(i,"vumeter");a.port.onmessage=o=>{const u=o.data.volume||0;this._volume=Math.min(u*100/2,10)},n.connect(a).connect(i.destination),this._audioCtx=i}stop(){var e;(e=this._audioCtx)==null||e.close(),this._audioCtx=null}}class Ue{constructor(){this._volumeDetectScriptUrl=void 0}static get instance(){return this._instance||(this._instance=new Ue),this._instance}get volumeDetectScriptUrl(){return this._volumeDetectScriptUrl}set volumeDetectScriptUrl(e){this._volumeDetectScriptUrl=e}}class wr extends Q{constructor(e){super(),this._width=0,this._height=0,this._mediaStream=null,this._nextStream=null,this._trackMap={},this.type=e.type,this.id=So(),this._source=e.stream}get source(){return this._source}get videoTrack(){return this._trackMap.video}get audioTrack(){return this._trackMap.audio}get width(){return this._width}get height(){return this._height}get isVideoStream(){return[S.Camera,S.Screen,S.VideoFile].includes(this.type)}get mediaStream(){if(this._mediaStream)return this._mediaStream;const e=new MediaStream;return this._trackMap.audio&&e.addTrack(this._trackMap.audio),this._trackMap.video&&e.addTrack(this._trackMap.video),this._mediaStream=e,e}async startVolumeDetect(){this.audioTrack&&(this._volumeDetector||(this._volumeDetector=new bo),await this._volumeDetector.start(this.audioTrack,Ue.instance.volumeDetectScriptUrl))}stopVolumeDetect(){var e;(e=this._volumeDetector)==null||e.stop(),this._volumeDetector=null}get volume(){var e;return((e=this._volumeDetector)==null?void 0:e.volume)||0}}class le extends wr{get isVideoStream(){return!0}get isAudioStream(){return!1}bindTrackSizeChangeEvent(e){e.on(M.SIZE_CHANGE,({width:t,height:i})=>{this._width=t,this._height=i,this.emit(rt.SizeChange,{width:t,height:i})})}}class $e extends wr{get isVideoStream(){return!1}get isAudioStream(){return!0}}class ko extends le{constructor(e){super({type:S.Camera,stream:e}),this._trackMap.video=e.track(),this._width=e.width(),this._height=e.height(),this.bindTrackSizeChangeEvent(e)}get source(){return this._source}get viewNode(){return this.source.node()}get mixerNode(){return null}bindTrackEnd(e){this.source.on(M.ENDED,e)}destroy(){this.source.destroy()}}var Or=typeof global=="object"&&global&&global.Object===Object&&global,Po=typeof self=="object"&&self&&self.Object===Object&&self,X=Or||Po||Function("return this")(),te=X.Symbol,Ir=Object.prototype,xo=Ir.hasOwnProperty,Ro=Ir.toString,ke=te?te.toStringTag:void 0;function Ao(r){var e=xo.call(r,ke),t=r[ke];try{r[ke]=void 0;var i=!0}catch{}var s=Ro.call(r);return i&&(e?r[ke]=t:delete r[ke]),s}var wo=Object.prototype,Oo=wo.toString;function Io(r){return Oo.call(r)}var Mo="[object Null]",Do="[object Undefined]",Mr=te?te.toStringTag:void 0;function me(r){return r==null?r===void 0?Do:Mo:Mr&&Mr in Object(r)?Ao(r):Io(r)}function fe(r){return r!=null&&typeof r=="object"}var Lo="[object Symbol]";function Be(r){return typeof r=="symbol"||fe(r)&&me(r)==Lo}function Dr(r,e){for(var t=-1,i=r==null?0:r.length,s=Array(i);++t<i;)s[t]=e(r[t],t,r);return s}var F=Array.isArray,Lr=te?te.prototype:void 0,Fr=Lr?Lr.toString:void 0;function Nr(r){if(typeof r=="string")return r;if(F(r))return Dr(r,Nr)+"";if(Be(r))return Fr?Fr.call(r):"";var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}var Fo=/\s/;function No(r){for(var e=r.length;e--&&Fo.test(r.charAt(e)););return e}var Vo=/^\s+/;function Uo(r){return r&&r.slice(0,No(r)+1).replace(Vo,"")}function Pe(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}var Vr=NaN,$o=/^[-+]0x[0-9a-f]+$/i,Bo=/^0b[01]+$/i,jo=/^0o[0-7]+$/i,zo=parseInt;function Go(r){if(typeof r=="number")return r;if(Be(r))return Vr;if(Pe(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=Pe(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=Uo(r);var t=Bo.test(r);return t||jo.test(r)?zo(r.slice(2),t?2:8):$o.test(r)?Vr:+r}var Ho=1/0,qo=17976931348623157e292;function Wo(r){if(!r)return r===0?r:0;if(r=Go(r),r===Ho||r===-1/0){var e=r<0?-1:1;return e*qo}return r===r?r:0}function Xo(r){var e=Wo(r),t=e%1;return e===e?t?e-t:e:0}function Ko(r){return r}var Jo="[object AsyncFunction]",Yo="[object Function]",Zo="[object GeneratorFunction]",Qo="[object Proxy]";function Ur(r){if(!Pe(r))return!1;var e=me(r);return e==Yo||e==Zo||e==Jo||e==Qo}var yt=X["__core-js_shared__"],$r=function(){var r=/[^.]+$/.exec(yt&&yt.keys&&yt.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""}();function ea(r){return!!$r&&$r in r}var ta=Function.prototype,ra=ta.toString;function ae(r){if(r!=null){try{return ra.call(r)}catch{}try{return r+""}catch{}}return""}var ia=/[\\^$.*+?()[\]{}|]/g,sa=/^\[object .+?Constructor\]$/,na=Function.prototype,oa=Object.prototype,aa=na.toString,ca=oa.hasOwnProperty,da=RegExp("^"+aa.call(ca).replace(ia,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function ua(r){if(!Pe(r)||ea(r))return!1;var e=Ur(r)?da:sa;return e.test(ae(r))}function ha(r,e){return r==null?void 0:r[e]}function _e(r,e){var t=ha(r,e);return ua(t)?t:void 0}var St=_e(X,"WeakMap");function pa(r,e,t,i){for(var s=r.length,n=t+-1;++n<s;)if(e(r[n],n,r))return n;return-1}var la=9007199254740991,ma=/^(?:0|[1-9]\d*)$/;function Br(r,e){var t=typeof r;return e=e??la,!!e&&(t=="number"||t!="symbol"&&ma.test(r))&&r>-1&&r%1==0&&r<e}function jr(r,e){return r===e||r!==r&&e!==e}var fa=9007199254740991;function Tt(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=fa}function Et(r){return r!=null&&Tt(r.length)&&!Ur(r)}var _a=Object.prototype;function ga(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||_a;return r===t}function va(r,e){for(var t=-1,i=Array(r);++t<r;)i[t]=e(t);return i}var Ca="[object Arguments]";function zr(r){return fe(r)&&me(r)==Ca}var Gr=Object.prototype,ya=Gr.hasOwnProperty,Sa=Gr.propertyIsEnumerable,Hr=zr(function(){return arguments}())?zr:function(r){return fe(r)&&ya.call(r,"callee")&&!Sa.call(r,"callee")};function Ta(){return!1}var qr=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Wr=qr&&typeof module=="object"&&module&&!module.nodeType&&module,Ea=Wr&&Wr.exports===qr,Xr=Ea?X.Buffer:void 0,ba=Xr?Xr.isBuffer:void 0,bt=ba||Ta,ka="[object Arguments]",Pa="[object Array]",xa="[object Boolean]",Ra="[object Date]",Aa="[object Error]",wa="[object Function]",Oa="[object Map]",Ia="[object Number]",Ma="[object Object]",Da="[object RegExp]",La="[object Set]",Fa="[object String]",Na="[object WeakMap]",Va="[object ArrayBuffer]",Ua="[object DataView]",$a="[object Float32Array]",Ba="[object Float64Array]",ja="[object Int8Array]",za="[object Int16Array]",Ga="[object Int32Array]",Ha="[object Uint8Array]",qa="[object Uint8ClampedArray]",Wa="[object Uint16Array]",Xa="[object Uint32Array]",k={};k[$a]=k[Ba]=k[ja]=k[za]=k[Ga]=k[Ha]=k[qa]=k[Wa]=k[Xa]=!0,k[ka]=k[Pa]=k[Va]=k[xa]=k[Ua]=k[Ra]=k[Aa]=k[wa]=k[Oa]=k[Ia]=k[Ma]=k[Da]=k[La]=k[Fa]=k[Na]=!1;function Ka(r){return fe(r)&&Tt(r.length)&&!!k[me(r)]}function Ja(r){return function(e){return r(e)}}var Kr=typeof exports=="object"&&exports&&!exports.nodeType&&exports,xe=Kr&&typeof module=="object"&&module&&!module.nodeType&&module,Ya=xe&&xe.exports===Kr,kt=Ya&&Or.process,Jr=function(){try{var r=xe&&xe.require&&xe.require("util").types;return r||kt&&kt.binding&&kt.binding("util")}catch{}}(),Yr=Jr&&Jr.isTypedArray,Zr=Yr?Ja(Yr):Ka,Za=Object.prototype,Qa=Za.hasOwnProperty;function ec(r,e){var t=F(r),i=!t&&Hr(r),s=!t&&!i&&bt(r),n=!t&&!i&&!s&&Zr(r),a=t||i||s||n,o=a?va(r.length,String):[],u=o.length;for(var c in r)Qa.call(r,c)&&!(a&&(c=="length"||s&&(c=="offset"||c=="parent")||n&&(c=="buffer"||c=="byteLength"||c=="byteOffset")||Br(c,u)))&&o.push(c);return o}function tc(r,e){return function(t){return r(e(t))}}var rc=tc(Object.keys,Object),ic=Object.prototype,sc=ic.hasOwnProperty;function nc(r){if(!ga(r))return rc(r);var e=[];for(var t in Object(r))sc.call(r,t)&&t!="constructor"&&e.push(t);return e}function Re(r){return Et(r)?ec(r):nc(r)}var oc=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,ac=/^\w*$/;function Pt(r,e){if(F(r))return!1;var t=typeof r;return t=="number"||t=="symbol"||t=="boolean"||r==null||Be(r)?!0:ac.test(r)||!oc.test(r)||e!=null&&r in Object(e)}var Ae=_e(Object,"create");function cc(){this.__data__=Ae?Ae(null):{},this.size=0}function dc(r){var e=this.has(r)&&delete this.__data__[r];return this.size-=e?1:0,e}var uc="__lodash_hash_undefined__",hc=Object.prototype,pc=hc.hasOwnProperty;function lc(r){var e=this.__data__;if(Ae){var t=e[r];return t===uc?void 0:t}return pc.call(e,r)?e[r]:void 0}var mc=Object.prototype,fc=mc.hasOwnProperty;function _c(r){var e=this.__data__;return Ae?e[r]!==void 0:fc.call(e,r)}var gc="__lodash_hash_undefined__";function vc(r,e){var t=this.__data__;return this.size+=this.has(r)?0:1,t[r]=Ae&&e===void 0?gc:e,this}function ce(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var i=r[e];this.set(i[0],i[1])}}ce.prototype.clear=cc,ce.prototype.delete=dc,ce.prototype.get=lc,ce.prototype.has=_c,ce.prototype.set=vc;function Cc(){this.__data__=[],this.size=0}function je(r,e){for(var t=r.length;t--;)if(jr(r[t][0],e))return t;return-1}var yc=Array.prototype,Sc=yc.splice;function Tc(r){var e=this.__data__,t=je(e,r);if(t<0)return!1;var i=e.length-1;return t==i?e.pop():Sc.call(e,t,1),--this.size,!0}function Ec(r){var e=this.__data__,t=je(e,r);return t<0?void 0:e[t][1]}function bc(r){return je(this.__data__,r)>-1}function kc(r,e){var t=this.__data__,i=je(t,r);return i<0?(++this.size,t.push([r,e])):t[i][1]=e,this}function K(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var i=r[e];this.set(i[0],i[1])}}K.prototype.clear=Cc,K.prototype.delete=Tc,K.prototype.get=Ec,K.prototype.has=bc,K.prototype.set=kc;var we=_e(X,"Map");function Pc(){this.size=0,this.__data__={hash:new ce,map:new(we||K),string:new ce}}function xc(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}function ze(r,e){var t=r.__data__;return xc(e)?t[typeof e=="string"?"string":"hash"]:t.map}function Rc(r){var e=ze(this,r).delete(r);return this.size-=e?1:0,e}function Ac(r){return ze(this,r).get(r)}function wc(r){return ze(this,r).has(r)}function Oc(r,e){var t=ze(this,r),i=t.size;return t.set(r,e),this.size+=t.size==i?0:1,this}function J(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var i=r[e];this.set(i[0],i[1])}}J.prototype.clear=Pc,J.prototype.delete=Rc,J.prototype.get=Ac,J.prototype.has=wc,J.prototype.set=Oc;var Ic="Expected a function";function xt(r,e){if(typeof r!="function"||e!=null&&typeof e!="function")throw new TypeError(Ic);var t=function(){var i=arguments,s=e?e.apply(this,i):i[0],n=t.cache;if(n.has(s))return n.get(s);var a=r.apply(this,i);return t.cache=n.set(s,a)||n,a};return t.cache=new(xt.Cache||J),t}xt.Cache=J;var Mc=500;function Dc(r){var e=xt(r,function(i){return t.size===Mc&&t.clear(),i}),t=e.cache;return e}var Lc=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Fc=/\\(\\)?/g,Nc=Dc(function(r){var e=[];return r.charCodeAt(0)===46&&e.push(""),r.replace(Lc,function(t,i,s,n){e.push(s?n.replace(Fc,"$1"):i||t)}),e});function Vc(r){return r==null?"":Nr(r)}function Qr(r,e){return F(r)?r:Pt(r,e)?[r]:Nc(Vc(r))}function Ge(r){if(typeof r=="string"||Be(r))return r;var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function ei(r,e){e=Qr(e,r);for(var t=0,i=e.length;r!=null&&t<i;)r=r[Ge(e[t++])];return t&&t==i?r:void 0}function Uc(r,e,t){var i=r==null?void 0:ei(r,e);return i===void 0?t:i}function $c(r,e){for(var t=-1,i=e.length,s=r.length;++t<i;)r[s+t]=e[t];return r}function Bc(){this.__data__=new K,this.size=0}function jc(r){var e=this.__data__,t=e.delete(r);return this.size=e.size,t}function zc(r){return this.__data__.get(r)}function Gc(r){return this.__data__.has(r)}var Hc=200;function qc(r,e){var t=this.__data__;if(t instanceof K){var i=t.__data__;if(!we||i.length<Hc-1)return i.push([r,e]),this.size=++t.size,this;t=this.__data__=new J(i)}return t.set(r,e),this.size=t.size,this}function Y(r){var e=this.__data__=new K(r);this.size=e.size}Y.prototype.clear=Bc,Y.prototype.delete=jc,Y.prototype.get=zc,Y.prototype.has=Gc,Y.prototype.set=qc;function ti(r,e){for(var t=-1,i=r==null?0:r.length,s=0,n=[];++t<i;){var a=r[t];e(a,t,r)&&(n[s++]=a)}return n}function Wc(){return[]}var Xc=Object.prototype,Kc=Xc.propertyIsEnumerable,ri=Object.getOwnPropertySymbols,Jc=ri?function(r){return r==null?[]:(r=Object(r),ti(ri(r),function(e){return Kc.call(r,e)}))}:Wc;function Yc(r,e,t){var i=e(r);return F(r)?i:$c(i,t(r))}function ii(r){return Yc(r,Re,Jc)}var Rt=_e(X,"DataView"),At=_e(X,"Promise"),wt=_e(X,"Set"),si="[object Map]",Zc="[object Object]",ni="[object Promise]",oi="[object Set]",ai="[object WeakMap]",ci="[object DataView]",Qc=ae(Rt),ed=ae(we),td=ae(At),rd=ae(wt),id=ae(St),re=me;(Rt&&re(new Rt(new ArrayBuffer(1)))!=ci||we&&re(new we)!=si||At&&re(At.resolve())!=ni||wt&&re(new wt)!=oi||St&&re(new St)!=ai)&&(re=function(r){var e=me(r),t=e==Zc?r.constructor:void 0,i=t?ae(t):"";if(i)switch(i){case Qc:return ci;case ed:return si;case td:return ni;case rd:return oi;case id:return ai}return e});var di=X.Uint8Array,sd="__lodash_hash_undefined__";function nd(r){return this.__data__.set(r,sd),this}function od(r){return this.__data__.has(r)}function He(r){var e=-1,t=r==null?0:r.length;for(this.__data__=new J;++e<t;)this.add(r[e])}He.prototype.add=He.prototype.push=nd,He.prototype.has=od;function ad(r,e){for(var t=-1,i=r==null?0:r.length;++t<i;)if(e(r[t],t,r))return!0;return!1}function cd(r,e){return r.has(e)}var dd=1,ud=2;function ui(r,e,t,i,s,n){var a=t&dd,o=r.length,u=e.length;if(o!=u&&!(a&&u>o))return!1;var c=n.get(r),d=n.get(e);if(c&&d)return c==e&&d==r;var h=-1,p=!0,l=t&ud?new He:void 0;for(n.set(r,e),n.set(e,r);++h<o;){var f=r[h],g=e[h];if(i)var _=a?i(g,f,h,e,r,n):i(f,g,h,r,e,n);if(_!==void 0){if(_)continue;p=!1;break}if(l){if(!ad(e,function(T,b){if(!cd(l,b)&&(f===T||s(f,T,t,i,n)))return l.push(b)})){p=!1;break}}else if(!(f===g||s(f,g,t,i,n))){p=!1;break}}return n.delete(r),n.delete(e),p}function hd(r){var e=-1,t=Array(r.size);return r.forEach(function(i,s){t[++e]=[s,i]}),t}function pd(r){var e=-1,t=Array(r.size);return r.forEach(function(i){t[++e]=i}),t}var ld=1,md=2,fd="[object Boolean]",_d="[object Date]",gd="[object Error]",vd="[object Map]",Cd="[object Number]",yd="[object RegExp]",Sd="[object Set]",Td="[object String]",Ed="[object Symbol]",bd="[object ArrayBuffer]",kd="[object DataView]",hi=te?te.prototype:void 0,Ot=hi?hi.valueOf:void 0;function Pd(r,e,t,i,s,n,a){switch(t){case kd:if(r.byteLength!=e.byteLength||r.byteOffset!=e.byteOffset)return!1;r=r.buffer,e=e.buffer;case bd:return!(r.byteLength!=e.byteLength||!n(new di(r),new di(e)));case fd:case _d:case Cd:return jr(+r,+e);case gd:return r.name==e.name&&r.message==e.message;case yd:case Td:return r==e+"";case vd:var o=hd;case Sd:var u=i&ld;if(o||(o=pd),r.size!=e.size&&!u)return!1;var c=a.get(r);if(c)return c==e;i|=md,a.set(r,e);var d=ui(o(r),o(e),i,s,n,a);return a.delete(r),d;case Ed:if(Ot)return Ot.call(r)==Ot.call(e)}return!1}var xd=1,Rd=Object.prototype,Ad=Rd.hasOwnProperty;function wd(r,e,t,i,s,n){var a=t&xd,o=ii(r),u=o.length,c=ii(e),d=c.length;if(u!=d&&!a)return!1;for(var h=u;h--;){var p=o[h];if(!(a?p in e:Ad.call(e,p)))return!1}var l=n.get(r),f=n.get(e);if(l&&f)return l==e&&f==r;var g=!0;n.set(r,e),n.set(e,r);for(var _=a;++h<u;){p=o[h];var T=r[p],b=e[p];if(i)var v=a?i(b,T,p,e,r,n):i(T,b,p,r,e,n);if(!(v===void 0?T===b||s(T,b,t,i,n):v)){g=!1;break}_||(_=p=="constructor")}if(g&&!_){var j=r.constructor,R=e.constructor;j!=R&&"constructor"in r&&"constructor"in e&&!(typeof j=="function"&&j instanceof j&&typeof R=="function"&&R instanceof R)&&(g=!1)}return n.delete(r),n.delete(e),g}var Od=1,pi="[object Arguments]",li="[object Array]",qe="[object Object]",Id=Object.prototype,mi=Id.hasOwnProperty;function Md(r,e,t,i,s,n){var a=F(r),o=F(e),u=a?li:re(r),c=o?li:re(e);u=u==pi?qe:u,c=c==pi?qe:c;var d=u==qe,h=c==qe,p=u==c;if(p&&bt(r)){if(!bt(e))return!1;a=!0,d=!1}if(p&&!d)return n||(n=new Y),a||Zr(r)?ui(r,e,t,i,s,n):Pd(r,e,u,t,i,s,n);if(!(t&Od)){var l=d&&mi.call(r,"__wrapped__"),f=h&&mi.call(e,"__wrapped__");if(l||f){var g=l?r.value():r,_=f?e.value():e;return n||(n=new Y),s(g,_,t,i,n)}}return p?(n||(n=new Y),wd(r,e,t,i,s,n)):!1}function It(r,e,t,i,s){return r===e?!0:r==null||e==null||!fe(r)&&!fe(e)?r!==r&&e!==e:Md(r,e,t,i,It,s)}var Dd=1,Ld=2;function Fd(r,e,t,i){var s=t.length,n=s;if(r==null)return!n;for(r=Object(r);s--;){var a=t[s];if(a[2]?a[1]!==r[a[0]]:!(a[0]in r))return!1}for(;++s<n;){a=t[s];var o=a[0],u=r[o],c=a[1];if(a[2]){if(u===void 0&&!(o in r))return!1}else{var d=new Y,h;if(!(h===void 0?It(c,u,Dd|Ld,i,d):h))return!1}}return!0}function fi(r){return r===r&&!Pe(r)}function Nd(r){for(var e=Re(r),t=e.length;t--;){var i=e[t],s=r[i];e[t]=[i,s,fi(s)]}return e}function _i(r,e){return function(t){return t==null?!1:t[r]===e&&(e!==void 0||r in Object(t))}}function Vd(r){var e=Nd(r);return e.length==1&&e[0][2]?_i(e[0][0],e[0][1]):function(t){return t===r||Fd(t,r,e)}}function Ud(r,e){return r!=null&&e in Object(r)}function $d(r,e,t){e=Qr(e,r);for(var i=-1,s=e.length,n=!1;++i<s;){var a=Ge(e[i]);if(!(n=r!=null&&t(r,a)))break;r=r[a]}return n||++i!=s?n:(s=r==null?0:r.length,!!s&&Tt(s)&&Br(a,s)&&(F(r)||Hr(r)))}function Bd(r,e){return r!=null&&$d(r,e,Ud)}var jd=1,zd=2;function Gd(r,e){return Pt(r)&&fi(e)?_i(Ge(r),e):function(t){var i=Uc(t,r);return i===void 0&&i===e?Bd(t,r):It(e,i,jd|zd)}}function Hd(r){return function(e){return e==null?void 0:e[r]}}function qd(r){return function(e){return ei(e,r)}}function Wd(r){return Pt(r)?Hd(Ge(r)):qd(r)}function Mt(r){return typeof r=="function"?r:r==null?Ko:typeof r=="object"?F(r)?Gd(r[0],r[1]):Vd(r):Wd(r)}function Xd(r){return function(e,t,i){for(var s=-1,n=Object(e),a=i(e),o=a.length;o--;){var u=a[++s];if(t(n[u],u,n)===!1)break}return e}}var Kd=Xd();function Jd(r,e){return r&&Kd(r,e,Re)}function Yd(r,e){return function(t,i){if(t==null)return t;if(!Et(t))return r(t,i);for(var s=t.length,n=-1,a=Object(t);++n<s&&i(a[n],n,a)!==!1;);return t}}var Zd=Yd(Jd);function Qd(r,e){var t=[];return Zd(r,function(i,s,n){e(i,s,n)&&t.push(i)}),t}function gi(r,e){var t=F(r)?ti:Qd;return t(r,Mt(e))}function eu(r){return function(e,t,i){var s=Object(e);if(!Et(e)){var n=Mt(t);e=Re(e),t=function(o){return n(s[o],o,s)}}var a=r(e,t,i);return a>-1?s[n?e[a]:a]:void 0}}var tu=Math.max;function ru(r,e,t){var i=r==null?0:r.length;if(!i)return-1;var s=t==null?0:Xo(t);return s<0&&(s=tu(i+s,0)),pa(r,Mt(e),s)}var Oe=eu(ru);function iu(r,e){return Dr(e,function(t){return r[t]})}function ge(r){return r==null?[]:iu(r,Re(r))}function su(r){return r==null}class nu extends $e{constructor(e){super({type:S.Microphone,stream:e}),this._trackMap.audio=e.track()}get source(){return this._source}get mixerNode(){return this.source.node()}bindTrackEnd(e){this.source.on(M.ENDED,e)}destroy(){this.source.destroy()}}class ou extends le{constructor(e){super({type:S.VideoFile,stream:e});const t=Oe(e,s=>s.kind===E.VIDEO),i=Oe(e,s=>s.kind===E.AUDIO);this._videoStream=t,this._audioStream=i,this._trackMap.video=t==null?void 0:t.track(),this._trackMap.audio=i==null?void 0:i.track(),t&&(this._height=t==null?void 0:t.height(),this._width=t==null?void 0:t.width())}get viewNode(){var e;return((e=this._videoStream)==null?void 0:e.node())??null}get mixerNode(){var e;return((e=this._audioStream)==null?void 0:e.node())??null}bindTrackEnd(e){var t;(t=this._videoStream)==null||t.on(M.ENDED,e)}destroy(){var e,t;(e=this._videoStream)==null||e.destroy(),(t=this._audioStream)==null||t.destroy(),delete this._trackMap.video,delete this._trackMap.audio}}class au extends le{constructor(e){super({type:S.Screen,stream:e});const t=Oe(e,s=>s.kind===E.VIDEO),i=Oe(e,s=>s.kind===E.AUDIO);this._videoStream=t,this._audioStream=i,this._trackMap.video=t==null?void 0:t.track(),this._trackMap.audio=i==null?void 0:i.track(),t&&(this._height=t==null?void 0:t.height(),this._width=t==null?void 0:t.width(),this.bindTrackSizeChangeEvent(t))}get viewNode(){var e;return((e=this._videoStream)==null?void 0:e.node())??null}get mixerNode(){var e;return((e=this._audioStream)==null?void 0:e.node())??null}bindTrackEnd(e){var t;(t=this._videoStream)==null||t.on(M.ENDED,e)}destroy(){var e,t;(e=this._videoStream)==null||e.destroy(),(t=this._audioStream)==null||t.destroy(),delete this._trackMap.video,delete this._trackMap.audio}}class cu extends $e{constructor(e){super({type:S.AudioFile,stream:e});const t=Oe(e,i=>i.kind===E.AUDIO);this._audioStream=t,this._trackMap.audio=t==null?void 0:t.track()}get mixerNode(){var e;return((e=this._audioStream)==null?void 0:e.node())??null}bindTrackEnd(e){var t;(t=this._audioStream)==null||t.on(M.ENDED,e)}destroy(){var e;(e=this._audioStream)==null||e.destroy()}}class du extends le{constructor(e){super({type:S.Image,stream:e}),this._width=e.width(),this._height=e.height()}get source(){return this._source}get mixerNode(){return null}get viewNode(){return this.source.node()}bindTrackEnd(e){this.source.on(M.ENDED,e)}destroy(){this.source.destroy()}}class uu extends le{constructor(e){super({type:S.CustomVideo,stream:e}),this._trackMap.video=e.track(),this._width=e.width(),this._height=e.height()}get source(){return this._source}get viewNode(){return this.source.node()}get mixerNode(){return null}bindTrackEnd(e){this.source.on(M.ENDED,e)}destroy(){this.source.destroy()}}class hu extends $e{constructor(e){super({type:S.CustomAudio,stream:e}),this._trackMap.audio=e==null?void 0:e.track()}get source(){return this._source}get mixerNode(){var e;return((e=this.source)==null?void 0:e.node())??null}bindTrackEnd(e){var t;(t=this._audioStream)==null||t.on(M.ENDED,e)}destroy(){var e;(e=this._audioStream)==null||e.destroy()}}const pu=["user","environment"];var N=(r=>(r[r.OPEN_CAMERA_FAILED=1001]="OPEN_CAMERA_FAILED",r[r.OPEN_MICROPHONE_FAILED=1002]="OPEN_MICROPHONE_FAILED",r[r.OPEN_SCREEN_FAILED=1003]="OPEN_SCREEN_FAILED",r[r.VIDEO_FILE_CAPTURE_FAILED=1004]="VIDEO_FILE_CAPTURE_FAILED",r[r.AUDIO_FILE_CAPTURE_FAILED=1005]="AUDIO_FILE_CAPTURE_FAILED",r[r.IMAGE_FILE_CAPTURE_FAILED=1006]="IMAGE_FILE_CAPTURE_FAILED",r[r.VOLUME_DETECT_FAILED=1008]="VOLUME_DETECT_FAILED",r[r.PUBLISH_FAILED=2001]="PUBLISH_FAILED",r[r.UPDATE_PUBLISH_FAILED=2002]="UPDATE_PUBLISH_FAILED",r[r.PUSH_CONNECT_FAILED=2003]="PUSH_CONNECT_FAILED",r))(N||{});class Ie extends Error{constructor(e,t,i){super(),this.code=e,this.message=t,i&&(this.ext=i)}}function ve(r,e,t){const i=it.Landscape;if(e==="video"){const u=(i===it.Landscape?tr:rr)[r],[c,d,h,p]=u.split("x").map(l=>Number(l));return{width:c,height:d,frameRate:h,bitrate:p*1e3}}const s=ir[r],[n,a]=s.split("x").map(o=>Number(o));return{sampleRate:n,bitrate:a*1e3}}class lu extends Q{constructor(){super(),this._videoConstraints={width:1080,height:720,frameRate:30},this._cameraStreams={},this._screenStreams={},this._videoFileStreams={},this._microphoneStreams={},this._audioFileStreams={},this._imageStreams={},this._customVideoStreams={},this._customAudioStreams={};const{width:e,height:t,frameRate:i}=ve(nr,"video"),{sampleRate:s}=ve(or,"audio");this._videoConstraints={width:e,height:t,frameRate:i},this._audioConstraints={sampleRate:s,enableAutoGainControl:!0,enableNoiseSuppression:!0,enableEchoCancellation:!0}}_notifyCaptured(e){this.emit(z.DeviceCaptured,e)}_notifyStopCapture(e){this.emit(z.DeviceStopCapture,e)}_bindStreamEvent(e){e.bindTrackEnd(()=>{this.emit(z.Interrupted,e),this.stopCapture({streamId:e.id,type:e.type})})}_handleError(e,t){const i=new Ie(t,e.message);this.emit(z.Error,i)}setVideoResolution(e){this._videoConstraints={...this._videoConstraints,...e}}setVideoFps(e){this._videoConstraints={...this._videoConstraints,frameRate:e}}setAudioSampleRate(e){this._audioConstraints={...this._audioConstraints,sampleRate:e}}async getDevicesList(e){return Yn(e?[e]:["audioinput","videoinput"])}async getMicrophones(){return this.getDevicesList("audioinput")}async getCameras(){return this.getDevicesList("videoinput")}stopCapture({streamId:e,type:t}){let i;switch(t){case S.Camera:i="_cameraStreams";break;case S.Screen:i="_screenStreams";break;case S.VideoFile:i="_videoFileStreams";break;case S.Microphone:i="_microphoneStreams";break;case S.AudioFile:i="_audioFileStreams";break;case S.Image:i="_imageStreams";break;case S.CustomVideo:i="_customVideoStreams";break;case S.CustomAudio:i="_customAudioStreams";break}if(i){let s=[];if(e){const n=this[i][e];s.push(n)}else s=ge(this[i]);s.forEach(n=>{this._notifyStopCapture(n),n.destroy(),delete this[i][n.id]})}}async startCameraCapture(e){let t={};pu.includes(e)?t={facingMode:e}:t={deviceId:e};try{const i=await Zn({...t,...this._videoConstraints}),s=new ko(i);return this._cameraStreams[s.id]=s,this._notifyCaptured(s),this._bindStreamEvent(s),s.id}catch(i){throw this._handleError(i,N.OPEN_CAMERA_FAILED),i}}async startMicrophoneCapture(e){try{const t=await eo({...this._audioConstraints,deviceId:e}),i=new nu(t);return this._microphoneStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),i.id}catch(t){throw this._handleError(t,N.OPEN_MICROPHONE_FAILED),t}}async startScreenCapture(e){try{const t=await to({audio:e,video:this._videoConstraints}),i=new au(t);return this._screenStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),i.id}catch(t){throw this._handleError(t,N.OPEN_SCREEN_FAILED),t}}async startVideoFileCapture(e){try{const t=await Er({url:e,video:!0,audio:!0,loop:!0}),i=new ou(t);return this._videoFileStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),i.id}catch(t){throw this._handleError(t,N.VIDEO_FILE_CAPTURE_FAILED),t}}async startAudioFileCapture(e){try{const t=await Er({url:e,video:!1,audio:!0,loop:!0}),i=new cu(t);return this._audioFileStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),i.id}catch(t){throw this._handleError(t,N.AUDIO_FILE_CAPTURE_FAILED),t}}async startImageCapture(e){try{const t=await Qn({url:e,width:0,height:0,frameRate:30}),i=new du(t);return this._imageStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),i.id}catch(t){throw this._handleError(t,N.IMAGE_FILE_CAPTURE_FAILED),t}}startCustomVideoCapture(e){const t=io(e);if(t){const i=new uu(t);return this._customVideoStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),i.id}}startCustomAudioCapture(e){const t=so(e);if(t){const i=new hu(t);return this._customAudioStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),i.id}}async startVolumeDetect(e){const t=this.getStreamById(e);if(t)try{await t.startVolumeDetect()}catch(i){this._handleError(i,N.VOLUME_DETECT_FAILED)}}stopVolumeDetect(e){const t=this.getStreamById(e);t&&t.stopVolumeDetect()}getDefaultVideoStream(){return ge(this._cameraStreams)[0]||ge(this._screenStreams)[0]||ge(this._videoFileStreams)[0]}getDefaultAudioStream(){return ge(this._microphoneStreams)[0]||ge(this._audioFileStreams)[0]}getVideoStream(e){return this._cameraStreams[e]||this._screenStreams[e]||this._videoFileStreams[e]||this._imageStreams[e]}getAudioStream(e){return this._microphoneStreams[e]||this._audioFileStreams[e]}getStreamById(e){return this.getAudioStream(e)||this.getVideoStream(e)}getVolume(e){const t=this.getStreamById(e);return(t==null?void 0:t.volume)||0}destroy(){Object.values(S).forEach(e=>{this.stopCapture({type:e})})}}let de=class{constructor(e){this._enabled=!1,this.group=(...t)=>{this._enabled&&console.group(`[${this._prefix}]: `,...t)},this.groupCollapsed=(...t)=>{this._enabled&&console.groupCollapsed(`[${this._prefix}]: `,...t)},this.groupEnd=()=>{this._enabled&&console.groupEnd()},this.log=(...t)=>{this._enabled&&console.log(`[${this._prefix}]: `,...t)},this.warn=(...t)=>{this._enabled&&console.warn(`[${this._prefix}]: `,...t)},this.error=(...t)=>{this._enabled&&console.error(`[${this._prefix}]: `,...t)},this.table=(...t)=>{this._enabled&&console.table(...t)},this._prefix=e;try{this._enabled=location.href.indexOf("rtmdebug")!==-1}catch{}}};class Dt{constructor({streamManagerController:e,composedStream:t,streamComposeController:i}){this._streamManagerController=e,this._composedStream=t,this._streamComposeController=i,this._active=!1,this.bindStreamManagerControllerEvent()}bindStreamManagerControllerEvent(){this._streamManagerController.on(z.DeviceCaptured,e=>{this._active&&this.onStreamCapture(e)}),this._streamManagerController.on(z.DeviceStopCapture,e=>{this._active&&this.onStreamStopCapture(e)})}getComposedStream(){return this._composedStream}enable(){this._active=!0}disable(){this._active=!1}}const vi=new de("SingleComposer");class mu extends Dt{onStreamCapture(e){e.isVideoStream?this._handleVideoStreamCapture(e):this._handleAudioStreamCapture(e)}onStreamStopCapture(e){e&&(e.isVideoStream?this._handleVideoStreamStopCapture(e):this._handleAudioStreamStopCapture(e))}enable(){if(super.enable(),this._composedStream.videoStream){const e=this._streamManagerController.getDefaultVideoStream();e&&this._handleVideoStreamCapture(e)}}async setVideoQuality({width:e,height:t,frameRate:i}){var s,n;if(this._active)try{await((n=(s=this._composedStream.videoStream)==null?void 0:s.videoTrack)==null?void 0:n.applyConstraints({width:{min:e,ideal:e},height:{min:t,ideal:t},frameRate:{min:i,ideal:i}}))}catch(a){vi.error("setVideoQuality error",a)}}_handleVideoStreamCapture(e){const t=this._composedStream.videoStream;t!=null&&t.id&&this._streamComposeController.getMixerComposer().haveMixedStream(t.id)&&this._streamComposeController.removeAudioStream(t.id),e.audioTrack&&this._streamComposeController.addAudioStream({streamId:e.id,volume:100}),this._composedStream.setVideoStream(e)}_handleAudioStreamCapture(e){const t=this._streamComposeController.getMixerComposer().getMixedStreamByType(e.type);t.length>0&&t.forEach(i=>{this._streamComposeController.removeAudioStream(i.id)}),this._streamComposeController.addAudioStream({streamId:e.id,volume:100})}_handleVideoStreamStopCapture(e){const t=this._composedStream.videoStream;if((t==null?void 0:t.id)===e.id){const i=this._streamManagerController.getDefaultVideoStream();i?this._handleVideoStreamCapture(i):vi.error("all video stream stop capture")}}_handleAudioStreamStopCapture(e){this._streamComposeController.removeAudioStream(e.id)}getComposedStream(){return this._composedStream}}class fu extends Q{constructor(e,{width:t,height:i,x:s,y:n,zOrder:a,keepRatio:o}){super(),this._rect={x:0,y:0,width:0,height:0,zOrder:0},this._isHidden=!1,this._paintSize={width:0,height:0},this._rect.width=t??e.width,this._rect.height=i??e.height,this._rect.x=s??0,this._rect.y=n??0,this._rect.zOrder=a??0,this._rect.sourceHeight=e.height,this._rect.sourceWidth=e.width,this._rect.keepRatio=o??!1,this._stream=e,this._bindVideoTrackSizeChange()}_getPaintSize({elementWidth:e,elementHeight:t}){const i=this._rect.width,s=this._rect.height;if(i===0&&s===0)return{width:0,height:0};if(i===0)return{height:s,width:e*(s/t)};if(s===0)return{width:i,height:t*(i/e)};const n=e/t,a=i/s;let o=i,u=s;return n>a?(o=i,u=2*Math.round(i/n/2)):n<a&&(o=2*Math.round(s*n/2),u=s),{width:o,height:u}}_bindVideoTrackSizeChange(){this._stream.on(rt.SizeChange,({width:e,height:t})=>{this.setBaseProps("sourceWidth",e),this.setBaseProps("sourceHeight",t)})}getViewNode(){var i;if(!this._stream)return;let e={width:this._rect.width,height:this._rect.height};return this._rect.keepRatio&&(e=this._getPaintSize({elementWidth:this._stream.width,elementHeight:this._stream.height})),this._paintSize=e,(i=this._stream.viewNode)==null?void 0:i.size(e.width,e.height).position(this._rect.x,this._rect.y)}get x(){return this._rect.x}set x(e){this.setBaseProps("x",e)}get y(){return this._rect.y}set y(e){this.setBaseProps("y",e)}get width(){return this._rect.width}set width(e){this.setBaseProps("width",e)}get height(){return this._rect.height}set height(e){this.setBaseProps("height",e)}get zOrder(){return this._rect.zOrder}set zOrder(e){this.setBaseProps("zOrder",e)}get keepRatio(){return this._rect.keepRatio??!1}set keepRatio(e){this.setBaseProps("keepRatio",e)}get paintSize(){return this._paintSize}setBaseProps(e,t){const i=this._rect[e]!==t;switch(e){case"width":this._rect.width=t;break;case"height":this._rect.height=t;break;case"x":this._rect.x=t;break;case"y":this._rect.y=t;break;case"zOrder":this._rect.zOrder=t;break;case"keepRatio":this._rect.keepRatio=t;break}i&&this.emit("propsChange",{[e]:t})}show(){this._isHidden=!1}hide(){this._isHidden=!0}get stream(){return this._stream}get isHidden(){return this._isHidden}destroy(){}}class Ci extends le{constructor(e){super({type:S.MixVideo,stream:e}),this._trackMap.video=e}get source(){return this._source}replaceVideoTrack(e){this._trackMap.video=e,this._source=e}get viewNode(){return null}get mixerNode(){return null}bindTrackEnd(e){this.source.onended=e}destroy(){this.source.stop(),delete this._trackMap.video}}var _u=Object.defineProperty,gu=Object.getOwnPropertyDescriptor,Me=(r,e,t,i)=>{for(var s=gu(e,t),n=r.length-1,a;n>=0;n--)(a=r[n])&&(s=a(e,t,s)||s);return s&&_u(e,t,s),s};const yi=new de("composition-composer");function De(r,e,t){const i=t.value;return t.value=function(...s){return this._active||yi.error("composer is not active"),i.apply(this,s)},t}class Ce extends Dt{constructor(e){super(e),this._compositionViewConfig={width:1080,height:720,frameRate:30,backgroundColor:"#000000"},this._sprites=[],this._videoMixer=new yo}onStreamCapture(e){}onStreamStopCapture(e){e&&e.isVideoStream&&this.removeVideoStream(e.id)}enable(){super.enable();const e=this._videoMixer.track();this._mixedVideoStream?this._mixedVideoStream.replaceVideoTrack(e):this._mixedVideoStream=new Ci(e),this._composedStream.setVideoStream(this._mixedVideoStream)}disable(){super.disable(),this._videoMixer.stop()}_updateSpriteToMixer(){const e=gi(this._sprites.map(t=>t.isHidden?null:t.getViewNode()));this._videoMixer.draw(e)}_removeSprite(e){this._sprites=this._sprites.filter(t=>t!==e),e.destroy(),this._updateSpriteToMixer()}_addSprite(e){this._sprites.push(e),this._sprites=this._sprites.sort((t,i)=>t.zOrder-i.zOrder),e.on("propsChange",t=>{su(t.zOrder)||(this._sprites=this._sprites.sort((i,s)=>i.zOrder-s.zOrder)),this._updateSpriteToMixer()}),this._updateSpriteToMixer()}setMixingConfig(e){const t=e.frameRate&&e.frameRate!==this._compositionViewConfig.frameRate;if(this._compositionViewConfig={...this._compositionViewConfig,...e},this._compositionViewConfig.frameRate<1&&(this._compositionViewConfig.frameRate=1),this._videoMixer.updateConfig(this._compositionViewConfig),t&&this._mixedVideoStream){const i=this._videoMixer.updateFps();this._mixedVideoStream?this._mixedVideoStream.replaceVideoTrack(i):this._mixedVideoStream=new Ci(i),this._composedStream.setVideoStream(this._mixedVideoStream)}}addVideoStream(e,t){if(!e.viewNode){yi.error("have no viewNode for composition");return}e.audioTrack&&this._streamComposeController.addAudioStream({streamId:e.id,volume:100});const i=new fu(e,t);this._addSprite(i)}_updateSingleVideoStream(e){const t=e.streamId;if(!t)return;const i=this._sprites.find(s=>s.stream.id===t);i&&(i.height=e.height,i.width=e.width,i.x=e.x,i.y=e.y,i.zOrder=e.zOrder,i.keepRatio=e.keepRatio??!1)}updateVideoStream(e){e.forEach(t=>{this._updateSingleVideoStream(t)}),this._updateSpriteToMixer()}removeVideoStream(e){if(!e)return;const t=this._sprites.find(i=>i.stream.id===e);t&&this._removeSprite(t)}muteVideoStream(e){if(e){const t=this._sprites.find(i=>i.stream.id===e);t&&t.hide()}else this._sprites.forEach(t=>{t.hide()});this._updateSpriteToMixer()}unmuteVideoStream(e){if(e){const t=this._sprites.find(i=>i.stream.id===e);t&&t.show()}else this._sprites.forEach(t=>{t.show()});this._updateSpriteToMixer()}setMixerWorkerScript(e){this._videoMixer.setWorkerTimerScriptUrl(e)}}Me([De],Ce.prototype,"addVideoStream"),Me([De],Ce.prototype,"updateVideoStream"),Me([De],Ce.prototype,"removeVideoStream"),Me([De],Ce.prototype,"muteVideoStream"),Me([De],Ce.prototype,"unmuteVideoStream");class vu extends Q{constructor(e,{volume:t}){super(),this._volume=100,this._isMute=!1,this._volume=t??100,this._stream=e}get volume(){return this._volume}set volume(e){const t=this._volume!==e;this._volume=e,t&&this.emit("propsChange",{volume:e})}getMixerNode(){var e;return(e=this._stream.mixerNode)==null?void 0:e.gain(this._volume/100)}mute(){this._isMute=!0}unmute(){this._isMute=!1}get isMute(){return this._isMute}get stream(){return this._stream}}class Cu extends $e{constructor(e){super({type:S.MixAudio,stream:e}),this._trackMap.audio=e}get source(){return this._source}hasVideoTrack(){return!1}get mixerNode(){return null}bindTrackEnd(e){this.source.onended=e}destroy(){var e;(e=this._trackMap.audio)==null||e.stop(),delete this._trackMap.audio}}class yu extends Dt{constructor(e){super(e),this._spriteList=[],this._audioMixer=new oo}onStreamCapture(e){}onStreamStopCapture(e){e&&this.removeAudioStream(e.id)}_updateSpriteToMixer(){const e=gi(this._spriteList.map(t=>t.isMute?null:t.getMixerNode()));this._audioMixer.mix(e)}_updateSingleAudioStream(e){const{streamId:t,volume:i}=e,s=this._spriteList.find(n=>n.stream.id===t);s?i!==void 0&&(s.volume=i):console.error("can not find stream"+t)}enable(){super.enable();const e=this._audioMixer.track(),t=new Cu(e);this._composedStream.setAudioStream(t),this._audioMixer.mix([])}addAudioStream(e,t){const i=new vu(e,t);this._spriteList.push(i),this._updateSpriteToMixer()}removeAudioStream(e){const t=this._spriteList.find(i=>i.stream.id===e);t&&(this._spriteList=this._spriteList.filter(i=>i!==t),this._updateSpriteToMixer())}updateAudioStream(e){e.forEach(t=>{this._updateSingleAudioStream(t)}),this._updateSpriteToMixer()}muteAudioStream(e){if(e){const t=this._spriteList.find(i=>i.stream.id===e);t&&t.mute()}else this._spriteList.forEach(t=>{t.mute()});this._updateSpriteToMixer()}unmuteAudioStream(e){if(e){const t=this._spriteList.find(i=>i.stream.id===e);t&&t.unmute()}else this._spriteList.forEach(t=>{t.unmute()});this._updateSpriteToMixer()}haveMixedStream(e){return this._spriteList.some(t=>t.stream.id===e)}getMixedStreamByType(e){return this._spriteList.filter(t=>t.stream.type===e).map(t=>t.stream)}}class Su extends Q{constructor({videoStream:e,audioStream:t}={}){super(),this._videoStream=e,this._audioStream=t}setVideoStream(e){var t;((t=this._videoStream)==null?void 0:t.id)!==(e==null?void 0:e.id)&&(this._videoStream=e,this.emit(ne.VideoStreamChange,e))}setAudioStream(e){var t;((t=this._audioStream)==null?void 0:t.id)!==e.id&&(this._audioStream=e,this.emit(ne.AudioStreamChange,e))}get audioStream(){return this._audioStream}get videoStream(){return this._videoStream}get videoTrack(){var e;return(e=this._videoStream)==null?void 0:e.videoTrack}get audioTrack(){var e;return(e=this._audioStream)==null?void 0:e.audioTrack}}const Tu=new de("streamComposeController");class Eu{constructor(e){this._streamManagerController=e,this._composedStream=new Su,this.singleComposer=new mu({streamManagerController:this._streamManagerController,composedStream:this._composedStream,streamComposeController:this}),this.compositionComposer=new Ce({streamManagerController:this._streamManagerController,composedStream:this._composedStream,streamComposeController:this}),this.mixerComposer=new yu({streamManagerController:this._streamManagerController,composedStream:this._composedStream,streamComposeController:this}),this.singleComposer.enable(),this.mixerComposer.enable()}enableMixing(e){e?(this.compositionComposer.enable(),this.singleComposer.disable()):(this.compositionComposer.disable(),this.singleComposer.enable())}setVideoQuality({width:e,height:t,frameRate:i}){this.singleComposer.setVideoQuality({width:e,height:t,frameRate:i}),this.compositionComposer.setMixingConfig({width:e,height:t,frameRate:i})}setMixingConfig(e){this.compositionComposer.setMixingConfig(e)}addAudioStream(e){const t=this._streamManagerController.getStreamById(e.streamId);this.mixerComposer.addAudioStream(t,{volume:e.volume??100})}removeAudioStream(e){return this.mixerComposer.removeAudioStream(e)}updateAudioStream(e){this.mixerComposer.updateAudioStream(e)}addVideoStream(e){const t=this._streamManagerController.getVideoStream(e.streamId);if(!t){Tu.error("can not find video stream"+e.streamId);return}this.compositionComposer.addVideoStream(t,e)}updateVideoStream(e){this.compositionComposer.updateVideoStream(e);const t=e.map(i=>({streamId:i.streamId,volume:i.volume}));this.mixerComposer.updateAudioStream(t)}removeVideoStream(e){this.compositionComposer.removeVideoStream(e),this.mixerComposer.removeAudioStream(e)}getComposer(){return this.isEnableMixing?this.compositionComposer:this.singleComposer}getComposedStream(){return this._composedStream}muteVideoStream(e){this.isEnableMixing&&this.compositionComposer.muteVideoStream(e)}unmuteVideoStream(e){this.isEnableMixing&&this.compositionComposer.unmuteVideoStream(e)}muteAudioStream(e){this.mixerComposer.muteAudioStream(e)}unmuteAudioStream(e){this.mixerComposer.unmuteAudioStream(e)}get isEnableMixing(){return this.compositionComposer._active}getMixerComposer(){return this.mixerComposer}setMixerWorkerScript(e){this.compositionComposer.setMixerWorkerScript(e)}}class Si{constructor(e){this._hasBindComposedStreamEvent=!1,this._composedStream=e}bindComposedStreamEvent(){this._hasBindComposedStreamEvent||(this._composedStream.on(ne.VideoStreamChange,this.handleVideoStreamChange),this._composedStream.on(ne.AudioStreamChange,this.handleAudioStreamChange),this._hasBindComposedStreamEvent=!0)}unbindComposedStreamEvent(){this._hasBindComposedStreamEvent&&(this._composedStream.off(ne.VideoStreamChange,this.handleVideoStreamChange),this._composedStream.off(ne.AudioStreamChange,this.handleAudioStreamChange),this._hasBindComposedStreamEvent=!1)}}const ye=new de("PreviewConsumer");class bu extends Si{constructor(e,{streamConsumeController:t}){super(e),this._isPreviewing=!1,this._previewElement=null,this.handleAudioStreamChange=i=>{this.startPreview()},this.handleVideoStreamChange=i=>{this.startPreview()},this._streamConsumeController=t}start(){this.bindComposedStreamEvent()}stop(){this.unbindComposedStreamEvent()}setRenderView(e){if(!e)return;const t=document.getElementById(e);if(!t)throw new Error(`can not found element with id ${e}`);if(t===this._previewElement)return;if(this._previewElement){if(t.contains(this._previewElement))return;t.appendChild(this._previewElement);return}const i=document.createElement("video");i.style.width="100%",i.style.height="100%",i.autoplay=!0,i.playsInline=!0,i.setAttribute("webkit-playsinline",""),i.setAttribute("x5-playsinline",""),this._previewElement=i;const s={video:null,audio:null};i.addEventListener("loadeddata",()=>{const n=i.srcObject.getVideoTracks()[0],a=i.srcObject.getAudioTracks()[0];n&&n!==s.video&&(this._streamConsumeController.emit(A.CaptureFirstVideoFrame),s.video=n),a&&a!==s.audio&&(this._streamConsumeController.emit(A.CaptureFirstAudioFrame),s.audio=a)}),t.appendChild(i)}startPreview(){if(ye.log("startPreview"),!this._previewElement){ye.warn("preview element not found");return}this._isPreviewing||this.start();const e=this._composedStream.audioTrack,t=this._composedStream.videoTrack;e&&(this._appendTrack(this._previewElement,e),this._removeTrack(this._previewElement,null)),t&&(this._appendTrack(this._previewElement,t),this._removeTrack(this._previewElement,null)),this._previewElement.play().catch(i=>{this._streamConsumeController.emit(A.NotAllowedAutoPlay)}),this._isPreviewing=!0}stopPreview(){this._isPreviewing=!1;const e=this._composedStream.audioTrack,t=this._composedStream.videoTrack;e&&this._removeTrack(this._previewElement,e),t&&this._removeTrack(this._previewElement,t),this.stop()}destroy(){this.stopPreview(),this._previewElement=null,this.unbindComposedStreamEvent()}_appendTrack(e,t){if(!e||!t)return;const i=e.srcObject||new MediaStream;i.getTracks().find(s=>s.id===t.id)||(t.kind==="audio"&&i.getTracks().forEach(s=>{s.kind==="audio"&&(ye.log(`remove preview track, ${s.label}, readyState=${s.readyState}`),i.removeTrack(s))}),t.kind==="video"&&i.getTracks().forEach(s=>{s.kind==="video"&&(i.removeTrack(s),ye.log(`remove preview track, ${s.label}, readyState=${s.readyState}`))}),i.addTrack(t),e.srcObject?e.load():e.srcObject=i)}_removeTrack(e,t){if(!e)return;const i=e.srcObject;i&&(i.getTracks().forEach(s=>{(s.id===(t==null?void 0:t.id)||s.readyState==="ended")&&(ye.log(`remove preview track ${s.label}`),i.removeTrack(s))}),i.getTracks().length===0&&(e.srcObject=null,ye.log("set srcObject null")))}getPreviewElement(){if(this.isPreviewing)return this._previewElement}get isPreviewing(){return this._isPreviewing}}var B={},Lt={},Ft={exports:{}},Ti;function Nt(){if(Ti)return Ft.exports;Ti=1;var r=Ft.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return e.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return e.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return e.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=e.raddr!=null?" raddr %s rport %d":"%v%v",t+=e.tcptype!=null?" tcptype %s":"%v",e.generation!=null&&(t+=" generation %d"),t+=e["network-id"]!=null?" network-id %d":"%v",t+=e["network-cost"]!=null?" network-cost %d":"%v",t}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return e.attribute!=null&&(t+=" %s",e.value!=null&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return e.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(e.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=e.id!=null?"id=%s %s":"%v%s",t+=e.mediaClockValue!=null?"=%s":"",t+=e.rateNumerator!=null?" rate=%s":"",t+=e.rateDenominator!=null?"/%s":"",t}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};return Object.keys(r).forEach(function(e){var t=r[e];t.forEach(function(i){i.reg||(i.reg=/(.*)/),i.format||(i.format="%s")})}),Ft.exports}var Ei;function ku(){return Ei||(Ei=1,function(r){var e=function(o){return String(Number(o))===o?Number(o):o},t=function(o,u,c,d){if(d&&!c)u[d]=e(o[1]);else for(var h=0;h<c.length;h+=1)o[h+1]!=null&&(u[c[h]]=e(o[h+1]))},i=function(o,u,c){var d=o.name&&o.names;o.push&&!u[o.push]?u[o.push]=[]:d&&!u[o.name]&&(u[o.name]={});var h=o.push?{}:d?u[o.name]:u;t(c.match(o.reg),h,o.names,o.name),o.push&&u[o.push].push(h)},s=Nt(),n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);r.parse=function(o){var u={},c=[],d=u;return o.split(/(\r\n|\r|\n)/).filter(n).forEach(function(h){var p=h[0],l=h.slice(2);p==="m"&&(c.push({rtp:[],fmtp:[]}),d=c[c.length-1]);for(var f=0;f<(s[p]||[]).length;f+=1){var g=s[p][f];if(g.reg.test(l))return i(g,d,l)}}),u.media=c,u};var a=function(o,u){var c=u.split(/=(.+)/,2);return c.length===2?o[c[0]]=e(c[1]):c.length===1&&u.length>1&&(o[c[0]]=void 0),o};r.parseParams=function(o){return o.split(/;\s?/).reduce(a,{})},r.parseFmtpConfig=r.parseParams,r.parsePayloads=function(o){return o.toString().split(" ").map(Number)},r.parseRemoteCandidates=function(o){for(var u=[],c=o.split(" ").map(e),d=0;d<c.length;d+=3)u.push({component:c[d],ip:c[d+1],port:c[d+2]});return u},r.parseImageAttributes=function(o){return o.split(" ").map(function(u){return u.substring(1,u.length-1).split(",").reduce(a,{})})},r.parseSimulcastStreamList=function(o){return o.split(";").map(function(u){return u.split(",").map(function(c){var d,h=!1;return c[0]!=="~"?d=e(c):(d=e(c.substring(1,c.length)),h=!0),{scid:d,paused:h}})})}}(Lt)),Lt}var Vt,bi;function Pu(){if(bi)return Vt;bi=1;var r=Nt(),e=/%[sdv%]/g,t=function(a){var o=1,u=arguments,c=u.length;return a.replace(e,function(d){if(o>=c)return d;var h=u[o];switch(o+=1,d){case"%%":return"%";case"%s":return String(h);case"%d":return Number(h);case"%v":return""}})},i=function(a,o,u){var c=o.format instanceof Function?o.format(o.push?u:u[o.name]):o.format,d=[a+"="+c];if(o.names)for(var h=0;h<o.names.length;h+=1){var p=o.names[h];o.name?d.push(u[o.name][p]):d.push(u[o.names[h]])}else d.push(u[o.name]);return t.apply(null,d)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],n=["i","c","b","a"];return Vt=function(a,o){o=o||{},a.version==null&&(a.version=0),a.name==null&&(a.name=" "),a.media.forEach(function(h){h.payloads==null&&(h.payloads="")});var u=o.outerOrder||s,c=o.innerOrder||n,d=[];return u.forEach(function(h){r[h].forEach(function(p){p.name in a&&a[p.name]!=null?d.push(i(h,p,a)):p.push in a&&a[p.push]!=null&&a[p.push].forEach(function(l){d.push(i(h,p,l))})})}),a.media.forEach(function(h){d.push(i("m",r.m[0],h)),c.forEach(function(p){r[p].forEach(function(l){l.name in h&&h[l.name]!=null?d.push(i(p,l,h)):l.push in h&&h[l.push]!=null&&h[l.push].forEach(function(f){d.push(i(p,l,f))})})})}),d.join(`\r
57
+ `)+`\r
58
+ `},Vt}var ki;function xu(){if(ki)return B;ki=1;var r=ku(),e=Pu(),t=Nt();return B.grammar=t,B.write=e,B.parse=r.parse,B.parseParams=r.parseParams,B.parseFmtpConfig=r.parseFmtpConfig,B.parsePayloads=r.parsePayloads,B.parseRemoteCandidates=r.parseRemoteCandidates,B.parseImageAttributes=r.parseImageAttributes,B.parseSimulcastStreamList=r.parseSimulcastStreamList,B}var Ru=xu();const We=I(Ru);function Pi(r){return new Promise(e=>{setTimeout(e,r)})}async function Au(r,e={},t=0){const i=new AbortController;let s=!1;e=Object.assign({},e,{signal:i.signal});const n=[fetch(r,e)];t&&n.push(new Promise((a,o)=>{setTimeout(()=>{s||(o({httpCode:0,message:"Timeout"}),i.abort())},t)}));try{const a=await Promise.race(n);if(s=!0,!a.ok||a.status<200||a.status>=300)throw{httpCode:a.status,message:a.statusText};return a.json()}catch(a){throw s=!0,a}}async function xi(r,e={},t={}){const{timeout:i=0,retryDelay:s=0}=t;let{retryCount:n=0}=t;try{return await Au(r,e,i)}catch(a){if(n--,t.retryCount=n,n<0)throw a;return await Pi(s),await xi(r,e,t)}}function w(r,e){let t;return e.forEach(i=>{i.type===r&&(t=i)}),t}async function Ut(r,e){const t={},i=await(r==null?void 0:r.getStats()),s=await(e==null?void 0:e.getStats());return i&&(t.audio={mediaSource:w("media-source",i),codec:w("codec",i),candidatePair:w("candidate-pair",i),remoteCandidate:w("remote-candidate",i),localCandidate:w("local-candidate",i),track:w("track",i),outboundRtp:w("outbound-rtp",i),remoteInboundRtp:w("remote-inbound-rtp",i),transport:w("transport",i)}),s&&(t.video={mediaSource:w("media-source",s),codec:w("codec",s),candidatePair:w("candidate-pair",s),remoteCandidate:w("remote-candidate",s),localCandidate:w("local-candidate",s),track:w("track",s),outboundRtp:w("outbound-rtp",s),remoteInboundRtp:w("remote-inbound-rtp",s),transport:w("transport",s)}),t}async function wu(r,e,t){var d,h,p,l,f,g,_,T,b,v,j,R,Ps,xs,Rs,As,ws,Os,Is,Ms,Ds,Ls,Fs,Ns,Vs,Us,$s,Bs,js,zs,Gs,Hs,qs,Ws,Xs,Ks;const i=await Ut(e,t);await Pi(r);const s=await Ut(e,t),{audio:n,video:a}=i,{audio:o,video:u}=s,c={};if(n!=null&&n.codec&&(o!=null&&o.codec)){const Jt=((d=o.outboundRtp)==null?void 0:d.timestamp)-((h=n.outboundRtp)==null?void 0:h.timestamp),Yt=((p=o.outboundRtp)==null?void 0:p.bytesSent)-((l=n.outboundRtp)==null?void 0:l.bytesSent),Zt=((f=o.remoteInboundRtp)==null?void 0:f.packetsLost)-((g=n.remoteInboundRtp)==null?void 0:g.packetsLost),Qt=((_=o.outboundRtp)==null?void 0:_.packetsSent)-((T=n.outboundRtp)==null?void 0:T.packetsSent);c.audio={codec:o.codec.mimeType,channels:o.codec.channels,sendBitrate:Yt/Jt*8e3,packetsSent:(b=o.outboundRtp)==null?void 0:b.packetsSent,nackCount:(v=o.outboundRtp)==null?void 0:v.nackCount,packetsLost:(j=o.remoteInboundRtp)==null?void 0:j.packetsLost,packetsLostPercent:Zt/Qt}}if(a!=null&&a.codec&&(u!=null&&u.codec)){const Jt=((R=u.outboundRtp)==null?void 0:R.timestamp)-((Ps=a.outboundRtp)==null?void 0:Ps.timestamp),Yt=((xs=u.outboundRtp)==null?void 0:xs.bytesSent)-((Rs=a.outboundRtp)==null?void 0:Rs.bytesSent),Zt=((As=u.outboundRtp)==null?void 0:As.framesEncoded)-((ws=a.outboundRtp)==null?void 0:ws.framesEncoded),Qt=((Os=u.outboundRtp)==null?void 0:Os.totalEncodeTime)-((Is=a.outboundRtp)==null?void 0:Is.totalEncodeTime),Js=((Ms=u.outboundRtp)==null?void 0:Ms.packetsSent)-((Ds=a.outboundRtp)==null?void 0:Ds.packetsSent),nh=((Ls=u.outboundRtp)==null?void 0:Ls.totalPacketSendDelay)-((Fs=a.outboundRtp)==null?void 0:Fs.totalPacketSendDelay),oh=((Ns=u.remoteInboundRtp)==null?void 0:Ns.packetsLost)-((Vs=a.remoteInboundRtp)==null?void 0:Vs.packetsLost);c.video={codec:u.codec.mimeType,sendBitrate:Yt/Jt*8e3,frameWidth:(Us=u.outboundRtp)==null?void 0:Us.frameWidth,frameHeight:($s=u.outboundRtp)==null?void 0:$s.frameHeight,framesPerSecond:(Bs=u.outboundRtp)==null?void 0:Bs.framesPerSecond,framesEncoded:(js=u.outboundRtp)==null?void 0:js.framesEncoded,keyFramesEncoded:(zs=u.outboundRtp)==null?void 0:zs.keyFramesEncoded,framesSent:(Gs=u.outboundRtp)==null?void 0:Gs.frameHeight,frameEncodeAvgTime:Qt*1e3/Zt,packetsSent:(Hs=u.outboundRtp)==null?void 0:Hs.packetsSent,packetSendDelay:nh*1e3/Js,nackCount:(qs=u.outboundRtp)==null?void 0:qs.nackCount,firCount:(Ws=u.outboundRtp)==null?void 0:Ws.firCount,pliCount:(Xs=u.outboundRtp)==null?void 0:Xs.pliCount,packetsLost:(Ks=u.remoteInboundRtp)==null?void 0:Ks.packetsLost,packetsLostPercent:oh/Js}}return c}const D=new de("PCConnect");class Ou{constructor(e,t,i){this._pc=null,this._ms=new MediaStream,this._signalUrl="",this._videoTransceiver=null,this._audioTransceiver=null,this._opts=void 0,this._sessionId=Date.now(),this._signalUrl=e,this._opts=t,this._onConnectStateChange=i}get isPushing(){var e,t,i,s;return((t=(e=this._videoTransceiver)==null?void 0:e.sender)==null?void 0:t.track)||((s=(i=this._audioTransceiver)==null?void 0:i.sender)==null?void 0:s.track)}get pushUrl(){return this._signalUrl}get sessionId(){return this._sessionId}async publish(e,t){const i=new RTCPeerConnection,s=/Gecko/.test(navigator.userAgent)&&/Firefox/.test(navigator.userAgent);this._pc=i,this._bindRTCEvent();const n=e.filter(h=>(h==null?void 0:h.kind)==="audio")[0],a=e.filter(h=>(h==null?void 0:h.kind)==="video")[0];n&&this._ms.addTrack(n),a&&this._ms.addTrack(a),this._audioTransceiver=i.addTransceiver(n||"audio",{direction:"sendonly",sendEncodings:[{maxBitrate:t[0]}],streams:[this._ms]}),D.log("add track to pc,",n),this._videoTransceiver=i.addTransceiver(a||"video",{direction:"sendonly",sendEncodings:[{maxBitrate:t[1]}],streams:[this._ms]}),D.log("add track to pc,",a);const o=await i.createOffer();D.groupCollapsed("local offer"),D.log(o.sdp);const u=We.parse(o.sdp);u.media.filter(h=>h.type==="audio").forEach(h=>{var l;if(!s)return;const p=(l=h.rtp.filter(f=>f.codec==="opus")[0])==null?void 0:l.payload;p&&h.fmtp.forEach(f=>{f.payload===p&&(f.config="minptime=10;useinbandfec=1")})}),o.sdp=We.write(u),D.log("local offer modified"),D.log(o.sdp),await i.setLocalDescription(o);const c=await xi(this._signalUrl,{method:"POST",mode:"cors",body:JSON.stringify({sessionId:""+this._sessionId,version:"1.0-html",localSdp:o,metadata:{platform:"Web"}})},this._opts);if((c==null?void 0:c.code)!==200)throw{code:c.code,message:c.message};D.log("remote answer:"),D.log(c.remoteSdp.sdp);const d=We.parse(c.remoteSdp.sdp);d.media.forEach(h=>{var p;(p=h.fingerprint)!=null&&p.hash&&(h.fingerprint.hash=h.fingerprint.hash.toUpperCase())}),c.remoteSdp.sdp=We.write(d),D.log("remote answer modified"),D.log(c.remoteSdp.sdp),D.groupEnd(),await i.setRemoteDescription(c.remoteSdp)}async updatePublish(e,t){var n,a;let i;t==="video"?i=this._videoTransceiver:i=this._audioTransceiver;const s=(n=i==null?void 0:i.sender)==null?void 0:n.track;(s==null?void 0:s.id)!==(e==null?void 0:e.id)&&(await((a=i==null?void 0:i.sender)==null?void 0:a.replaceTrack(e)),D.log(`replace ${t} track done! ${s==null?void 0:s.label} -> ${e==null?void 0:e.label}`))}applyBitrate(e,t,i){var a,o,u;const s=t==="video"?(a=this._videoTransceiver)==null?void 0:a.sender:(o=this._audioTransceiver)==null?void 0:o.sender;if(!s)return;const n=s.getParameters();n.encodings=(u=n.encodings)!=null&&u.length?n.encodings:[{}],i?n.encodings[0].minBitrate=e:n.encodings[0].maxBitrate=e,s.setParameters(n),D.log(`set bitrate for ${t}, ${e} bps, min:${i}`)}unpublish(){var e,t;(e=this._pc)==null||e.getSenders().forEach(i=>{var s;(s=this._pc)==null||s.removeTrack(i)}),(t=this._pc)==null||t.close(),this._audioTransceiver=null,this._videoTransceiver=null,this._pc=null,D.log("close pc!")}getStats(){var e,t;return Ut((e=this._audioTransceiver)==null?void 0:e.sender,(t=this._videoTransceiver)==null?void 0:t.sender)}getStatsSnapshoot(e){var t,i;return wu(e||100,(t=this._audioTransceiver)==null?void 0:t.sender,(i=this._videoTransceiver)==null?void 0:i.sender)}_bindRTCEvent(){const e=this._pc;e==null||e.addEventListener("connectionstatechange",()=>{D.log("onconnectionstatechange:",e.connectionState),this._onConnectStateChange(e.connectionState)})}}var ue=(r=>(r.OnError="onerror",r.OnConnectClosed="onconnectclosed",r.OnFirstFramePushed="onfirstframepushed",r))(ue||{}),ie=(r=>(r.Video="video",r.Audio="audio",r))(ie||{}),V=(r=>(r.Init="init",r.AvExist="avexist",r.VideoFrame="videoframe",r.MockVideoEncode="mockvideoencode",r.AudioFrame="audioframe",r.AdjustBitrate="adjustbitrate",r.Publish="publish",r.UnPublish="unpublish",r.Download="download",r.GetStats="getstats",r.EncodeConfig="encodeconfig",r))(V||{}),he=(r=>(r.Ready="ready",r.Error="error",r.FirstFramePushed="firstframepushed",r.Flvfile="flvfile",r.STATS="stats",r.Close="close",r))(he||{}),$t={exports:{}},Ri;function Iu(){return Ri||(Ri=1,function(r){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(t=!1));function s(u,c,d){this.fn=u,this.context=c,this.once=d||!1}function n(u,c,d,h,p){if(typeof d!="function")throw new TypeError("The listener must be a function");var l=new s(d,h||u,p),f=t?t+c:c;return u._events[f]?u._events[f].fn?u._events[f]=[u._events[f],l]:u._events[f].push(l):(u._events[f]=l,u._eventsCount++),u}function a(u,c){--u._eventsCount===0?u._events=new i:delete u._events[c]}function o(){this._events=new i,this._eventsCount=0}o.prototype.eventNames=function(){var c=[],d,h;if(this._eventsCount===0)return c;for(h in d=this._events)e.call(d,h)&&c.push(t?h.slice(1):h);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(d)):c},o.prototype.listeners=function(c){var d=t?t+c:c,h=this._events[d];if(!h)return[];if(h.fn)return[h.fn];for(var p=0,l=h.length,f=new Array(l);p<l;p++)f[p]=h[p].fn;return f},o.prototype.listenerCount=function(c){var d=t?t+c:c,h=this._events[d];return h?h.fn?1:h.length:0},o.prototype.emit=function(c,d,h,p,l,f){var g=t?t+c:c;if(!this._events[g])return!1;var _=this._events[g],T=arguments.length,b,v;if(_.fn){switch(_.once&&this.removeListener(c,_.fn,void 0,!0),T){case 1:return _.fn.call(_.context),!0;case 2:return _.fn.call(_.context,d),!0;case 3:return _.fn.call(_.context,d,h),!0;case 4:return _.fn.call(_.context,d,h,p),!0;case 5:return _.fn.call(_.context,d,h,p,l),!0;case 6:return _.fn.call(_.context,d,h,p,l,f),!0}for(v=1,b=new Array(T-1);v<T;v++)b[v-1]=arguments[v];_.fn.apply(_.context,b)}else{var j=_.length,R;for(v=0;v<j;v++)switch(_[v].once&&this.removeListener(c,_[v].fn,void 0,!0),T){case 1:_[v].fn.call(_[v].context);break;case 2:_[v].fn.call(_[v].context,d);break;case 3:_[v].fn.call(_[v].context,d,h);break;case 4:_[v].fn.call(_[v].context,d,h,p);break;default:if(!b)for(R=1,b=new Array(T-1);R<T;R++)b[R-1]=arguments[R];_[v].fn.apply(_[v].context,b)}}return!0},o.prototype.on=function(c,d,h){return n(this,c,d,h,!1)},o.prototype.once=function(c,d,h){return n(this,c,d,h,!0)},o.prototype.removeListener=function(c,d,h,p){var l=t?t+c:c;if(!this._events[l])return this;if(!d)return a(this,l),this;var f=this._events[l];if(f.fn)f.fn===d&&(!p||f.once)&&(!h||f.context===h)&&a(this,l);else{for(var g=0,_=[],T=f.length;g<T;g++)(f[g].fn!==d||p&&!f[g].once||h&&f[g].context!==h)&&_.push(f[g]);_.length?this._events[l]=_.length===1?_[0]:_:a(this,l)}return this},o.prototype.removeAllListeners=function(c){var d;return c?(d=t?t+c:c,this._events[d]&&a(this,d)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,r.exports=o}($t)),$t.exports}var Mu=Iu();const Du=I(Mu);var Bt=(r=>(r[r.RTMP_INIT_FAIL=3e3]="RTMP_INIT_FAIL",r[r.AUDIO_ENCODER_INIT_FAIL=3001]="AUDIO_ENCODER_INIT_FAIL",r[r.AUDIO_RRNOISE_INIT_FAIL=3002]="AUDIO_RRNOISE_INIT_FAIL",r[r.AUDIO_ENCODE_FAIL=3003]="AUDIO_ENCODE_FAIL",r[r.VIDEO_ENCODE_CONFIGURE_FAIL=3004]="VIDEO_ENCODE_CONFIGURE_FAIL",r[r.VIDEO_ENCODE_FAIL=3005]="VIDEO_ENCODE_FAIL",r[r.WTP_OPEN_FAIL=3006]="WTP_OPEN_FAIL",r[r.WTP_CONNECT_FAIL=3007]="WTP_CONNECT_FAIL",r[r.WORKER_ERROR=3008]="WORKER_ERROR",r))(Bt||{});class Lu extends Error{constructor(e,t,i){super(),this.code=e,this.message=t,i&&(this.ext=i),this.toJson=()=>({code:this.code,message:this.message,ext:this.ext})}}function Ai(r,e,t){return new Lu(r,e,t)}const Te=class Te{constructor(e){this.group=(...t)=>{this._enabled&&console.group(`[${this._prefix}]: `,...t)},this.groupCollapsed=(...t)=>{this._enabled&&console.groupCollapsed(`[${this._prefix}]: `,...t)},this.groupEnd=()=>{this._enabled&&console.groupEnd()},this.log=(...t)=>{this._enabled&&console.log(`[${this._prefix}]: `,...t)},this.warn=(...t)=>{this._enabled&&console.warn(`[${this._prefix}]: `,...t)},this.error=(...t)=>{this._enabled&&console.error(`[${this._prefix}]: `,...t)},this.table=(...t)=>{this._enabled&&console.table(...t)},this._prefix=e}get _enabled(){return Te.enable}get _enableLong(){return Te.enableLong}get long(){return this._enableLong}};Te.enable=!1,Te.enableLong=!1;let se=Te;const U=new se("RTMP_Capture");class Fu{constructor(e){this._videoFirstframeCaptured=!1,this._audioFirstframeCaptured=!1,this._videoProcessorReader=null,this._audioProcessorReader=null,this._bridge=e}get audioTrack(){return this._bridge.audioMsTrack}get videoTrack(){return this._bridge.videoMsTrack}start(){this._startVideoCapture(),this._startAudioCapture()}restartCapture(e){if(U.log(`replace ${e} track`),e===ie.Video){if(this._videoProcessorReader){this._videoProcessorReader.cancel().finally(()=>{this._startVideoCapture()});return}this._startVideoCapture();return}if(this._audioProcessorReader){this._audioProcessorReader.cancel().finally(()=>{this._startAudioCapture()});return}this._startAudioCapture()}async _startVideoCapture(){var s;if(!this.videoTrack){U.log("no video track to capture");return}if(this.videoTrack.readyState!=="live"){U.warn("video track not live");return}const e=new MediaStreamTrackProcessor(this.videoTrack);e.track=this.videoTrack;const t=e.readable.getReader();this._videoProcessorReader=t,U.log("start capture video frame",this.videoTrack);let i;for(;;){i&&clearInterval(i),i=setTimeout(()=>{U.warn("long time no capture output"),this._bridge._postMockVideoEncodeFlag()},1500);const n=await t.read();if(clearInterval(i),this._videoFirstframeCaptured||(this._videoFirstframeCaptured=!0,U.log("video first frame captured")),n.done||!n.value){(s=n.value)==null||s.close();break}this._bridge._postVideoFrame(n.value,this.videoTrack.getSettings())}clearInterval(i),this._videoFirstframeCaptured=!1,this._videoProcessorReader=null,U.log("video track read done!",e.track)}async _startAudioCapture(){if(!this.audioTrack){U.log("no audio track to capture");return}if(this.audioTrack.readyState!=="live"){U.warn("audio track not live");return}const e=new MediaStreamTrackProcessor(this.audioTrack);e.track=this.audioTrack;const t=e.readable.getReader();for(this._audioProcessorReader=t,U.log("start capture audio frame");;){const i=await t.read();if(this._audioFirstframeCaptured||(this._audioFirstframeCaptured=!0,U.log("audio first frame captured")),i.done||!i.value)break;this._bridge._postAudioFrame(i.value,this.audioTrack.getSettings())}this._audioFirstframeCaptured=!1,this._audioProcessorReader=null,U.log("audio track read done!",e.track)}destroy(){var e,t;(e=this._audioProcessorReader)==null||e.cancel().catch(()=>{}),(t=this._videoProcessorReader)==null||t.cancel().catch(()=>{})}}const wi='(function(){"use strict";var l=(i=>(i.OnVideoCaptured="onvideocaptured",i.OnAudioCaptured="onaudiocaptured",i.OnVideoCaptureNoOutput="onvideocapturenooutput",i.OnVideoEncoded="onvideoencoded",i.OnAudioEncoded="onaudioencoded",i.OnEncodedFrame="onencodedframe",i.OnPacketed="onpacketed",i.OnUpstreamFeedback="onupstreamfeedback",i.OnBitrateChanged="onbitratechanged",i))(l||{}),O=(i=>(i.OnError="onerror",i.OnConnectClosed="onconnectclosed",i.OnFirstFramePushed="onfirstframepushed",i))(O||{}),S=(i=>(i.Video="video",i.Audio="audio",i))(S||{}),v=(i=>(i.Init="init",i.AvExist="avexist",i.VideoFrame="videoframe",i.MockVideoEncode="mockvideoencode",i.AudioFrame="audioframe",i.AdjustBitrate="adjustbitrate",i.Publish="publish",i.UnPublish="unpublish",i.Download="download",i.GetStats="getstats",i.EncodeConfig="encodeconfig",i))(v||{}),y=(i=>(i.Ready="ready",i.Error="error",i.FirstFramePushed="firstframepushed",i.Flvfile="flvfile",i.STATS="stats",i.Close="close",i))(y||{});function $(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var k={exports:{}},T;function q(){return T||(T=1,function(i){var t=Object.prototype.hasOwnProperty,e="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(e=!1));function n(u,a,r){this.fn=u,this.context=a,this.once=r||!1}function o(u,a,r,h,m){if(typeof r!="function")throw new TypeError("The listener must be a function");var g=new n(r,h||u,m),f=e?e+a:a;return u._events[f]?u._events[f].fn?u._events[f]=[u._events[f],g]:u._events[f].push(g):(u._events[f]=g,u._eventsCount++),u}function _(u,a){--u._eventsCount===0?u._events=new s:delete u._events[a]}function c(){this._events=new s,this._eventsCount=0}c.prototype.eventNames=function(){var a=[],r,h;if(this._eventsCount===0)return a;for(h in r=this._events)t.call(r,h)&&a.push(e?h.slice(1):h);return Object.getOwnPropertySymbols?a.concat(Object.getOwnPropertySymbols(r)):a},c.prototype.listeners=function(a){var r=e?e+a:a,h=this._events[r];if(!h)return[];if(h.fn)return[h.fn];for(var m=0,g=h.length,f=new Array(g);m<g;m++)f[m]=h[m].fn;return f},c.prototype.listenerCount=function(a){var r=e?e+a:a,h=this._events[r];return h?h.fn?1:h.length:0},c.prototype.emit=function(a,r,h,m,g,f){var w=e?e+a:a;if(!this._events[w])return!1;var d=this._events[w],F=arguments.length,V,p;if(d.fn){switch(d.once&&this.removeListener(a,d.fn,void 0,!0),F){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,r),!0;case 3:return d.fn.call(d.context,r,h),!0;case 4:return d.fn.call(d.context,r,h,m),!0;case 5:return d.fn.call(d.context,r,h,m,g),!0;case 6:return d.fn.call(d.context,r,h,m,g,f),!0}for(p=1,V=new Array(F-1);p<F;p++)V[p-1]=arguments[p];d.fn.apply(d.context,V)}else{var fe=d.length,R;for(p=0;p<fe;p++)switch(d[p].once&&this.removeListener(a,d[p].fn,void 0,!0),F){case 1:d[p].fn.call(d[p].context);break;case 2:d[p].fn.call(d[p].context,r);break;case 3:d[p].fn.call(d[p].context,r,h);break;case 4:d[p].fn.call(d[p].context,r,h,m);break;default:if(!V)for(R=1,V=new Array(F-1);R<F;R++)V[R-1]=arguments[R];d[p].fn.apply(d[p].context,V)}}return!0},c.prototype.on=function(a,r,h){return o(this,a,r,h,!1)},c.prototype.once=function(a,r,h){return o(this,a,r,h,!0)},c.prototype.removeListener=function(a,r,h,m){var g=e?e+a:a;if(!this._events[g])return this;if(!r)return _(this,g),this;var f=this._events[g];if(f.fn)f.fn===r&&(!m||f.once)&&(!h||f.context===h)&&_(this,g);else{for(var w=0,d=[],F=f.length;w<F;w++)(f[w].fn!==r||m&&!f[w].once||h&&f[w].context!==h)&&d.push(f[w]);d.length?this._events[g]=d.length===1?d[0]:d:_(this,g)}return this},c.prototype.removeAllListeners=function(a){var r;return a?(r=e?e+a:a,this._events[r]&&_(this,r)):(this._events=new s,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=e,c.EventEmitter=c,i.exports=c}(k)),k.exports}var z=q(),j=$(z);const N=class N{constructor(t){this.group=(...e)=>{this._enabled&&console.group(`[${this._prefix}]: `,...e)},this.groupCollapsed=(...e)=>{this._enabled&&console.groupCollapsed(`[${this._prefix}]: `,...e)},this.groupEnd=()=>{this._enabled&&console.groupEnd()},this.log=(...e)=>{this._enabled&&console.log(`[${this._prefix}]: `,...e)},this.warn=(...e)=>{this._enabled&&console.warn(`[${this._prefix}]: `,...e)},this.error=(...e)=>{this._enabled&&console.error(`[${this._prefix}]: `,...e)},this.table=(...e)=>{this._enabled&&console.table(...e)},this._prefix=t}get _enabled(){return N.enable}get _enableLong(){return N.enableLong}get long(){return this._enableLong}};N.enable=!1,N.enableLong=!1;let E=N;function D(i){i=i.filter(Boolean);const t=new Uint8Array(i.reduce((s,n)=>s+n.byteLength,0));let e=0;return i.forEach(s=>{t.set(s,e),e+=s.byteLength}),t}const A={codec:"avc1.4DE033",MaxCachedFrameSize:100,RealSpeedPercent:.8,UplinkBitrateCheckInterval:60*1e3,VideoBitrateDefault:1e6,AudioBitrateDefault:68e3,gopSize:90,sampleRate:48e3,channel:2,audioEncoderPath:"https://lf-unpkg.volccdn.com/obj/vcloudfe/sdk/Web_push/1.0.1/1735619140327/pcm2aac.js",audioEncoderWasmPath:"https://lf-unpkg.volccdn.com/obj/vcloudfe/sdk/Web_push/1.0.2/1735619208418/pcm2aac.wasm",rrnoiseAssetsPath:"https://sf1-cdn-tos.huoshanstatic.com/obj/media-fe/encoder/0.1.0",ignoreRelPublish:!1},U=new E("RTMP_AudioEncoder");class H{constructor(t){this._encodedFrameCount=0,this._ready=!1,this._lastFrame=null,this._aacOutput=(e,s)=>{const n=this._module.HEAPU8.subarray(e,e+s);if(!this._lastFrame)return;this._encodedFrameCount++;const{props:o}=this._lastFrame,_={buffer:new Uint8Array(n),props:{timestamp:parseInt(o.timestamp/1e3),originTs:parseInt(o.timestamp/1e3)}};this._core.emit(l.OnAudioEncoded,_)},this._core=t}async init(){const t=await fetch(A.audioEncoderPath).then(_=>_.text());new Function(`self.exports={};${t}`)();const e=self.exports.m;let s,n;const o=new Promise((_,c)=>{n=_,s=c});return e({instantiateWasm:function(_,c){fetch(A.audioEncoderWasmPath).then(u=>u.arrayBuffer()).then(u=>WebAssembly.instantiate(u,_)).then(function(u){return c(u.instance)}).then(()=>{n(),U.log("aac module inited")}).catch(u=>{s(u)})}}).then(_=>{const c=_.addFunction(this._aacOutput,"vii");_._init_callback(c),this._module=_}).catch(s),o}rnnoise(t){var s;const e=t.length;for(let n=0;n<e;n++)t[n]=t[n]*32768;(s=this._rnnoiseModule)==null||s.processFrame(t);for(let n=0;n<e;n++)t[n]=t[n]/32768}updateConfigure(){this._module._flush(),this._module._free_encoder(),this._ready=!1}encode(t){if(!this._ready){const o=this._start_encoder();if(o<0)throw new Error(`init aac encoder error, code:${o}`)}this._lastFrame=t;const e=t.buffer.buffer,s=this._module._malloc(e.byteLength);this._module.HEAPU8.subarray(s,s+e.byteLength).set(new Uint8Array(e));const n=this._module._encode_one_frame(s);if(n<0)throw new Error(`encode aac frame error, code:${n}`)}_start_encoder(){const t=this._core.getSetting(),e=this._module._init_encoder(t.sampleRate,t.channel,t.audioBitrate);if(e<0)return e;this._ready=!0,U.log(`init encoder: sampleRate=${t.sampleRate}, channel:${t.channel}, bitrate:${t.audioBitrate}`)}destroy(){var t;(t=this._module)==null||t._free_encoder()}}const P=1024;class M{constructor(){this._queue=[],this._sampleCount=0}compose(t){if(this._queue.push(t),this._sampleCount+=t.data.audioData.numberOfFrames,this._sampleCount>=P)return this._doCompose()}_doCompose(){const t=new Float32Array(P);let e=0,s=P;const n=this._queue[0];for(;;){const o=this._queue[0];if(!o)break;const _=Math.min(s,o.data.audioData.numberOfFrames-o.offset,480),c=o.data.buffer.slice(o.offset,o.offset+_);if(o.offset+=_,o.offset>=o.data.audioData.numberOfFrames&&this._queue.shift(),s-=_,this._sampleCount-=_,t.set(c,e),e+=_,s<=0)break}return{buffer:t,props:{timestamp:n.data.audioData.timestamp,sampleRate:n.data.audioData.sampleRate,numberOfChannels:n.data.audioData.numberOfChannels}}}}var C=(i=>(i[i.RTMP_INIT_FAIL=3e3]="RTMP_INIT_FAIL",i[i.AUDIO_ENCODER_INIT_FAIL=3001]="AUDIO_ENCODER_INIT_FAIL",i[i.AUDIO_RRNOISE_INIT_FAIL=3002]="AUDIO_RRNOISE_INIT_FAIL",i[i.AUDIO_ENCODE_FAIL=3003]="AUDIO_ENCODE_FAIL",i[i.VIDEO_ENCODE_CONFIGURE_FAIL=3004]="VIDEO_ENCODE_CONFIGURE_FAIL",i[i.VIDEO_ENCODE_FAIL=3005]="VIDEO_ENCODE_FAIL",i[i.WTP_OPEN_FAIL=3006]="WTP_OPEN_FAIL",i[i.WTP_CONNECT_FAIL=3007]="WTP_CONNECT_FAIL",i[i.WORKER_ERROR=3008]="WORKER_ERROR",i))(C||{});class W extends Error{constructor(t,e,s){super(),this.code=t,this.message=e,s&&(this.ext=s),this.toJson=()=>({code:this.code,message:this.message,ext:this.ext})}}function x(i,t,e){return new W(i,t,e)}class G{constructor(t){this._audioFrameQueue=new M,this.encode=e=>{const s=new Float32Array(e.numberOfFrames);e.copyTo(s,{planeIndex:0,frameOffset:0,frameCount:e.numberOfFrames});const n=this._audioFrameQueue.compose({offset:0,data:{audioData:e,buffer:s}});if(n)try{this._encoder.encode(n)}catch(o){this._core.emit(O.OnError,x(C.AUDIO_ENCODE_FAIL,o.message))}},this._core=t,this._encoder=new H(t)}async init(){try{await this._encoder.init()}catch(t){throw x(C.AUDIO_ENCODER_INIT_FAIL,t.message)}}setConfiguration(t){const e=Object.assign({},this._core.getSetting(),{audioBitrate:t});this._core.updateSetting(e),this._encoder.updateConfigure()}destroy(){this._encoder.destroy()}}const B=new E("RTMP_VEncoder");class J{constructor(t){this._encoder=null,this._queue=[],this._encodeTimer=0,this._loopEncodeTimer=0,this._frameIndex=0,this._gopSize=0,this._encodedFrameCount=0,this._lastFrame=null,this._startTimer=()=>{this._clearEncodeTimer(),this._encodeTimer=setInterval(()=>{const e=this._queue.shift();if(!(!e||!this._encoder||this._encoder.state==="closed"))try{this._encoder.encode(e,{keyFrame:this._frameIndex%this._gopSize===0}),this._frameIndex++,this._lastFrame&&this._lastFrame.close(),this._lastFrame=e}catch(s){B.log("encode frame error",s)}},5)},this._core=t}configurate(t){return this._gopSize=t.gopSize,this._encoder?this.flush().then(()=>this._configure(t)):this._configure(t)}_configure(t){return this._clearEncodeTimer(),B.log("start config encoder",t),VideoEncoder.isConfigSupported(t).then(e=>{if(!e.supported)throw new Error(`VideoEncoder not support config, ${JSON.stringify(t)}`);this._encoder=new VideoEncoder({output:(s,n)=>{const o=new Uint8Array(s.byteLength);s.copyTo(o),this._emitFrame(o,s,n)},error:s=>{this._clearEncodeTimer(),this._core.emit(O.OnError,x(C.VIDEO_ENCODE_FAIL,s.message))}}),this._encoder.configure(t),B.log("encoder configured")}).then(this._startTimer).catch(e=>{throw x(C.VIDEO_ENCODE_CONFIGURE_FAIL,e.message)})}_emitFrame(t,e,s){this._encodedFrameCount++,this._core.emit(l.OnVideoEncoded,{buffer:t,props:{byteLength:e.byteLength,duration:e.duration,timestamp:parseInt(e.timestamp/1e3),originTs:parseInt(e.timestamp/1e3),type:e.type},cfg:s.decoderConfig})}_clearEncodeTimer(){clearInterval(this._encodeTimer)}_clearLoopEncodeTimer(){this._loopEncodeTimer&&clearInterval(this._loopEncodeTimer)}flush(){return this._encoder?this._encoder.flush().then(()=>{var t;this._clearEncodeTimer(),(t=this._encoder)==null||t.close(),this._frameIndex=0,this._encoder=null,B.log("encoder flush & closed")}).catch(t=>{console.log("encoder flush & close error:",t)}):Promise.resolve()}encode(t){this._clearLoopEncodeTimer(),this._queue.push(t)}startLoop(t){if(!this._lastFrame)return;const e=Math.floor(1e3/t*1e3);B.log("start encode last frame looped, ",t,"increment:",e),this._loopEncodeTimer=setInterval(()=>{if(!this._lastFrame)return;const s=new VideoFrame(this._lastFrame,{duration:e,timestamp:(this._lastFrame.timestamp||0)+e});this._queue.push(s)},Math.floor(1e3/t))}destroy(){this._queue.forEach(t=>t.close()),this._lastFrame&&this._lastFrame.close(),this._clearEncodeTimer(),this._clearLoopEncodeTimer(),this.flush()}}const Q=new E("RTMP_VideoEncode");class K{constructor(t){this._core=t,this._encoder=new J(t)}async setConfiguration(t={}){const e=Object.assign({},this._core.getSetting(),t),s={width:e.width,height:e.height,displayWidth:e.width,displayHeight:e.height,bitrate:e.videoBitrate,framerate:Math.floor(e.frameRate),codec:e.codec,gopSize:e.gopSize,hardwareAcceleration:e.hardwareAcceleration};this._core.updateSetting(e),Q.log("set Configuration:",s,t);try{await this._encoder.configurate(s)}catch(n){this._core.emit(O.OnError,n)}}encode(t){this._encoder.encode(t)}startLoopEncodeLastFrame(){this._encoder.startLoop(this._core.getSetting().frameRate)}flushEncoder(){this._encoder.flush()}destroy(){this._encoder.destroy()}}const I=new E("RTMP_AVSync");class Z{constructor(t){this._videoFrameGot=!1,this._videoBaseDts=0,this._audioBaseDts=0,this._videoNextDts=0,this._videoLastDts=0,this._audioNextDts=0,this._lastVideoReceived=0,this._core=t}get avExist(){return this._core.getSetting().hasVideo&&this._core.getSetting().hasAudio}get videoRefDuration(){return parseInt(1e3/this._core.getSetting().frameRate)}get audioRefDuration(){return parseInt(1024/this._core.getSetting().sampleRate*1e3)}addVideoFrame(t){this._videoFrameGot||(this._videoFrameGot=!0);const e=t.props;if(Math.abs(this._videoNextDts-e.timestamp-this._videoBaseDts)>1e3){const n=Date.now()-this._lastVideoReceived;this._videoNextDts=this._videoNextDts===this._audioNextDts?this._videoNextDts+this.videoRefDuration:this._audioNextDts||this._videoNextDts+n,this._videoBaseDts=this._videoNextDts-e.timestamp,I.warn(`video stream timestamp breaked! dts:${this._videoNextDts} -> ${e.timestamp}, videoBaseDts=${this._videoBaseDts}, deltaToLastFrame=${n}`)}e.timestamp=e.timestamp+this._videoBaseDts;const s=e.timestamp-this._videoLastDts;return s>100&&I.warn("video frame large gap",s),this._videoLastDts=this._videoNextDts=e.timestamp,I.long&&I.log(`V frame, dts: ${e.timestamp}, originDts:${e.originTs}, videoBaseDts=${this._videoBaseDts}, type=${e.type}, duration=${s}`),this._lastVideoReceived=Date.now(),this._core.emit(l.OnEncodedFrame,S.Video,t),{size:t.buffer.length,duration:s,key:t.props.type==="key"}}addAudioFrame(t){if(this.avExist&&!this._videoFrameGot)return;const e=t.props;return this._audioBaseDts||(this._audioBaseDts=e.timestamp-this._videoNextDts),Math.abs(e.timestamp-this._audioBaseDts-this._audioNextDts)>1e3&&(this._audioBaseDts=this._audioNextDts+this.audioRefDuration-e.timestamp,I.warn(`audio stream timestamp breaked! dts:${this._audioNextDts} -> ${e.timestamp}, audioBaseDts=${this._audioBaseDts}`)),this._audioNextDts=e.timestamp=e.timestamp-this._audioBaseDts,I.long&&I.log(`A frame, dts: ${e.timestamp}, originDts:${e.originTs}`),this._core.emit(l.OnEncodedFrame,S.Audio,t),{size:t.buffer.length,duration:this.audioRefDuration}}}class X{constructor(){this._videoSize=0,this._videoDuration=0,this._videoBitrate=0,this._frameCount=0,this._fps=0,this._videoEncodedCount=0,this._keyCount=0,this._audioSize=0,this._audioDuration=0,this._audioBitrate=0,this._audioEncodedCount=0}get videoStats(){return{sendBitrate:this._videoBitrate,framesPerSecond:this._fps,framesEncoded:this._videoEncodedCount,keyFramesEncoded:this._keyCount}}get audioStats(){return{sendBitrate:this._audioBitrate,framesEncoded:this._audioEncodedCount}}addVideoSample({size:t,duration:e,key:s}){this._videoEncodedCount++,this._videoSize+=t,this._videoDuration+=e,this._frameCount++,s&&this._keyCount++,this._videoDuration>=1e3&&(this._videoBitrate=Math.floor(this._videoSize/this._videoDuration*8e3),this._fps=this._frameCount,this._frameCount=0,this._videoSize=0,this._videoDuration=0)}addAudioSample({size:t,duration:e}){this._audioEncodedCount++,this._audioSize+=t,this._audioDuration+=e,this._audioDuration>=1e3&&(this._audioBitrate=Math.floor(this._audioSize/this._audioDuration*1e3),this._audioSize=0,this._audioDuration=0)}}const Y=new E("RTMP_EncodeController");class ee{constructor(t){this._analyse=new X,this._gotFrame=!1,this._OnVideoCaptured=(e,s)=>{this._gotFrame=!0,this._videoSettingChanged(s)&&(Y.log("video track setting changed!",s),this._core.updateSetting({width:s.width,height:s.height,frameRate:s.frameRate,vDeviceId:s.deviceId}),this._videoEncode.setConfiguration()),this._videoEncode.encode(e)},this._OnVideoCaptureNoOutput=()=>{this._videoEncode.startLoopEncodeLastFrame()},this._OnAudioCaptured=e=>{this._gotFrame=!0,this._audioEncode.encode(e)},this._OnVideoEncoded=e=>{const s=this._avSync.addVideoFrame(e);this._analyse.addVideoSample(s)},this._OnAudioEncoded=e=>{if(!e.buffer.length)return;const s=this._avSync.addAudioFrame(e);s&&this._analyse.addAudioSample(s)},this._OnUpstreamFeedback=e=>{this._videoEncode.setConfiguration(e)},this._OnBitrateChanged=(e,s)=>{this._gotFrame&&(e===S.Video&&this._videoEncode.setConfiguration({videoBitrate:s}),e===S.Audio&&this._audioEncode.setConfiguration(s))},this._core=t,this._audioEncode=new G(t),this._videoEncode=new K(t),this._avSync=new Z(t),this._bindEvents()}getStats(){return{video:this._analyse.videoStats,audio:this._analyse.audioStats}}init(){return this._audioEncode.init()}_bindEvents(){this._core.on(l.OnVideoCaptured,this._OnVideoCaptured),this._core.on(l.OnAudioCaptured,this._OnAudioCaptured),this._core.on(l.OnVideoCaptureNoOutput,this._OnVideoCaptureNoOutput),this._core.on(l.OnVideoEncoded,this._OnVideoEncoded),this._core.on(l.OnAudioEncoded,this._OnAudioEncoded),this._core.on(l.OnUpstreamFeedback,this._OnUpstreamFeedback),this._core.on(l.OnBitrateChanged,this._OnBitrateChanged)}_videoSettingChanged(t){const e=this._core.getSetting();return t.width!==e.width||t.height!==e.height||Math.floor(t.frameRate)!==Math.floor(e.frameRate)||t.deviceId!==e.vDeviceId}destroy(){this._videoEncode.destroy(),this._audioEncode.destroy()}}var L=(i=>(i[i.AUDIO=8]="AUDIO",i[i.VIDEO=9]="VIDEO",i[i.SCRIPT_DATA=18]="SCRIPT_DATA",i))(L||{});const te=10,ie=1,se=7,oe={96e3:0,48e3:3,44100:4,22050:7,16e3:8,8e3:11};function ne(i){const t=(i[4]&3)+1;let e;const s=[],n=[];let o=6;const _=i[5]&31;let c;for(let r=0;r<_;r++){if(c=i[o]<<8|i[o+1],o+=2,!c)continue;const h=i.subarray(o,o+c);o+=c,s.push(h)}const u=i[o];o++;let a;for(let r=0;r<u;r++)a=i[o]<<8|i[o+1],o+=2,a&&(n.push(i.subarray(o,o+a)),o+=a);return{sps:e,spsArr:s,ppsArr:n,nalUnitSize:t}}class re{constructor(){this._cfg={hasVideo:!1,hasAudio:!1,sampleRate:48e3,channelCount:1},this._hasAudioSeqHeader=!1,this._hasVideoSeqHeader=!1}setConfig(t){this._cfg=Object.assign(this._cfg,t)}genHeader(){const t=[70,76,86,1,(this._cfg.hasAudio?1:0)<<2|(this._cfg.hasVideo?1:0),0,0,0,9,0,0,0,0];return new Uint8Array(t)}genSeqTag(t,e){let s;t===8?(s=this._genAudioTagPaylod(0,e),this._hasAudioSeqHeader=!0):(s=this._genVideoTagPayload(0,e),this._hasVideoSeqHeader=!0);const n=this._genTagHeader(t,s.length,e.props.timestamp),o=n.length+s.length;return D([n,s,new Uint8Array([o>>>24,o>>>16,o>>>8,o])])}genFrameTag(t,e){let s;t===8?s=this._genAudioTagPaylod(1,e):s=this._genVideoTagPayload(1,e);const n=this._genTagHeader(t,s.length,e.props.timestamp),o=n.length+s.length;return D([n,s,new Uint8Array([o>>>24,o>>>16,o>>>8,o])])}_genTagHeader(t,e,s){return new Uint8Array([t,e>>>16,e>>>8,e,s>>>16,s>>>8,s,s>>>24,0,0,0])}_genAudioTagPaylod(t,e){return D(t===0?[this._genAudioTagHeader(),this._genAudioSequenceHeader()]:[this._genAudioTagHeader(),this._genAudioData(e)])}_genAudioTagHeader(){return new Uint8Array([te<<4|12|ie<<1|this._cfg.channelCount-1])}_genAudioSequenceHeader(){const t=4096|oe[this._cfg.sampleRate]<<7|this._cfg.channelCount<<3;return new Uint8Array([0,t>>8,t])}_genAudioData(t){const e=new Uint8Array(1+t.buffer.length);return e.set([1],0),e.set(t.buffer,1),e}_genVideoTagPayload(t,e){return D(t===0?[this._genVideoTagHeader(e),this._genVideoSequenceHeader(e)]:[this._genVideoTagHeader(e),this._genVideoData(e)])}_genVideoTagHeader(t){return new Uint8Array([(t.props.type==="key"?1:2)<<4|se,this._hasVideoSeqHeader?1:0,0,0,0])}_genVideoSequenceHeader(t){return new Uint8Array(t.cfg.description)}_genVideoData(t){if(t.props.type==="delta")return t.buffer;const e=ne(new Uint8Array(t.cfg.description)),s=e.spsArr[0].length,n=e.ppsArr[0].length;return D([new Uint8Array([0,0,s>>8,s%256]),e.spsArr[0],new Uint8Array([0,0,n>>8,n%256]),e.ppsArr[0],t.buffer])}}const ae=new E("RTMP_Packet");class de{constructor(t){this._firstFrame=!0,this._flv=new re,this._OnEncodedFrame=(e,s)=>{if(this._firstFrame){const o=this._core.getSetting();this._flv.setConfig({hasVideo:o.hasVideo,hasAudio:o.hasAudio,sampleRate:o.sampleRate,channelCount:o.channel});const _=this._flv.genHeader();if(this._core.emit(l.OnPacketed,_),o.hasVideo){const c=this._flv.genSeqTag(L.VIDEO,s);this._core.emit(l.OnPacketed,c)}if(o.hasAudio){const c=this._flv.genSeqTag(L.AUDIO,s);this._core.emit(l.OnPacketed,c)}this._firstFrame=!1,ae.log("first frame encoded & packed")}const n=this._flv.genFrameTag(e==="video"?L.VIDEO:L.AUDIO,s);this._core.emit(l.OnPacketed,n,s.props.type==="key")},this._core=t,this._bindEvents()}_bindEvents(){this._core.on(l.OnEncodedFrame,this._OnEncodedFrame)}destroy(){}}class he{constructor(){this._lastDot=0,this._totalSize=0,this._speed=[]}addSample(t){this._lastDot||(this._lastDot=Date.now()),this._totalSize+=t;const e=Date.now()-this._lastDot;e>=500&&(this._addSpeedSample(this._totalSize/e*8e3),this._totalSize=0,this._lastDot=Date.now())}_addSpeedSample(t){this._speed.push(t),this._speed=this._speed.slice(-6)}reset(){this._speed=[]}getUpSpeed(){return this._speed.length?parseInt(this._speed.reduce((t,e)=>t+=e,0)/this._speed.length):0}}const b=new E("RTMP_Wtp");class ce{constructor(t){this._queue=[],this._url="",this._connectClosed=!1,this._upSpeed=new he,this._transport=null,this._writer=null,this._inWriting=!1,this._inAdjustEncode=!1,this._increaseTimer=0,this._firstFramePushed=!1,this._core=t,this._bindEvents()}get sendSpeed(){return this._upSpeed.getUpSpeed()}getStats(){var t;return(t=this._transport)==null?void 0:t.getStats()}_bindEvents(){this._core.on(l.OnPacketed,(t,e=!1)=>{this._checkDecreaseBitrate(),this._checkDeleteCache(e),this._queue.push(t),this._inWriting||this._write()})}_checkDecreaseBitrate(){if(this._inAdjustEncode)return;const t=this._upSpeed.getUpSpeed();if(!t||this._queue.length<A.MaxCachedFrameSize)return;b.log(`up speed: ${t} low, ajust encode setting`);const e=this._core.getSetting();this._core.emit(l.OnUpstreamFeedback,{videoBitrate:t*A.RealSpeedPercent,width:e.width,height:e.height,frameRate:e.frameRate}),this._inAdjustEncode=!0,this._checkIncreaseBitrate()}_checkIncreaseBitrate(){b.log("add timer to check uplink speed increased"),clearInterval(this._increaseTimer),this._increaseTimer=setTimeout(()=>{const t=this._core.getSetting();b.log(`set encode bitrate to specified ${t.videoBitrate}`),this._core.emit(l.OnUpstreamFeedback,{videoBitrate:t.videoBitrate,width:t.width,height:t.height,frameRate:t.frameRate}),this._inAdjustEncode=!0},A.UplinkBitrateCheckInterval)}_checkDeleteCache(t){this._inAdjustEncode&&t&&(b.log(`ajust encode setting finish, delete cached ${this._queue.length} frame`),this._queue=[],this._upSpeed.reset(),this._inAdjustEncode=!1)}async start(t){this._url=t;try{await this._connect()}catch(e){throw x(C.WTP_OPEN_FAIL,e.message)}}async _connect(){const t=new WebTransport(this._url);let e;t.closed.then(()=>{b.log("webtransport closed")}).catch(n=>{e=n.message,b.log("webtransport closed due to",n)}).finally(()=>{this._connectClosed=!0,this._core.emit(O.OnConnectClosed,e),this._core.emit(O.OnError,x(C.WTP_CONNECT_FAIL,e))}),await t.ready,this._transport=t;const s=await t.createBidirectionalStream();this._writer=s.writable.getWriter(),this._write(),b.log("transport opend")}async _write(){var e;if(!this._writer)return;this._inWriting=!0;const t=this._queue.shift();if(!t){this._inWriting=!1;return}await((e=this._writer)==null?void 0:e.write(t)),this._firstFramePushed||(this._firstFramePushed=!0,this._core.emit(O.OnFirstFramePushed),b.log("first frame pushed")),this._upSpeed.addSample(t.length);try{await this._write()}catch(s){b.log("writer error:",s)}}getFile(){return D(this._queue)}destroy(){var t,e;clearTimeout(this._increaseTimer),this._connectClosed||(t=this._writer)==null||t.close(),this._writer=null,(e=this._transport)==null||e.close(),this._transport=null}}const ue=new E("LiveRTMP");class _e extends j{constructor(){super(),this._ts=0,this._setting={codec:A.codec,hardwareAcceleration:"prefer-hardware",width:-1,height:-1,frameRate:-1,sampleRate:A.sampleRate,channel:A.channel,gopSize:A.gopSize,videoBitrate:A.VideoBitrateDefault,audioBitrate:A.AudioBitrateDefault,hasAudio:!1,hasVideo:!1,vDeviceId:"",aDeviceId:""},this._encode=new ee(this),this._packet=new de(this),this._transport=new ce(this)}ready(){return this._encode.init()}getSetting(){return this._setting}updateSetting(t){this._setting=Object.assign({},this._setting,t)}videoFrameCaptured(t,e){this.emit(l.OnVideoCaptured,t,e)}audioFrameCaptured(t,e){this.emit(l.OnAudioCaptured,t,e)}startMockVideoEncode(){this.emit(l.OnVideoCaptureNoOutput)}adjustBitrate(t,e){t===S.Video&&this.updateSetting({videoBitrate:e}),t===S.Audio&&this.updateSetting({audioBitrate:e}),this.emit(l.OnBitrateChanged,t,e)}avExist(t,e){this._setting.hasVideo=t,this._setting.hasAudio=e}publish(t){return this._transport.start(t)}setEncodeCapacity(t){this._setting=Object.assign({},this._setting,t)}getStats(){return{video:{...this._encode.getStats().video,sendSpeed:this._transport.sendSpeed,codec:this._setting.codec,frameWidth:this._setting.width,frameHeight:this._setting.height,gopSize:this._setting.gopSize},audio:{...this._encode.getStats().audio,codec:"aac",channels:this._setting.channel,sampleRate:this._setting.sampleRate}}}destroy(){ue.log("destroy"),this._encode.destroy(),this._packet.destroy(),this._transport.destroy()}down(){return this._transport.getFile()}}self.constructor.name!=="Window"&&le();function le(){let i={};self.addEventListener("message",async t=>{switch(t.data.type){case v.Init:{const{options:e}=t.data;e.logEnable&&(E.enable=!0),e.logEnableLong&&(E.enableLong=!0),i=new _e,i.on(O.OnError,s=>{self.postMessage({type:y.Error,data:s.toJson()})}),i.on(O.OnConnectClosed,()=>{self.postMessage({type:y.Close})}),i.on(O.OnFirstFramePushed,()=>{self.postMessage({type:y.FirstFramePushed})});try{await i.ready(),self.postMessage({type:y.Ready})}catch(s){self.postMessage({type:y.Error,data:s.toJson()})}}break;case v.AvExist:{const{hasAudio:e,hasVideo:s}=t.data;i.avExist(s,e)}break;case v.VideoFrame:{const{frame:e,setting:s}=t.data;i.videoFrameCaptured(e,s)}break;case v.MockVideoEncode:i.startMockVideoEncode();break;case v.AudioFrame:{const{frame:e,setting:s}=t.data;i.audioFrameCaptured(e,s)}break;case v.AdjustBitrate:{const{kind:e,bitrate:s}=t.data;i.adjustBitrate(e,s)}break;case v.Publish:{const{url:e}=t.data;try{await i.publish(e)}catch(s){self.postMessage({type:y.Error,data:s.toJson()})}}break;case v.GetStats:self.postMessage({type:y.STATS,data:i.getStats()});break;case v.EncodeConfig:{i.setEncodeCapacity(t.data.cfg);break}case v.Download:{const e=i.down();self.postMessage({type:y.Flvfile,buffer:e},[e.buffer])}break;case v.UnPublish:{i.destroy();break}}})}})();\n',Oi=typeof self<"u"&&self.Blob&&new Blob([wi],{type:"text/javascript;charset=utf-8"});function Nu(r){let e;try{if(e=Oi&&(self.URL||self.webkitURL).createObjectURL(Oi),!e)throw"";const t=new Worker(e,{name:r==null?void 0:r.name});return t.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),t}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(wi),{name:r==null?void 0:r.name})}finally{e&&(self.URL||self.webkitURL).revokeObjectURL(e)}}try{se.enable=location.href.indexOf("rtmpdebug")!==-1,se.enableLong=location.href.indexOf("rtmpdebug=long")!==-1}catch{}const Xe=new se("Bridge");class Ii extends Du{constructor(){super(),this._worker=null,this._audioMsTrack=null,this._videoMsTrack=null,this._capture=new Fu(this)}static isSupported(){return typeof WebTransport<"u"&&typeof MediaStreamTrackProcessor<"u"&&typeof MediaStreamTrackGenerator<"u"&&typeof VideoEncoder<"u"}get audioMsTrack(){return this._audioMsTrack}get videoMsTrack(){return this._videoMsTrack}async ready(){var n,a;let e,t;const i=new Promise((o,u)=>{e=o,t=u}),s=o=>{var u;switch((u=this._worker)==null||u.removeEventListener("message",s),o.data.type){case he.Error:t(o.data.data);break;default:this._bindWorkerEvent(),Xe.log("rtmp ready!"),e(!0)}};try{this._worker=new Nu}catch(o){t(Ai(Bt.RTMP_INIT_FAIL,o.message))}return(n=this._worker)==null||n.postMessage({type:V.Init,options:{logEnable:se.enable,logEnableLong:se.enableLong}}),(a=this._worker)==null||a.addEventListener("message",s),i}_bindWorkerEvent(){var e,t;(e=this._worker)==null||e.addEventListener("message",i=>{switch(i.data.type){case he.Error:Xe.table(i.data.data),this.emit(ue.OnError,i.data.data);break;case he.Flvfile:Vu(i.data.buffer);break;case he.FirstFramePushed:this.emit(ue.OnFirstFramePushed);break;case he.Close:this.emit(ue.OnConnectClosed),this.destroy();break}}),(t=this._worker)==null||t.addEventListener("error",i=>{this.emit(ue.OnError,Ai(Bt.WORKER_ERROR,i.message))})}addTrack(e){e.kind===ie.Video&&(this._videoMsTrack=e),e.kind===ie.Audio&&(this._audioMsTrack=e),this._setAVExist(!!this._videoMsTrack,!!this._audioMsTrack)}replaceTrack(e,t){e===ie.Video&&(this._videoMsTrack=t),e===ie.Audio&&(this._audioMsTrack=t),this._setAVExist(!!this._videoMsTrack,!!this._audioMsTrack),this._capture.restartCapture(e)}async getStats(){var n,a;let e,t;const i=new Promise((o,u)=>{e=o,t=u});this._worker||setTimeout(()=>{t()},0);const s=o=>{var u;switch(o.data.type){case he.STATS:e(o.data.data),(u=this._worker)==null||u.removeEventListener("message",s);break}};return(n=this._worker)==null||n.addEventListener("message",s),(a=this._worker)==null||a.postMessage({type:V.GetStats}),i}_postVideoFrame(e,t){var i;(i=this._worker)==null||i.postMessage({type:V.VideoFrame,frame:e,setting:t},[e])}_postMockVideoEncodeFlag(){var e;(e=this._worker)==null||e.postMessage({type:V.MockVideoEncode})}_setAVExist(e,t){var i;(i=this._worker)==null||i.postMessage({type:V.AvExist,hasVideo:e,hasAudio:t})}_postAudioFrame(e,t){var i;(i=this._worker)==null||i.postMessage({type:V.AudioFrame,frame:e,setting:t},[e])}setEncodeCapacity(e){var t;(t=this._worker)==null||t.postMessage({type:V.EncodeConfig,cfg:e})}adjustBitrate(e,t){var i;(i=this._worker)==null||i.postMessage({type:V.AdjustBitrate,kind:e,bitrate:t})}publish(e){var t;Xe.log("start capture & connect"),this._capture.start(),(t=this._worker)==null||t.postMessage({type:V.Publish,url:e})}unpublish(){var e;this._capture.destroy(),(e=this._worker)==null||e.postMessage({type:V.UnPublish})}destroy(){var e;Xe.log("destroy capture & rtmp worker"),this._capture.destroy(),(e=this._worker)==null||e.terminate(),this._worker=null}download(){var e;(e=this._worker)==null||e.postMessage({type:V.Download})}}function Vu(r){const e=document.createElement("a");e.href=URL.createObjectURL(new Blob([r])),e.download=Date.now()+".flv",e.click()}const Mi=new de("RTMPConnect");class Uu{constructor(e,t,i,s){this._opts=void 0,this._isPushing=!1,this._url=e,this._opts=t,this._onError=i,this._OnSuccess=s,this._rtmp=new Ii,this._bindEvents()}get isPushing(){return this._isPushing}get pushUrl(){return this._url}get sessionId(){return 0}_bindEvents(){this._rtmp.on(ue.OnError,e=>{this._isPushing=!1,this._onError(e)}),this._rtmp.on(ue.OnFirstFramePushed,()=>{this._isPushing=!0,this._OnSuccess()})}async publish(e,t,i){await this._rtmp.ready(),i&&this._rtmp.setEncodeCapacity(i),e.filter(Boolean).forEach(s=>this._rtmp.addTrack(s)),t[0]&&this._rtmp.adjustBitrate(ie.Audio,t[0]),t[1]&&this._rtmp.adjustBitrate(ie.Video,t[1]),this._rtmp.publish(this._url)}updatePublish(e,t){Mi.log(`replace track to ${e==null?void 0:e.label}`),this._rtmp.replaceTrack(t,e)}applyBitrate(e,t){this._rtmp.adjustBitrate(t,e)}async getStats(){return this._rtmp.getStats()}async getStatsSnapshoot(){return this._rtmp.getStats()}unpublish(){Mi.warn("unpublish"),this._rtmp.unpublish(),this._isPushing=!1}}const $u=new de("PushController");class Bu extends Si{constructor(e,{config:t,streamConsumeController:i}){super(e),this._connect=null,this._pushMode="rtm",this._pushConfig={timeout:5e3,retryCount:1,retryDelay:1e3},this._audioBitrate=ve(or,"audio").bitrate,this._videoBitrate=ve(nr,"video").bitrate,this.handleAudioStreamChange=s=>{this.updatePush({audioTrack:s.audioTrack})},this.handleVideoStreamChange=s=>{this.updatePush({videoTrack:s.videoTrack})},this._OnRTMPSuccess=()=>{this._streamConsumeController.emit(A.PushStart)},this._OnRTMPError=s=>{const n=new Ie(N.PUBLISH_FAILED,`code:${s.code}, message: ${s.message}`);this._streamConsumeController.emit(A.PushError,n),this.unpublish()},this._OnRtcStateChange=s=>{if(s==="failed"){this.unpublish();const n=new Ie(N.PUSH_CONNECT_FAILED,"pc disconnect");this._streamConsumeController.emit(A.PushError,n)}s==="connected"&&this._streamConsumeController.emit(A.PushStart),this._streamConsumeController.emit(A.RTCConnectStateChanged,s)},this._pushMode=(t==null?void 0:t.mode)||"rtm",this._streamConsumeController=i,t&&(this._pushConfig=t)}get isPushing(){var e;return!!((e=this._connect)!=null&&e.isPushing)}get pushUrl(){var e;return((e=this._connect)==null?void 0:e.pushUrl)||""}get sessionId(){var e;return((e=this._connect)==null?void 0:e.sessionId)||0}start(){this.bindComposedStreamEvent()}stop(){this.unbindComposedStreamEvent()}setPushConfig(e){e&&(this._pushConfig=e)}async getStats(e=2e3){var t;return(t=this._connect)==null?void 0:t.getStatsSnapshoot(e)}async startPush(e,t){if(!e)throw new Error("lack publish url");if(this._connect)return;this.start();const i=this._composedStream.videoTrack,s=this._composedStream.audioTrack;if(!i&&!s)return;let n;this._pushMode==="rtm"?n=new Ou(e,this._pushConfig,this._OnRtcStateChange):n=new Uu(e,this._pushConfig,this._OnRTMPError,this._OnRTMPSuccess),this._connect=n;try{await n.publish([s,i],[this._audioBitrate,this._videoBitrate],t)}catch(a){$u.groupEnd(),n.unpublish();const o=new Ie(N.PUBLISH_FAILED,a.message,a);this._streamConsumeController.emit(A.PushError,o)}}async updatePush({videoTrack:e,audioTrack:t}){if(this._connect)try{const i=[];e&&i.push(()=>{var s;return(s=this._connect)==null?void 0:s.updatePublish(e,"video")}),t&&i.push(()=>{var s;return(s=this._connect)==null?void 0:s.updatePublish(t,"audio")}),await Promise.all(i.map(s=>s()))}catch(i){const s=new Ie(N.UPDATE_PUBLISH_FAILED,`${i.name}, code:${i.code}`);this._streamConsumeController.emit(A.PushError,s)}}unpublish(){var e;(e=this._connect)==null||e.unpublish(),this._connect=null,this._streamConsumeController.emit(A.PushStop)}async destroy(){this._connect&&await this.unpublish(),this.unbindComposedStreamEvent()}setPushMode(e){this._pushMode=e}setBitrate(e,t,i){var s;t==="video"?this._videoBitrate=e:this._audioBitrate=e,(s=this._connect)==null||s.applyBitrate(e,t,i)}get pushMode(){return this._pushMode}}class ju extends Q{constructor(e){super(),this._previewConsumer=new bu(e.getComposedStream(),{streamConsumeController:this}),this._pushConsumer=new Bu(e.getComposedStream(),{streamConsumeController:this})}startPreview(){this._previewConsumer.startPreview()}setRenderView(e){this._previewConsumer.setRenderView(e)}async startPush(e,t){return this._pushConsumer.startPush(e,t)}async stopPush(){return this._pushConsumer.unpublish()}setPushMode(e){this._pushConsumer.setPushMode(e)}isPushing(){return this._pushConsumer.isPushing}getStats(){return this._pushConsumer.getStats()}getPreviewElement(){return this._previewConsumer.getPreviewElement()}stopPreview(){this._previewConsumer.stopPreview()}setBitrate(e,t,i){this._pushConsumer.setBitrate(e,t,i)}setPushConfig(e){this._pushConsumer.setPushConfig(e)}get pushMode(){return this._pushConsumer.pushMode}async destroy(){await this._pushConsumer.destroy(),this._previewConsumer.destroy()}}const zu=()=>typeof window>"u",H={},Ke=async r=>{const e=new RTCPeerConnection({sdpSemantics:"unified-plan"});e.addTransceiver("video",{direction:r});const t=await e.createOffer();return e.close(),t.sdp.toLowerCase()};function Di(r){const e=r.split(`
59
+ `);let t=!1;for(const i of e)if(i.includes("level-asymmetry-allowed=1")&&i.includes("packetization-mode=1")&&i.includes("profile-level-id=42e0")){t=!0;break}if(t){const i=navigator.userAgent.toLowerCase();let s=!1;const n=[/miuibrowser/,/70.*HeyTapBrowser/i];for(const a of n)a.test(i)&&(s=!0);return!s}return!1}const Gu=async()=>{let r=await Ke("sendonly");return navigator.userAgent.includes("VivoBrowser")&&(r=await Ke("sendonly")),H.h264encode=Di(r),H.vp8encode=r.indexOf("vp8")>-1,H},Hu=async()=>{let r=await Ke("recvonly");return navigator.userAgent.includes("VivoBrowser")&&(r=await Ke("recvonly")),H.h264decode=Di(r),H.vp8decode=r.indexOf("vp8")>-1,H},qu=async()=>{if(typeof H.h264encode>"u")try{await Gu()}catch{return!1}return H.h264encode||!1},Wu=async()=>{if(typeof H.h264decode>"u")try{await Hu()}catch{return!1}return H.h264decode||!1};class Xu{constructor(){this.onError=(e,t,i)=>{},this.onWarning=e=>{},this.onCaptureFirstAudioFrame=()=>{},this.onCaptureFirstVideoFrame=()=>{},this.onPushStatusUpdate=(e,t)=>{},this.onMicrophoneChanged=e=>{},this.onCameraChanged=e=>{},this.onCaptureInterrupted=e=>{},this.onPushStart=()=>{},this.onPushStop=()=>{},this.onStopCapture=e=>{}}}const Ku=new Xu;let Li=!0,Fi=!0;function Je(r,e,t){const i=r.match(e);return i&&i.length>=t&&parseInt(i[t],10)}function pe(r,e,t){if(!r.RTCPeerConnection)return;const i=r.RTCPeerConnection.prototype,s=i.addEventListener;i.addEventListener=function(a,o){if(a!==e)return s.apply(this,arguments);const u=c=>{const d=t(c);d&&(o.handleEvent?o.handleEvent(d):o(d))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(o,u),s.apply(this,[a,u])};const n=i.removeEventListener;i.removeEventListener=function(a,o){if(a!==e||!this._eventMap||!this._eventMap[e])return n.apply(this,arguments);if(!this._eventMap[e].has(o))return n.apply(this,arguments);const u=this._eventMap[e].get(o);return this._eventMap[e].delete(o),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,n.apply(this,[a,u])},Object.defineProperty(i,"on"+e,{get(){return this["_on"+e]},set(a){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),a&&this.addEventListener(e,this["_on"+e]=a)},enumerable:!0,configurable:!0})}function Ju(r){return typeof r!="boolean"?new Error("Argument type: "+typeof r+". Please use a boolean."):(Li=r,r?"adapter.js logging disabled":"adapter.js logging enabled")}function Yu(r){return typeof r!="boolean"?new Error("Argument type: "+typeof r+". Please use a boolean."):(Fi=!r,"adapter.js deprecation warnings "+(r?"disabled":"enabled"))}function Ni(){if(typeof window=="object"){if(Li)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function jt(r,e){Fi&&console.warn(r+" is deprecated, please use "+e+" instead.")}function Zu(r){const e={browser:null,version:null};if(typeof r>"u"||!r.navigator||!r.navigator.userAgent)return e.browser="Not a browser.",e;const{navigator:t}=r;if(t.userAgentData&&t.userAgentData.brands){const i=t.userAgentData.brands.find(s=>s.brand==="Chromium");if(i)return{browser:"chrome",version:parseInt(i.version,10)}}if(t.mozGetUserMedia)e.browser="firefox",e.version=Je(t.userAgent,/Firefox\/(\d+)\./,1);else if(t.webkitGetUserMedia||r.isSecureContext===!1&&r.webkitRTCPeerConnection)e.browser="chrome",e.version=Je(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(r.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=Je(t.userAgent,/AppleWebKit\/(\d+)\./,1),e.supportsUnifiedPlan=r.RTCRtpTransceiver&&"currentDirection"in r.RTCRtpTransceiver.prototype;else return e.browser="Not a supported browser.",e;return e}function Vi(r){return Object.prototype.toString.call(r)==="[object Object]"}function Ui(r){return Vi(r)?Object.keys(r).reduce(function(e,t){const i=Vi(r[t]),s=i?Ui(r[t]):r[t],n=i&&!Object.keys(s).length;return s===void 0||n?e:Object.assign(e,{[t]:s})},{}):r}function zt(r,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(i=>{i.endsWith("Id")?zt(r,r.get(e[i]),t):i.endsWith("Ids")&&e[i].forEach(s=>{zt(r,r.get(s),t)})}))}function $i(r,e,t){const i=t?"outbound-rtp":"inbound-rtp",s=new Map;if(e===null)return s;const n=[];return r.forEach(a=>{a.type==="track"&&a.trackIdentifier===e.id&&n.push(a)}),n.forEach(a=>{r.forEach(o=>{o.type===i&&o.trackId===a.id&&zt(r,o,s)})}),s}const Bi=Ni;function ji(r,e){const t=r&&r.navigator;if(!t.mediaDevices)return;const i=function(o){if(typeof o!="object"||o.mandatory||o.optional)return o;const u={};return Object.keys(o).forEach(c=>{if(c==="require"||c==="advanced"||c==="mediaSource")return;const d=typeof o[c]=="object"?o[c]:{ideal:o[c]};d.exact!==void 0&&typeof d.exact=="number"&&(d.min=d.max=d.exact);const h=function(p,l){return p?p+l.charAt(0).toUpperCase()+l.slice(1):l==="deviceId"?"sourceId":l};if(d.ideal!==void 0){u.optional=u.optional||[];let p={};typeof d.ideal=="number"?(p[h("min",c)]=d.ideal,u.optional.push(p),p={},p[h("max",c)]=d.ideal,u.optional.push(p)):(p[h("",c)]=d.ideal,u.optional.push(p))}d.exact!==void 0&&typeof d.exact!="number"?(u.mandatory=u.mandatory||{},u.mandatory[h("",c)]=d.exact):["min","max"].forEach(p=>{d[p]!==void 0&&(u.mandatory=u.mandatory||{},u.mandatory[h(p,c)]=d[p])})}),o.advanced&&(u.optional=(u.optional||[]).concat(o.advanced)),u},s=function(o,u){if(e.version>=61)return u(o);if(o=JSON.parse(JSON.stringify(o)),o&&typeof o.audio=="object"){const c=function(d,h,p){h in d&&!(p in d)&&(d[p]=d[h],delete d[h])};o=JSON.parse(JSON.stringify(o)),c(o.audio,"autoGainControl","googAutoGainControl"),c(o.audio,"noiseSuppression","googNoiseSuppression"),o.audio=i(o.audio)}if(o&&typeof o.video=="object"){let c=o.video.facingMode;c=c&&(typeof c=="object"?c:{ideal:c});const d=e.version<66;if(c&&(c.exact==="user"||c.exact==="environment"||c.ideal==="user"||c.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!d)){delete o.video.facingMode;let h;if(c.exact==="environment"||c.ideal==="environment"?h=["back","rear"]:(c.exact==="user"||c.ideal==="user")&&(h=["front"]),h)return t.mediaDevices.enumerateDevices().then(p=>{p=p.filter(f=>f.kind==="videoinput");let l=p.find(f=>h.some(g=>f.label.toLowerCase().includes(g)));return!l&&p.length&&h.includes("back")&&(l=p[p.length-1]),l&&(o.video.deviceId=c.exact?{exact:l.deviceId}:{ideal:l.deviceId}),o.video=i(o.video),Bi("chrome: "+JSON.stringify(o)),u(o)})}o.video=i(o.video)}return Bi("chrome: "+JSON.stringify(o)),u(o)},n=function(o){return e.version>=64?o:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[o.name]||o.name,message:o.message,constraint:o.constraint||o.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},a=function(o,u,c){s(o,d=>{t.webkitGetUserMedia(d,u,h=>{c&&c(n(h))})})};if(t.getUserMedia=a.bind(t),t.mediaDevices.getUserMedia){const o=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(u){return s(u,c=>o(c).then(d=>{if(c.audio&&!d.getAudioTracks().length||c.video&&!d.getVideoTracks().length)throw d.getTracks().forEach(h=>{h.stop()}),new DOMException("","NotFoundError");return d},d=>Promise.reject(n(d))))}}}function zi(r){r.MediaStream=r.MediaStream||r.webkitMediaStream}function Gi(r){if(typeof r=="object"&&r.RTCPeerConnection&&!("ontrack"in r.RTCPeerConnection.prototype)){Object.defineProperty(r.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(t){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=t)},enumerable:!0,configurable:!0});const e=r.RTCPeerConnection.prototype.setRemoteDescription;r.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=i=>{i.stream.addEventListener("addtrack",s=>{let n;r.RTCPeerConnection.prototype.getReceivers?n=this.getReceivers().find(o=>o.track&&o.track.id===s.track.id):n={track:s.track};const a=new Event("track");a.track=s.track,a.receiver=n,a.transceiver={receiver:n},a.streams=[i.stream],this.dispatchEvent(a)}),i.stream.getTracks().forEach(s=>{let n;r.RTCPeerConnection.prototype.getReceivers?n=this.getReceivers().find(o=>o.track&&o.track.id===s.id):n={track:s};const a=new Event("track");a.track=s,a.receiver=n,a.transceiver={receiver:n},a.streams=[i.stream],this.dispatchEvent(a)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else pe(r,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function Hi(r){if(typeof r=="object"&&r.RTCPeerConnection&&!("getSenders"in r.RTCPeerConnection.prototype)&&"createDTMFSender"in r.RTCPeerConnection.prototype){const e=function(s,n){return{track:n,get dtmf(){return this._dtmf===void 0&&(n.kind==="audio"?this._dtmf=s.createDTMFSender(n):this._dtmf=null),this._dtmf},_pc:s}};if(!r.RTCPeerConnection.prototype.getSenders){r.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const s=r.RTCPeerConnection.prototype.addTrack;r.RTCPeerConnection.prototype.addTrack=function(o,u){let c=s.apply(this,arguments);return c||(c=e(this,o),this._senders.push(c)),c};const n=r.RTCPeerConnection.prototype.removeTrack;r.RTCPeerConnection.prototype.removeTrack=function(o){n.apply(this,arguments);const u=this._senders.indexOf(o);u!==-1&&this._senders.splice(u,1)}}const t=r.RTCPeerConnection.prototype.addStream;r.RTCPeerConnection.prototype.addStream=function(n){this._senders=this._senders||[],t.apply(this,[n]),n.getTracks().forEach(a=>{this._senders.push(e(this,a))})};const i=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(n){this._senders=this._senders||[],i.apply(this,[n]),n.getTracks().forEach(a=>{const o=this._senders.find(u=>u.track===a);o&&this._senders.splice(this._senders.indexOf(o),1)})}}else if(typeof r=="object"&&r.RTCPeerConnection&&"getSenders"in r.RTCPeerConnection.prototype&&"createDTMFSender"in r.RTCPeerConnection.prototype&&r.RTCRtpSender&&!("dtmf"in r.RTCRtpSender.prototype)){const e=r.RTCPeerConnection.prototype.getSenders;r.RTCPeerConnection.prototype.getSenders=function(){const i=e.apply(this,[]);return i.forEach(s=>s._pc=this),i},Object.defineProperty(r.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function qi(r){if(!(typeof r=="object"&&r.RTCPeerConnection&&r.RTCRtpSender&&r.RTCRtpReceiver))return;if(!("getStats"in r.RTCRtpSender.prototype)){const t=r.RTCPeerConnection.prototype.getSenders;t&&(r.RTCPeerConnection.prototype.getSenders=function(){const n=t.apply(this,[]);return n.forEach(a=>a._pc=this),n});const i=r.RTCPeerConnection.prototype.addTrack;i&&(r.RTCPeerConnection.prototype.addTrack=function(){const n=i.apply(this,arguments);return n._pc=this,n}),r.RTCRtpSender.prototype.getStats=function(){const n=this;return this._pc.getStats().then(a=>$i(a,n.track,!0))}}if(!("getStats"in r.RTCRtpReceiver.prototype)){const t=r.RTCPeerConnection.prototype.getReceivers;t&&(r.RTCPeerConnection.prototype.getReceivers=function(){const s=t.apply(this,[]);return s.forEach(n=>n._pc=this),s}),pe(r,"track",i=>(i.receiver._pc=i.srcElement,i)),r.RTCRtpReceiver.prototype.getStats=function(){const s=this;return this._pc.getStats().then(n=>$i(n,s.track,!1))}}if(!("getStats"in r.RTCRtpSender.prototype&&"getStats"in r.RTCRtpReceiver.prototype))return;const e=r.RTCPeerConnection.prototype.getStats;r.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof r.MediaStreamTrack){const i=arguments[0];let s,n,a;return this.getSenders().forEach(o=>{o.track===i&&(s?a=!0:s=o)}),this.getReceivers().forEach(o=>(o.track===i&&(n?a=!0:n=o),o.track===i)),a||s&&n?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):s?s.getStats():n?n.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return e.apply(this,arguments)}}function Wi(r){r.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(a=>this._shimmedLocalStreams[a][0])};const e=r.RTCPeerConnection.prototype.addTrack;r.RTCPeerConnection.prototype.addTrack=function(a,o){if(!o)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const u=e.apply(this,arguments);return this._shimmedLocalStreams[o.id]?this._shimmedLocalStreams[o.id].indexOf(u)===-1&&this._shimmedLocalStreams[o.id].push(u):this._shimmedLocalStreams[o.id]=[o,u],u};const t=r.RTCPeerConnection.prototype.addStream;r.RTCPeerConnection.prototype.addStream=function(a){this._shimmedLocalStreams=this._shimmedLocalStreams||{},a.getTracks().forEach(c=>{if(this.getSenders().find(h=>h.track===c))throw new DOMException("Track already exists.","InvalidAccessError")});const o=this.getSenders();t.apply(this,arguments);const u=this.getSenders().filter(c=>o.indexOf(c)===-1);this._shimmedLocalStreams[a.id]=[a].concat(u)};const i=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[a.id],i.apply(this,arguments)};const s=r.RTCPeerConnection.prototype.removeTrack;r.RTCPeerConnection.prototype.removeTrack=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},a&&Object.keys(this._shimmedLocalStreams).forEach(o=>{const u=this._shimmedLocalStreams[o].indexOf(a);u!==-1&&this._shimmedLocalStreams[o].splice(u,1),this._shimmedLocalStreams[o].length===1&&delete this._shimmedLocalStreams[o]}),s.apply(this,arguments)}}function Xi(r,e){if(!r.RTCPeerConnection)return;if(r.RTCPeerConnection.prototype.addTrack&&e.version>=65)return Wi(r);const t=r.RTCPeerConnection.prototype.getLocalStreams;r.RTCPeerConnection.prototype.getLocalStreams=function(){const d=t.apply(this);return this._reverseStreams=this._reverseStreams||{},d.map(h=>this._reverseStreams[h.id])};const i=r.RTCPeerConnection.prototype.addStream;r.RTCPeerConnection.prototype.addStream=function(d){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},d.getTracks().forEach(h=>{if(this.getSenders().find(l=>l.track===h))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[d.id]){const h=new r.MediaStream(d.getTracks());this._streams[d.id]=h,this._reverseStreams[h.id]=d,d=h}i.apply(this,[d])};const s=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(d){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.apply(this,[this._streams[d.id]||d]),delete this._reverseStreams[this._streams[d.id]?this._streams[d.id].id:d.id],delete this._streams[d.id]},r.RTCPeerConnection.prototype.addTrack=function(d,h){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const p=[].slice.call(arguments,1);if(p.length!==1||!p[0].getTracks().find(g=>g===d))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(g=>g.track===d))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const f=this._streams[h.id];if(f)f.addTrack(d),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const g=new r.MediaStream([d]);this._streams[h.id]=g,this._reverseStreams[g.id]=h,this.addStream(g)}return this.getSenders().find(g=>g.track===d)};function n(c,d){let h=d.sdp;return Object.keys(c._reverseStreams||[]).forEach(p=>{const l=c._reverseStreams[p],f=c._streams[l.id];h=h.replace(new RegExp(f.id,"g"),l.id)}),new RTCSessionDescription({type:d.type,sdp:h})}function a(c,d){let h=d.sdp;return Object.keys(c._reverseStreams||[]).forEach(p=>{const l=c._reverseStreams[p],f=c._streams[l.id];h=h.replace(new RegExp(l.id,"g"),f.id)}),new RTCSessionDescription({type:d.type,sdp:h})}["createOffer","createAnswer"].forEach(function(c){const d=r.RTCPeerConnection.prototype[c],h={[c](){const p=arguments;return arguments.length&&typeof arguments[0]=="function"?d.apply(this,[f=>{const g=n(this,f);p[0].apply(null,[g])},f=>{p[1]&&p[1].apply(null,f)},arguments[2]]):d.apply(this,arguments).then(f=>n(this,f))}};r.RTCPeerConnection.prototype[c]=h[c]});const o=r.RTCPeerConnection.prototype.setLocalDescription;r.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?o.apply(this,arguments):(arguments[0]=a(this,arguments[0]),o.apply(this,arguments))};const u=Object.getOwnPropertyDescriptor(r.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(r.RTCPeerConnection.prototype,"localDescription",{get(){const c=u.get.apply(this);return c.type===""?c:n(this,c)}}),r.RTCPeerConnection.prototype.removeTrack=function(d){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!d._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(d._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let p;Object.keys(this._streams).forEach(l=>{this._streams[l].getTracks().find(g=>d.track===g)&&(p=this._streams[l])}),p&&(p.getTracks().length===1?this.removeStream(this._reverseStreams[p.id]):p.removeTrack(d.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Gt(r,e){!r.RTCPeerConnection&&r.webkitRTCPeerConnection&&(r.RTCPeerConnection=r.webkitRTCPeerConnection),r.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const i=r.RTCPeerConnection.prototype[t],s={[t](){return arguments[0]=new(t==="addIceCandidate"?r.RTCIceCandidate:r.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};r.RTCPeerConnection.prototype[t]=s[t]})}function Ki(r,e){pe(r,"negotiationneeded",t=>{const i=t.target;if(!((e.version<72||i.getConfiguration&&i.getConfiguration().sdpSemantics==="plan-b")&&i.signalingState!=="stable"))return t})}const Ji=Object.freeze(Object.defineProperty({__proto__:null,fixNegotiationNeeded:Ki,shimAddTrackRemoveTrack:Xi,shimAddTrackRemoveTrackWithNative:Wi,shimGetSendersWithDtmf:Hi,shimGetUserMedia:ji,shimMediaStream:zi,shimOnTrack:Gi,shimPeerConnection:Gt,shimSenderReceiverGetStats:qi},Symbol.toStringTag,{value:"Module"}));function Yi(r,e){const t=r&&r.navigator,i=r&&r.MediaStreamTrack;if(t.getUserMedia=function(s,n,a){jt("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(s).then(n,a)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){const s=function(a,o,u){o in a&&!(u in a)&&(a[u]=a[o],delete a[o])},n=t.mediaDevices.getUserMedia.bind(t.mediaDevices);if(t.mediaDevices.getUserMedia=function(a){return typeof a=="object"&&typeof a.audio=="object"&&(a=JSON.parse(JSON.stringify(a)),s(a.audio,"autoGainControl","mozAutoGainControl"),s(a.audio,"noiseSuppression","mozNoiseSuppression")),n(a)},i&&i.prototype.getSettings){const a=i.prototype.getSettings;i.prototype.getSettings=function(){const o=a.apply(this,arguments);return s(o,"mozAutoGainControl","autoGainControl"),s(o,"mozNoiseSuppression","noiseSuppression"),o}}if(i&&i.prototype.applyConstraints){const a=i.prototype.applyConstraints;i.prototype.applyConstraints=function(o){return this.kind==="audio"&&typeof o=="object"&&(o=JSON.parse(JSON.stringify(o)),s(o,"autoGainControl","mozAutoGainControl"),s(o,"noiseSuppression","mozNoiseSuppression")),a.apply(this,[o])}}}}function Qu(r,e){r.navigator.mediaDevices&&"getDisplayMedia"in r.navigator.mediaDevices||r.navigator.mediaDevices&&(r.navigator.mediaDevices.getDisplayMedia=function(i){if(!(i&&i.video)){const s=new DOMException("getDisplayMedia without video constraints is undefined");return s.name="NotFoundError",s.code=8,Promise.reject(s)}return i.video===!0?i.video={mediaSource:e}:i.video.mediaSource=e,r.navigator.mediaDevices.getUserMedia(i)})}function Zi(r){typeof r=="object"&&r.RTCTrackEvent&&"receiver"in r.RTCTrackEvent.prototype&&!("transceiver"in r.RTCTrackEvent.prototype)&&Object.defineProperty(r.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Ht(r,e){if(typeof r!="object"||!(r.RTCPeerConnection||r.mozRTCPeerConnection))return;!r.RTCPeerConnection&&r.mozRTCPeerConnection&&(r.RTCPeerConnection=r.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(s){const n=r.RTCPeerConnection.prototype[s],a={[s](){return arguments[0]=new(s==="addIceCandidate"?r.RTCIceCandidate:r.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};r.RTCPeerConnection.prototype[s]=a[s]});const t={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=r.RTCPeerConnection.prototype.getStats;r.RTCPeerConnection.prototype.getStats=function(){const[n,a,o]=arguments;return i.apply(this,[n||null]).then(u=>{if(e.version<53&&!a)try{u.forEach(c=>{c.type=t[c.type]||c.type})}catch(c){if(c.name!=="TypeError")throw c;u.forEach((d,h)=>{u.set(h,Object.assign({},d,{type:t[d.type]||d.type}))})}return u}).then(a,o)}}function Qi(r){if(!(typeof r=="object"&&r.RTCPeerConnection&&r.RTCRtpSender)||r.RTCRtpSender&&"getStats"in r.RTCRtpSender.prototype)return;const e=r.RTCPeerConnection.prototype.getSenders;e&&(r.RTCPeerConnection.prototype.getSenders=function(){const s=e.apply(this,[]);return s.forEach(n=>n._pc=this),s});const t=r.RTCPeerConnection.prototype.addTrack;t&&(r.RTCPeerConnection.prototype.addTrack=function(){const s=t.apply(this,arguments);return s._pc=this,s}),r.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function es(r){if(!(typeof r=="object"&&r.RTCPeerConnection&&r.RTCRtpSender)||r.RTCRtpSender&&"getStats"in r.RTCRtpReceiver.prototype)return;const e=r.RTCPeerConnection.prototype.getReceivers;e&&(r.RTCPeerConnection.prototype.getReceivers=function(){const i=e.apply(this,[]);return i.forEach(s=>s._pc=this),i}),pe(r,"track",t=>(t.receiver._pc=t.srcElement,t)),r.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function ts(r){!r.RTCPeerConnection||"removeStream"in r.RTCPeerConnection.prototype||(r.RTCPeerConnection.prototype.removeStream=function(t){jt("removeStream","removeTrack"),this.getSenders().forEach(i=>{i.track&&t.getTracks().includes(i.track)&&this.removeTrack(i)})})}function rs(r){r.DataChannel&&!r.RTCDataChannel&&(r.RTCDataChannel=r.DataChannel)}function is(r){if(!(typeof r=="object"&&r.RTCPeerConnection))return;const e=r.RTCPeerConnection.prototype.addTransceiver;e&&(r.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let i=arguments[1]&&arguments[1].sendEncodings;i===void 0&&(i=[]),i=[...i];const s=i.length>0;s&&i.forEach(a=>{if("rid"in a&&!/^[a-z0-9]{0,16}$/i.test(a.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in a&&!(parseFloat(a.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in a&&!(parseFloat(a.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const n=e.apply(this,arguments);if(s){const{sender:a}=n,o=a.getParameters();(!("encodings"in o)||o.encodings.length===1&&Object.keys(o.encodings[0]).length===0)&&(o.encodings=i,a.sendEncodings=i,this.setParametersPromises.push(a.setParameters(o).then(()=>{delete a.sendEncodings}).catch(()=>{delete a.sendEncodings})))}return n})}function ss(r){if(!(typeof r=="object"&&r.RTCRtpSender))return;const e=r.RTCRtpSender.prototype.getParameters;e&&(r.RTCRtpSender.prototype.getParameters=function(){const i=e.apply(this,arguments);return"encodings"in i||(i.encodings=[].concat(this.sendEncodings||[{}])),i})}function ns(r){if(!(typeof r=="object"&&r.RTCPeerConnection))return;const e=r.RTCPeerConnection.prototype.createOffer;r.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}function os(r){if(!(typeof r=="object"&&r.RTCPeerConnection))return;const e=r.RTCPeerConnection.prototype.createAnswer;r.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}const as=Object.freeze(Object.defineProperty({__proto__:null,shimAddTransceiver:is,shimCreateAnswer:os,shimCreateOffer:ns,shimGetDisplayMedia:Qu,shimGetParameters:ss,shimGetUserMedia:Yi,shimOnTrack:Zi,shimPeerConnection:Ht,shimRTCDataChannel:rs,shimReceiverGetStats:es,shimRemoveStream:ts,shimSenderGetStats:Qi},Symbol.toStringTag,{value:"Module"}));function cs(r){if(!(typeof r!="object"||!r.RTCPeerConnection)){if("getLocalStreams"in r.RTCPeerConnection.prototype||(r.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in r.RTCPeerConnection.prototype)){const e=r.RTCPeerConnection.prototype.addTrack;r.RTCPeerConnection.prototype.addStream=function(i){this._localStreams||(this._localStreams=[]),this._localStreams.includes(i)||this._localStreams.push(i),i.getAudioTracks().forEach(s=>e.call(this,s,i)),i.getVideoTracks().forEach(s=>e.call(this,s,i))},r.RTCPeerConnection.prototype.addTrack=function(i,...s){return s&&s.forEach(n=>{this._localStreams?this._localStreams.includes(n)||this._localStreams.push(n):this._localStreams=[n]}),e.apply(this,arguments)}}"removeStream"in r.RTCPeerConnection.prototype||(r.RTCPeerConnection.prototype.removeStream=function(t){this._localStreams||(this._localStreams=[]);const i=this._localStreams.indexOf(t);if(i===-1)return;this._localStreams.splice(i,1);const s=t.getTracks();this.getSenders().forEach(n=>{s.includes(n.track)&&this.removeTrack(n)})})}}function ds(r){if(!(typeof r!="object"||!r.RTCPeerConnection)&&("getRemoteStreams"in r.RTCPeerConnection.prototype||(r.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in r.RTCPeerConnection.prototype))){Object.defineProperty(r.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(t){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=t),this.addEventListener("track",this._onaddstreampoly=i=>{i.streams.forEach(s=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(s))return;this._remoteStreams.push(s);const n=new Event("addstream");n.stream=s,this.dispatchEvent(n)})})}});const e=r.RTCPeerConnection.prototype.setRemoteDescription;r.RTCPeerConnection.prototype.setRemoteDescription=function(){const i=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(s){s.streams.forEach(n=>{if(i._remoteStreams||(i._remoteStreams=[]),i._remoteStreams.indexOf(n)>=0)return;i._remoteStreams.push(n);const a=new Event("addstream");a.stream=n,i.dispatchEvent(a)})}),e.apply(i,arguments)}}}function us(r){if(typeof r!="object"||!r.RTCPeerConnection)return;const e=r.RTCPeerConnection.prototype,t=e.createOffer,i=e.createAnswer,s=e.setLocalDescription,n=e.setRemoteDescription,a=e.addIceCandidate;e.createOffer=function(c,d){const h=arguments.length>=2?arguments[2]:arguments[0],p=t.apply(this,[h]);return d?(p.then(c,d),Promise.resolve()):p},e.createAnswer=function(c,d){const h=arguments.length>=2?arguments[2]:arguments[0],p=i.apply(this,[h]);return d?(p.then(c,d),Promise.resolve()):p};let o=function(u,c,d){const h=s.apply(this,[u]);return d?(h.then(c,d),Promise.resolve()):h};e.setLocalDescription=o,o=function(u,c,d){const h=n.apply(this,[u]);return d?(h.then(c,d),Promise.resolve()):h},e.setRemoteDescription=o,o=function(u,c,d){const h=a.apply(this,[u]);return d?(h.then(c,d),Promise.resolve()):h},e.addIceCandidate=o}function hs(r){const e=r&&r.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const t=e.mediaDevices,i=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=s=>i(ps(s))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(i,s,n){e.mediaDevices.getUserMedia(i).then(s,n)}).bind(e))}function ps(r){return r&&r.video!==void 0?Object.assign({},r,{video:Ui(r.video)}):r}function ls(r){if(!r.RTCPeerConnection)return;const e=r.RTCPeerConnection;r.RTCPeerConnection=function(i,s){if(i&&i.iceServers){const n=[];for(let a=0;a<i.iceServers.length;a++){let o=i.iceServers[a];o.urls===void 0&&o.url?(jt("RTCIceServer.url","RTCIceServer.urls"),o=JSON.parse(JSON.stringify(o)),o.urls=o.url,delete o.url,n.push(o)):n.push(i.iceServers[a])}i.iceServers=n}return new e(i,s)},r.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(r.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function ms(r){typeof r=="object"&&r.RTCTrackEvent&&"receiver"in r.RTCTrackEvent.prototype&&!("transceiver"in r.RTCTrackEvent.prototype)&&Object.defineProperty(r.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function fs(r){const e=r.RTCPeerConnection.prototype.createOffer;r.RTCPeerConnection.prototype.createOffer=function(i){if(i){typeof i.offerToReceiveAudio<"u"&&(i.offerToReceiveAudio=!!i.offerToReceiveAudio);const s=this.getTransceivers().find(a=>a.receiver.track.kind==="audio");i.offerToReceiveAudio===!1&&s?s.direction==="sendrecv"?s.setDirection?s.setDirection("sendonly"):s.direction="sendonly":s.direction==="recvonly"&&(s.setDirection?s.setDirection("inactive"):s.direction="inactive"):i.offerToReceiveAudio===!0&&!s&&this.addTransceiver("audio",{direction:"recvonly"}),typeof i.offerToReceiveVideo<"u"&&(i.offerToReceiveVideo=!!i.offerToReceiveVideo);const n=this.getTransceivers().find(a=>a.receiver.track.kind==="video");i.offerToReceiveVideo===!1&&n?n.direction==="sendrecv"?n.setDirection?n.setDirection("sendonly"):n.direction="sendonly":n.direction==="recvonly"&&(n.setDirection?n.setDirection("inactive"):n.direction="inactive"):i.offerToReceiveVideo===!0&&!n&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function _s(r){typeof r!="object"||r.AudioContext||(r.AudioContext=r.webkitAudioContext)}const gs=Object.freeze(Object.defineProperty({__proto__:null,shimAudioContext:_s,shimCallbacksAPI:us,shimConstraints:ps,shimCreateOfferLegacy:fs,shimGetUserMedia:hs,shimLocalStreamsAPI:cs,shimRTCIceServerUrls:ls,shimRemoteStreamsAPI:ds,shimTrackEventTransceiver:ms},Symbol.toStringTag,{value:"Module"}));var qt={exports:{}},vs;function eh(){return vs||(vs=1,function(r){const e={};e.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},e.localCName=e.generateIdentifier(),e.splitLines=function(t){return t.trim().split(`
60
+ `).map(i=>i.trim())},e.splitSections=function(t){return t.split(`
61
+ m=`).map((s,n)=>(n>0?"m="+s:s).trim()+`\r
62
+ `)},e.getDescription=function(t){const i=e.splitSections(t);return i&&i[0]},e.getMediaSections=function(t){const i=e.splitSections(t);return i.shift(),i},e.matchPrefix=function(t,i){return e.splitLines(t).filter(s=>s.indexOf(i)===0)},e.parseCandidate=function(t){let i;t.indexOf("a=candidate:")===0?i=t.substring(12).split(" "):i=t.substring(10).split(" ");const s={foundation:i[0],component:{1:"rtp",2:"rtcp"}[i[1]]||i[1],protocol:i[2].toLowerCase(),priority:parseInt(i[3],10),ip:i[4],address:i[4],port:parseInt(i[5],10),type:i[7]};for(let n=8;n<i.length;n+=2)switch(i[n]){case"raddr":s.relatedAddress=i[n+1];break;case"rport":s.relatedPort=parseInt(i[n+1],10);break;case"tcptype":s.tcpType=i[n+1];break;case"ufrag":s.ufrag=i[n+1],s.usernameFragment=i[n+1];break;default:s[i[n]]===void 0&&(s[i[n]]=i[n+1]);break}return s},e.writeCandidate=function(t){const i=[];i.push(t.foundation);const s=t.component;s==="rtp"?i.push(1):s==="rtcp"?i.push(2):i.push(s),i.push(t.protocol.toUpperCase()),i.push(t.priority),i.push(t.address||t.ip),i.push(t.port);const n=t.type;return i.push("typ"),i.push(n),n!=="host"&&t.relatedAddress&&t.relatedPort&&(i.push("raddr"),i.push(t.relatedAddress),i.push("rport"),i.push(t.relatedPort)),t.tcpType&&t.protocol.toLowerCase()==="tcp"&&(i.push("tcptype"),i.push(t.tcpType)),(t.usernameFragment||t.ufrag)&&(i.push("ufrag"),i.push(t.usernameFragment||t.ufrag)),"candidate:"+i.join(" ")},e.parseIceOptions=function(t){return t.substring(14).split(" ")},e.parseRtpMap=function(t){let i=t.substring(9).split(" ");const s={payloadType:parseInt(i.shift(),10)};return i=i[0].split("/"),s.name=i[0],s.clockRate=parseInt(i[1],10),s.channels=i.length===3?parseInt(i[2],10):1,s.numChannels=s.channels,s},e.writeRtpMap=function(t){let i=t.payloadType;t.preferredPayloadType!==void 0&&(i=t.preferredPayloadType);const s=t.channels||t.numChannels||1;return"a=rtpmap:"+i+" "+t.name+"/"+t.clockRate+(s!==1?"/"+s:"")+`\r
63
+ `},e.parseExtmap=function(t){const i=t.substring(9).split(" ");return{id:parseInt(i[0],10),direction:i[0].indexOf("/")>0?i[0].split("/")[1]:"sendrecv",uri:i[1],attributes:i.slice(2).join(" ")}},e.writeExtmap=function(t){return"a=extmap:"+(t.id||t.preferredId)+(t.direction&&t.direction!=="sendrecv"?"/"+t.direction:"")+" "+t.uri+(t.attributes?" "+t.attributes:"")+`\r
64
+ `},e.parseFmtp=function(t){const i={};let s;const n=t.substring(t.indexOf(" ")+1).split(";");for(let a=0;a<n.length;a++)s=n[a].trim().split("="),i[s[0].trim()]=s[1];return i},e.writeFmtp=function(t){let i="",s=t.payloadType;if(t.preferredPayloadType!==void 0&&(s=t.preferredPayloadType),t.parameters&&Object.keys(t.parameters).length){const n=[];Object.keys(t.parameters).forEach(a=>{t.parameters[a]!==void 0?n.push(a+"="+t.parameters[a]):n.push(a)}),i+="a=fmtp:"+s+" "+n.join(";")+`\r
65
+ `}return i},e.parseRtcpFb=function(t){const i=t.substring(t.indexOf(" ")+1).split(" ");return{type:i.shift(),parameter:i.join(" ")}},e.writeRtcpFb=function(t){let i="",s=t.payloadType;return t.preferredPayloadType!==void 0&&(s=t.preferredPayloadType),t.rtcpFeedback&&t.rtcpFeedback.length&&t.rtcpFeedback.forEach(n=>{i+="a=rtcp-fb:"+s+" "+n.type+(n.parameter&&n.parameter.length?" "+n.parameter:"")+`\r
66
+ `}),i},e.parseSsrcMedia=function(t){const i=t.indexOf(" "),s={ssrc:parseInt(t.substring(7,i),10)},n=t.indexOf(":",i);return n>-1?(s.attribute=t.substring(i+1,n),s.value=t.substring(n+1)):s.attribute=t.substring(i+1),s},e.parseSsrcGroup=function(t){const i=t.substring(13).split(" ");return{semantics:i.shift(),ssrcs:i.map(s=>parseInt(s,10))}},e.getMid=function(t){const i=e.matchPrefix(t,"a=mid:")[0];if(i)return i.substring(6)},e.parseFingerprint=function(t){const i=t.substring(14).split(" ");return{algorithm:i[0].toLowerCase(),value:i[1].toUpperCase()}},e.getDtlsParameters=function(t,i){return{role:"auto",fingerprints:e.matchPrefix(t+i,"a=fingerprint:").map(e.parseFingerprint)}},e.writeDtlsParameters=function(t,i){let s="a=setup:"+i+`\r
67
+ `;return t.fingerprints.forEach(n=>{s+="a=fingerprint:"+n.algorithm+" "+n.value+`\r
68
+ `}),s},e.parseCryptoLine=function(t){const i=t.substring(9).split(" ");return{tag:parseInt(i[0],10),cryptoSuite:i[1],keyParams:i[2],sessionParams:i.slice(3)}},e.writeCryptoLine=function(t){return"a=crypto:"+t.tag+" "+t.cryptoSuite+" "+(typeof t.keyParams=="object"?e.writeCryptoKeyParams(t.keyParams):t.keyParams)+(t.sessionParams?" "+t.sessionParams.join(" "):"")+`\r
69
+ `},e.parseCryptoKeyParams=function(t){if(t.indexOf("inline:")!==0)return null;const i=t.substring(7).split("|");return{keyMethod:"inline",keySalt:i[0],lifeTime:i[1],mkiValue:i[2]?i[2].split(":")[0]:void 0,mkiLength:i[2]?i[2].split(":")[1]:void 0}},e.writeCryptoKeyParams=function(t){return t.keyMethod+":"+t.keySalt+(t.lifeTime?"|"+t.lifeTime:"")+(t.mkiValue&&t.mkiLength?"|"+t.mkiValue+":"+t.mkiLength:"")},e.getCryptoParameters=function(t,i){return e.matchPrefix(t+i,"a=crypto:").map(e.parseCryptoLine)},e.getIceParameters=function(t,i){const s=e.matchPrefix(t+i,"a=ice-ufrag:")[0],n=e.matchPrefix(t+i,"a=ice-pwd:")[0];return s&&n?{usernameFragment:s.substring(12),password:n.substring(10)}:null},e.writeIceParameters=function(t){let i="a=ice-ufrag:"+t.usernameFragment+`\r
70
+ a=ice-pwd:`+t.password+`\r
71
+ `;return t.iceLite&&(i+=`a=ice-lite\r
72
+ `),i},e.parseRtpParameters=function(t){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=e.splitLines(t)[0].split(" ");i.profile=n[2];for(let o=3;o<n.length;o++){const u=n[o],c=e.matchPrefix(t,"a=rtpmap:"+u+" ")[0];if(c){const d=e.parseRtpMap(c),h=e.matchPrefix(t,"a=fmtp:"+u+" ");switch(d.parameters=h.length?e.parseFmtp(h[0]):{},d.rtcpFeedback=e.matchPrefix(t,"a=rtcp-fb:"+u+" ").map(e.parseRtcpFb),i.codecs.push(d),d.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(d.name.toUpperCase());break}}}e.matchPrefix(t,"a=extmap:").forEach(o=>{i.headerExtensions.push(e.parseExtmap(o))});const a=e.matchPrefix(t,"a=rtcp-fb:* ").map(e.parseRtcpFb);return i.codecs.forEach(o=>{a.forEach(u=>{o.rtcpFeedback.find(d=>d.type===u.type&&d.parameter===u.parameter)||o.rtcpFeedback.push(u)})}),i},e.writeRtpDescription=function(t,i){let s="";s+="m="+t+" ",s+=i.codecs.length>0?"9":"0",s+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",s+=i.codecs.map(a=>a.preferredPayloadType!==void 0?a.preferredPayloadType:a.payloadType).join(" ")+`\r
73
+ `,s+=`c=IN IP4 0.0.0.0\r
74
+ `,s+=`a=rtcp:9 IN IP4 0.0.0.0\r
75
+ `,i.codecs.forEach(a=>{s+=e.writeRtpMap(a),s+=e.writeFmtp(a),s+=e.writeRtcpFb(a)});let n=0;return i.codecs.forEach(a=>{a.maxptime>n&&(n=a.maxptime)}),n>0&&(s+="a=maxptime:"+n+`\r
76
+ `),i.headerExtensions&&i.headerExtensions.forEach(a=>{s+=e.writeExtmap(a)}),s},e.parseRtpEncodingParameters=function(t){const i=[],s=e.parseRtpParameters(t),n=s.fecMechanisms.indexOf("RED")!==-1,a=s.fecMechanisms.indexOf("ULPFEC")!==-1,o=e.matchPrefix(t,"a=ssrc:").map(p=>e.parseSsrcMedia(p)).filter(p=>p.attribute==="cname"),u=o.length>0&&o[0].ssrc;let c;const d=e.matchPrefix(t,"a=ssrc-group:FID").map(p=>p.substring(17).split(" ").map(f=>parseInt(f,10)));d.length>0&&d[0].length>1&&d[0][0]===u&&(c=d[0][1]),s.codecs.forEach(p=>{if(p.name.toUpperCase()==="RTX"&&p.parameters.apt){let l={ssrc:u,codecPayloadType:parseInt(p.parameters.apt,10)};u&&c&&(l.rtx={ssrc:c}),i.push(l),n&&(l=JSON.parse(JSON.stringify(l)),l.fec={ssrc:u,mechanism:a?"red+ulpfec":"red"},i.push(l))}}),i.length===0&&u&&i.push({ssrc:u});let h=e.matchPrefix(t,"b=");return h.length&&(h[0].indexOf("b=TIAS:")===0?h=parseInt(h[0].substring(7),10):h[0].indexOf("b=AS:")===0?h=parseInt(h[0].substring(5),10)*1e3*.95-50*40*8:h=void 0,i.forEach(p=>{p.maxBitrate=h})),i},e.parseRtcpParameters=function(t){const i={},s=e.matchPrefix(t,"a=ssrc:").map(o=>e.parseSsrcMedia(o)).filter(o=>o.attribute==="cname")[0];s&&(i.cname=s.value,i.ssrc=s.ssrc);const n=e.matchPrefix(t,"a=rtcp-rsize");i.reducedSize=n.length>0,i.compound=n.length===0;const a=e.matchPrefix(t,"a=rtcp-mux");return i.mux=a.length>0,i},e.writeRtcpParameters=function(t){let i="";return t.reducedSize&&(i+=`a=rtcp-rsize\r
77
+ `),t.mux&&(i+=`a=rtcp-mux\r
78
+ `),t.ssrc!==void 0&&t.cname&&(i+="a=ssrc:"+t.ssrc+" cname:"+t.cname+`\r
79
+ `),i},e.parseMsid=function(t){let i;const s=e.matchPrefix(t,"a=msid:");if(s.length===1)return i=s[0].substring(7).split(" "),{stream:i[0],track:i[1]};const n=e.matchPrefix(t,"a=ssrc:").map(a=>e.parseSsrcMedia(a)).filter(a=>a.attribute==="msid");if(n.length>0)return i=n[0].value.split(" "),{stream:i[0],track:i[1]}},e.parseSctpDescription=function(t){const i=e.parseMLine(t),s=e.matchPrefix(t,"a=max-message-size:");let n;s.length>0&&(n=parseInt(s[0].substring(19),10)),isNaN(n)&&(n=65536);const a=e.matchPrefix(t,"a=sctp-port:");if(a.length>0)return{port:parseInt(a[0].substring(12),10),protocol:i.fmt,maxMessageSize:n};const o=e.matchPrefix(t,"a=sctpmap:");if(o.length>0){const u=o[0].substring(10).split(" ");return{port:parseInt(u[0],10),protocol:u[1],maxMessageSize:n}}},e.writeSctpDescription=function(t,i){let s=[];return t.protocol!=="DTLS/SCTP"?s=["m="+t.kind+" 9 "+t.protocol+" "+i.protocol+`\r
80
+ `,`c=IN IP4 0.0.0.0\r
81
+ `,"a=sctp-port:"+i.port+`\r
82
+ `]:s=["m="+t.kind+" 9 "+t.protocol+" "+i.port+`\r
83
+ `,`c=IN IP4 0.0.0.0\r
84
+ `,"a=sctpmap:"+i.port+" "+i.protocol+` 65535\r
85
+ `],i.maxMessageSize!==void 0&&s.push("a=max-message-size:"+i.maxMessageSize+`\r
86
+ `),s.join("")},e.generateSessionId=function(){return Math.random().toString().substr(2,22)},e.writeSessionBoilerplate=function(t,i,s){let n;const a=i!==void 0?i:2;return t?n=t:n=e.generateSessionId(),`v=0\r
87
+ o=`+(s||"thisisadapterortc")+" "+n+" "+a+` IN IP4 127.0.0.1\r
88
+ s=-\r
89
+ t=0 0\r
90
+ `},e.getDirection=function(t,i){const s=e.splitLines(t);for(let n=0;n<s.length;n++)switch(s[n]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return s[n].substring(2)}return i?e.getDirection(i):"sendrecv"},e.getKind=function(t){return e.splitLines(t)[0].split(" ")[0].substring(2)},e.isRejected=function(t){return t.split(" ",2)[1]==="0"},e.parseMLine=function(t){const s=e.splitLines(t)[0].substring(2).split(" ");return{kind:s[0],port:parseInt(s[1],10),protocol:s[2],fmt:s.slice(3).join(" ")}},e.parseOLine=function(t){const s=e.matchPrefix(t,"o=")[0].substring(2).split(" ");return{username:s[0],sessionId:s[1],sessionVersion:parseInt(s[2],10),netType:s[3],addressType:s[4],address:s[5]}},e.isValidSDP=function(t){if(typeof t!="string"||t.length===0)return!1;const i=e.splitLines(t);for(let s=0;s<i.length;s++)if(i[s].length<2||i[s].charAt(1)!=="=")return!1;return!0},r.exports=e}(qt)),qt.exports}var Cs=eh();const Se=I(Cs),th=$({__proto__:null,default:Se},[Cs]);function Ye(r){if(!r.RTCIceCandidate||r.RTCIceCandidate&&"foundation"in r.RTCIceCandidate.prototype)return;const e=r.RTCIceCandidate;r.RTCIceCandidate=function(i){if(typeof i=="object"&&i.candidate&&i.candidate.indexOf("a=")===0&&(i=JSON.parse(JSON.stringify(i)),i.candidate=i.candidate.substring(2)),i.candidate&&i.candidate.length){const s=new e(i),n=Se.parseCandidate(i.candidate);for(const a in n)a in s||Object.defineProperty(s,a,{value:n[a]});return s.toJSON=function(){return{candidate:s.candidate,sdpMid:s.sdpMid,sdpMLineIndex:s.sdpMLineIndex,usernameFragment:s.usernameFragment}},s}return new e(i)},r.RTCIceCandidate.prototype=e.prototype,pe(r,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new r.RTCIceCandidate(t.candidate),writable:"false"}),t))}function Wt(r){!r.RTCIceCandidate||r.RTCIceCandidate&&"relayProtocol"in r.RTCIceCandidate.prototype||pe(r,"icecandidate",e=>{if(e.candidate){const t=Se.parseCandidate(e.candidate.candidate);t.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function Ze(r,e){if(!r.RTCPeerConnection)return;"sctp"in r.RTCPeerConnection.prototype||Object.defineProperty(r.RTCPeerConnection.prototype,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp}});const t=function(o){if(!o||!o.sdp)return!1;const u=Se.splitSections(o.sdp);return u.shift(),u.some(c=>{const d=Se.parseMLine(c);return d&&d.kind==="application"&&d.protocol.indexOf("SCTP")!==-1})},i=function(o){const u=o.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(u===null||u.length<2)return-1;const c=parseInt(u[1],10);return c!==c?-1:c},s=function(o){let u=65536;return e.browser==="firefox"&&(e.version<57?o===-1?u=16384:u=2147483637:e.version<60?u=e.version===57?65535:65536:u=2147483637),u},n=function(o,u){let c=65536;e.browser==="firefox"&&e.version===57&&(c=65535);const d=Se.matchPrefix(o.sdp,"a=max-message-size:");return d.length>0?c=parseInt(d[0].substring(19),10):e.browser==="firefox"&&u!==-1&&(c=2147483637),c},a=r.RTCPeerConnection.prototype.setRemoteDescription;r.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,e.browser==="chrome"&&e.version>=76){const{sdpSemantics:u}=this.getConfiguration();u==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp},enumerable:!0,configurable:!0})}if(t(arguments[0])){const u=i(arguments[0]),c=s(u),d=n(arguments[0],u);let h;c===0&&d===0?h=Number.POSITIVE_INFINITY:c===0||d===0?h=Math.max(c,d):h=Math.min(c,d);const p={};Object.defineProperty(p,"maxMessageSize",{get(){return h}}),this._sctp=p}return a.apply(this,arguments)}}function Qe(r){if(!(r.RTCPeerConnection&&"createDataChannel"in r.RTCPeerConnection.prototype))return;function e(i,s){const n=i.send;i.send=function(){const o=arguments[0],u=o.length||o.size||o.byteLength;if(i.readyState==="open"&&s.sctp&&u>s.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+s.sctp.maxMessageSize+" bytes)");return n.apply(i,arguments)}}const t=r.RTCPeerConnection.prototype.createDataChannel;r.RTCPeerConnection.prototype.createDataChannel=function(){const s=t.apply(this,arguments);return e(s,this),s},pe(r,"datachannel",i=>(e(i.channel,i.target),i))}function Xt(r){if(!r.RTCPeerConnection||"connectionState"in r.RTCPeerConnection.prototype)return;const e=r.RTCPeerConnection.prototype;Object.defineProperty(e,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(e,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(t){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),t&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=t)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(t=>{const i=e[t];e[t]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=s=>{const n=s.target;if(n._lastConnectionState!==n.connectionState){n._lastConnectionState=n.connectionState;const a=new Event("connectionstatechange",s);n.dispatchEvent(a)}return s},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}})}function Kt(r,e){if(!r.RTCPeerConnection||e.browser==="chrome"&&e.version>=71||e.browser==="safari"&&e.version>=605)return;const t=r.RTCPeerConnection.prototype.setRemoteDescription;r.RTCPeerConnection.prototype.setRemoteDescription=function(s){if(s&&s.sdp&&s.sdp.indexOf(`
91
+ a=extmap-allow-mixed`)!==-1){const n=s.sdp.split(`
92
+ `).filter(a=>a.trim()!=="a=extmap-allow-mixed").join(`
93
+ `);r.RTCSessionDescription&&s instanceof r.RTCSessionDescription?arguments[0]=new r.RTCSessionDescription({type:s.type,sdp:n}):s.sdp=n}return t.apply(this,arguments)}}function et(r,e){if(!(r.RTCPeerConnection&&r.RTCPeerConnection.prototype))return;const t=r.RTCPeerConnection.prototype.addIceCandidate;!t||t.length===0||(r.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(e.browser==="chrome"&&e.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():t.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function tt(r,e){if(!(r.RTCPeerConnection&&r.RTCPeerConnection.prototype))return;const t=r.RTCPeerConnection.prototype.setLocalDescription;!t||t.length===0||(r.RTCPeerConnection.prototype.setLocalDescription=function(){let s=arguments[0]||{};if(typeof s!="object"||s.type&&s.sdp)return t.apply(this,arguments);if(s={type:s.type,sdp:s.sdp},!s.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":s.type="offer";break;default:s.type="answer";break}return s.sdp||s.type!=="offer"&&s.type!=="answer"?t.apply(this,[s]):(s.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(a=>t.apply(this,[a]))})}const rh=Object.freeze(Object.defineProperty({__proto__:null,removeExtmapAllowMixed:Kt,shimAddIceCandidateNullOrEmpty:et,shimConnectionState:Xt,shimMaxMessageSize:Ze,shimParameterlessSetLocalDescription:tt,shimRTCIceCandidate:Ye,shimRTCIceCandidateRelayProtocol:Wt,shimSendThrowTypeError:Qe},Symbol.toStringTag,{value:"Module"}));function ih({window:r}={},e={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const t=Ni,i=Zu(r),s={browserDetails:i,commonShim:rh,extractVersion:Je,disableLog:Ju,disableWarnings:Yu,sdp:th};switch(i.browser){case"chrome":if(!Ji||!Gt||!e.shimChrome)return t("Chrome shim is not included in this adapter release."),s;if(i.version===null)return t("Chrome shim can not determine version, not shimming."),s;t("adapter.js shimming chrome."),s.browserShim=Ji,et(r,i),tt(r),ji(r,i),zi(r),Gt(r,i),Gi(r),Xi(r,i),Hi(r),qi(r),Ki(r,i),Ye(r),Wt(r),Xt(r),Ze(r,i),Qe(r),Kt(r,i);break;case"firefox":if(!as||!Ht||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),s;t("adapter.js shimming firefox."),s.browserShim=as,et(r,i),tt(r),Yi(r,i),Ht(r,i),Zi(r),ts(r),Qi(r),es(r),rs(r),is(r),ss(r),ns(r),os(r),Ye(r),Xt(r),Ze(r,i),Qe(r);break;case"safari":if(!gs||!e.shimSafari)return t("Safari shim is not included in this adapter release."),s;t("adapter.js shimming safari."),s.browserShim=gs,et(r,i),tt(r),ls(r),fs(r),us(r),cs(r),ds(r),ms(r),hs(r),_s(r),Ye(r),Wt(r),Ze(r,i),Qe(r),Kt(r,i);break;default:t("Unsupported browser!");break}return s}ih({window:typeof window>"u"?void 0:window});class sh extends Q{static async isSupported(e){if(e==="webTransport")return Promise.resolve(Ii.isSupported());try{return zu()||!window.RTCPeerConnection||!window.RTCPeerConnection.prototype.addTransceiver||!window.RTCPeerConnection.prototype.createDataChannel?!1:await Wu()&&await qu()}catch{return!1}}constructor(e){super(),this._streamManagerController=new lu,this._streamComposeController=new Eu(this._streamManagerController),this._streamConsumeController=new ju(this._streamComposeController),this._streamConsumeController.setPushConfig(e),this._observer=Ku,this._bindEvent()}async getDevicesList(e){return this._streamManagerController.getDevicesList(e)}async getCameras(){return this._streamManagerController.getCameras()}async getMicrophones(){return this._streamManagerController.getMicrophones()}async startCamera(e){return this._streamManagerController.startCameraCapture(e)}stopCamera(e){this._streamManagerController.stopCapture({streamId:e,type:S.Camera})}async startMicrophone(e){return await this._streamManagerController.startMicrophoneCapture(e)}stopMicrophone(e){this._streamManagerController.stopCapture({streamId:e,type:S.Microphone})}async startVideoFileCapture(e){return e?await this._streamManagerController.startVideoFileCapture(e):void 0}stopVideoFileCapture(e){this._streamManagerController.stopCapture({streamId:e,type:S.VideoFile})}async startScreenCapture(e=!1){return await this._streamManagerController.startScreenCapture(e)}stopScreenCapture(e){this._streamManagerController.stopCapture({streamId:e,type:S.Screen})}async startAudioFileCapture(e){return e?await this._streamManagerController.startAudioFileCapture(e):void 0}stopAudioFileCapture(e){this._streamManagerController.stopCapture({streamId:e,type:S.AudioFile})}async startImageCapture(e){return e?await this._streamManagerController.startImageCapture(e):void 0}stopImageCapture(e){this._streamManagerController.stopCapture({streamId:e,type:S.Image})}startCustomVideoCapture(e){return e?this._streamManagerController.startCustomVideoCapture(e):void 0}stopCustomVideoCapture(e){this._streamManagerController.stopCapture({streamId:e,type:S.CustomVideo})}startCustomAudioCapture(e){return e?this._streamManagerController.startCustomAudioCapture(e):void 0}stopCustomAudioCapture(e){this._streamManagerController.stopCapture({streamId:e,type:S.CustomAudio})}async startVolumeDetect(e){var t;e?await this._streamManagerController.startVolumeDetect(e):await((t=this._streamComposeController.getComposedStream().audioStream)==null?void 0:t.startVolumeDetect())}stopVolumeDetect(e){var t;e?this._streamManagerController.stopVolumeDetect(e):(t=this._streamComposeController.getComposedStream().audioStream)==null||t.stopVolumeDetect()}getVolume(e){var t;return e?this._streamManagerController.getVolume(e):((t=this._streamComposeController.getComposedStream().audioStream)==null?void 0:t.volume)??0}enableMixing(e){if(this.isPushing())throw new Error("can not change mixing while pushing");this._streamComposeController.enableMixing(e)}setMixingConfig(e){this._streamComposeController.setMixingConfig(e)}setRenderView(e){return this._streamConsumeController.setRenderView(e)}startPreview(){return this._streamConsumeController.startPreview()}stopPreview(){return this._streamConsumeController.stopPreview()}async startPush(e){return this._streamConsumeController.startPush(e)}addVideoStream(e){F(e)?e.forEach(t=>{this._streamComposeController.addVideoStream(t)}):this._streamComposeController.addVideoStream(e)}removeVideoStream(e){this._streamComposeController.removeVideoStream(e)}updateVideoStream(e){F(e)?this._streamComposeController.updateVideoStream(e):this._streamComposeController.updateVideoStream([e])}muteVideoStream(e){this._streamComposeController.muteVideoStream(e)}unmuteVideoStream(e){this._streamComposeController.unmuteVideoStream(e)}addAudioStream(e){F(e)?e.map(t=>this._streamComposeController.addAudioStream(t)):this._streamComposeController.addAudioStream(e)}removeAudioStream(e){this._streamComposeController.removeAudioStream(e)}updateAudioStream(e){F(e)?this._streamComposeController.updateAudioStream(e):this._streamComposeController.updateAudioStream([e])}muteAudioStream(e){this._streamComposeController.muteAudioStream(e)}unmuteAudioStream(e){this._streamComposeController.unmuteAudioStream(e)}setProperty(e,t){switch(e){case"setVideoResolution":this._streamManagerController.setVideoResolution(t);break;case"setVideoFps":this._streamManagerController.setVideoFps(t);break;case"setAudioSampleRate":this._streamManagerController.setAudioSampleRate(t);break;case"setPushMode":this._streamConsumeController.setPushMode(t);break;case"setVideoBitrate":this._streamConsumeController.setBitrate(t,"video");break;case"setAudioBitrate":this._streamConsumeController.setBitrate(t,"audio");break;case"setVolumeDetectScriptUrl":Ue.instance.volumeDetectScriptUrl=t;break;case"setMixerWorkerScriptUrl":this._streamComposeController.setMixerWorkerScript(t);break}}setVideoQuality(e){if(this._streamConsumeController.pushMode==="webTransport"&&["120p","180p","240p"].indexOf(e)!==-1)throw new Error("quality not allowed lower than 360p on rtmp mode");const{width:t,height:i,frameRate:s,bitrate:n}=ve(e,"video");this._streamManagerController.setVideoResolution({width:t,height:i}),this._streamManagerController.setVideoFps(s),this._streamComposeController.setVideoQuality({width:t,height:i,frameRate:s}),this._streamConsumeController.setBitrate(n,"video")}setAudioQuality(e){const{sampleRate:t,bitrate:i}=ve(e,"audio");this._streamManagerController.setAudioSampleRate(t),this._streamConsumeController.setBitrate(i,"audio")}getMediaStream(e){return this._streamManagerController.getStreamById(e).mediaStream}stopPush(){return this._streamConsumeController.stopPush()}isPushing(){return this._streamConsumeController.isPushing()}getStats(){return this._streamConsumeController.getStats()}getPreviewElement(){return this._streamConsumeController.getPreviewElement()}_bindEvent(){this._streamManagerController.on(z.Error,e=>{this.observer.onError(e.code,e.message,e.ext)}),this._streamManagerController.on(z.Interrupted,e=>{this.observer.onCaptureInterrupted(e.id)}),this._streamConsumeController.on(A.PushStart,()=>{this.observer.onPushStart()}),this._streamConsumeController.on(A.PushStop,()=>{this.observer.onPushStop()}),this._streamConsumeController.on(A.RTCConnectStateChanged,e=>{this.observer.onPushStatusUpdate(sr[e],e)}),this._streamConsumeController.on(A.PushError,e=>{this.observer.onError(e.code,e.message,e.ext)}),this._streamManagerController.on(z.DeviceStopCapture,e=>{this.observer.onStopCapture(e.id)}),this._streamConsumeController.on(A.CaptureFirstAudioFrame,()=>{this.observer.onCaptureFirstAudioFrame()}),this._streamConsumeController.on(A.CaptureFirstVideoFrame,()=>{this.observer.onCaptureFirstVideoFrame()}),ro(e=>{e.deviceInfo.kind==="videoinput"?this.observer.onCameraChanged(e.deviceInfo):e.deviceInfo.kind==="audioinput"&&this.observer.onMicrophoneChanged(e.deviceInfo)})}async destroy(){await this._streamConsumeController.destroy(),this._streamManagerController.destroy()}get observer(){return this._observer}get isEnableMixing(){return this._streamComposeController.isEnableMixing}get pushMode(){return this._streamConsumeController.pushMode}}return sh});