@byteplus/vepusher 2.0.4-rc.0 → 2.0.4-rc.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.es.d.ts +31 -0
- package/dist/index.es.js +895 -860
- package/dist/index.umd.js +6 -6
- package/package.json +1 -1
package/dist/index.umd.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
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 hh=Object.defineProperty;var ph=($,I,Z)=>I in $?hh($,I,{enumerable:!0,configurable:!0,writable:!0,value:Z}):$[I]=Z;var m=($,I,Z)=>ph($,typeof I!="symbol"?I+"":I,Z);var Ss,Ts,Es,bs,ks,Ps;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 Zs(){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,d,c){this.fn=u,this.context=d,this.once=c||!1}function n(u,d,c,h,p){if(typeof c!="function")throw new TypeError("The listener must be a function");var l=new s(c,h||u,p),f=t?t+d:d;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,d){--u._eventsCount===0?u._events=new i:delete u._events[d]}function o(){this._events=new i,this._eventsCount=0}o.prototype.eventNames=function(){var d=[],c,h;if(this._eventsCount===0)return d;for(h in c=this._events)e.call(c,h)&&d.push(t?h.slice(1):h);return Object.getOwnPropertySymbols?d.concat(Object.getOwnPropertySymbols(c)):d},o.prototype.listeners=function(d){var c=t?t+d:d,h=this._events[c];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(d){var c=t?t+d:d,h=this._events[c];return h?h.fn?1:h.length:0},o.prototype.emit=function(d,c,h,p,l,f){var g=t?t+d:d;if(!this._events[g])return!1;var _=this._events[g],T=arguments.length,b,v;if(_.fn){switch(_.once&&this.removeListener(d,_.fn,void 0,!0),T){case 1:return _.fn.call(_.context),!0;case 2:return _.fn.call(_.context,c),!0;case 3:return _.fn.call(_.context,c,h),!0;case 4:return _.fn.call(_.context,c,h,p),!0;case 5:return _.fn.call(_.context,c,h,p,l),!0;case 6:return _.fn.call(_.context,c,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(d,_[v].fn,void 0,!0),T){case 1:_[v].fn.call(_[v].context);break;case 2:_[v].fn.call(_[v].context,c);break;case 3:_[v].fn.call(_[v].context,c,h);break;case 4:_[v].fn.call(_[v].context,c,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(d,c,h){return n(this,d,c,h,!1)},o.prototype.once=function(d,c,h){return n(this,d,c,h,!0)},o.prototype.removeListener=function(d,c,h,p){var l=t?t+d:d;if(!this._events[l])return this;if(!c)return a(this,l),this;var f=this._events[l];if(f.fn)f.fn===c&&(!p||f.once)&&(!h||f.context===h)&&a(this,l);else{for(var g=0,_=[],T=f.length;g<T;g++)(f[g].fn!==c||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(d){var c;return d?(c=t?t+d:d,this._events[c]&&a(this,c)):(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 Qs=Zs();const Q=I(Qs);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||{}),it=(r=>(r.SizeChange="sizeChange",r))(it||{}),st=(r=>(r.Portrait="portrait",r.Landscape="landscape",r))(st||{});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||{}),D=(r=>(r.ENDED="ended",r.MUTE="mute",r.UNMUTE="unmute",r.PLAY_FAILED="play-failed",r.SIZE_CHANGE="size-change",r))(D||{});const O=[];for(let r=0;r<256;++r)O.push((r+256).toString(16).slice(1));function en(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 nt;const tn=new Uint8Array(16);function rn(){if(!nt){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");nt=crypto.getRandomValues.bind(crypto)}return nt(tn)}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))??rn();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,en(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 sn extends cr{constructor(t){super();m(this,"previousNode",null);m(this,"source");this.source=t}available(){return this.source.available()}destroy(){super.destroy()}}class nn extends sn{constructor(){super(...arguments);m(this,"_node")}createNode(t){if(this._node)return this._node;let i;if(this.source instanceof vr){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__",on="[VE-CAPTURE]";function an(){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=cn();an()&&console.log(`${s}-${on}%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 cn(){const r=new Date;return`${r.toTimeString().split(" ")[0]}:${r.getMilliseconds().toString().padStart(3,"0")}`}function ot(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 at{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 ct(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 lr=ct()==="firefox",Le=ct()==="safari";ct(),!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());const dn=!x()&&!!/(iphone|ipad|ipod)/i.exec(P());!x()&&/android/i.test(P()),!x()&&/windows/i.test(P()),!x()&&/openharmony/i.test(P());let mr="0";const un=!x()&&((Ss=P().match(/version\/(\d+)/i))==null?void 0:Ss[1]);Le&&un&&(mr=(Ts=navigator.userAgent.match(/version\/(\d+\.\d+)/i))==null?void 0:Ts[1]),!x()&&((Es=P().match(/firefox\/(\d+)/i))==null||Es[1]);const dt=mr;!x()&&((ks=(bs=P().match(/ ([\d_]+) like mac os x/i))==null?void 0:bs[1])==null||ks.split("_").map(r=>parseInt(r))),!x()&&((Ps=P().match(/chrome\/(\d+)/i))==null||Ps[1]);function hn(){var r;return!!((r=navigator==null?void 0:navigator.permissions)!=null&&r.query)}function ut(){return!!(navigator!=null&&navigator.mediaDevices)}function pn(){var r;return ut()&&!!((r=navigator==null?void 0:navigator.mediaDevices)!=null&&r.getUserMedia)}function ln(){return!!Promise.withResolvers}function mn(){return!(Le&&dt==="16.1")}function fn(){return!(Le&&dt&&["16.1","16.2","16.3"].includes(dt))}function _n(){return!lr}function gn(){return typeof CanvasCaptureMediaStreamTrack<"u"}function vn(r){return typeof r.requestFrame=="function"}function Cn(){return!!ut()&&typeof navigator.mediaDevices.ondevicechange<"u"&&typeof navigator.mediaDevices.addEventListener=="function"}const q={permissionQuery:hn,mediaDevices:ut,settingResolutionInGetDisplayMedia:mn,promiseWithResolvers:ln,getUserMedia:pn,isolateEnumerateDevices:_n,supportIdealParamsInGetDisplayMedia:fn,canvasCaptureMediaStreamTrack:gn,requestFrameOnMediaStream:vn,ondevicechange:Cn};function yn(){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 fr(r={}){const{timeout:e,message:t}={timeout:0,message:new C(y.UNEXPECTED_ERROR,"unexpected timeout"),...r},{promise:i,resolve:s,reject:n}=yn();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 Sn={playsinline:"","webkit-playsinline":"","x5-playsinline":"","x5-video-player-type":"h5","x-webkit-airplay":"allow",preload:"metadata",muted:"",crossOrigin:"anonymous"},Tn={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=En(o),this._stream=o}else if(e.url)i=bn(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}=fr({timeout:2e3,message:new C(y.PLAY_FAILED,"load media timeout")});this._readyLock=s,this._releaseReadyLock=n,this._throwReadyLock=a,this._element=new at(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 En(r){let e="audio";r.getVideoTracks().length>0&&(e="video");const t=_r(e==="video"?E.VIDEO:E.AUDIO);return t.srcObject=r,t}function bn(r){const{url:e,kind:t,loop:i}=r,s=_r(t);return s.src=e,s.loop=i,s}function _r(r){if(r===E.VIDEO)return ot(E.VIDEO,{style:{width:"100%",height:"100%"},attributes:Sn});if(r===E.AUDIO)return ot(E.AUDIO,{style:{display:"none"},attributes:Tn});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 gr{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=kn({url:e.url,width:t,height:i});this._image=new at(o);const{promise:u,resolve:d,reject:c}=fr({timeout:2e3,message:new C(y.PLAY_FAILED,"load image timeout")});this._readyLock=u,this._releaseReadyLock=d,this._throwReadyLock=c,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 kn({url:r,height:e,width:t}){const i=ot("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 at(t),this._bindTrackEvent(this._track)):t instanceof Ee?(this._element=t,t.addReferenceTrack(this)):t instanceof gr&&(this._element=t)}_bindTrackEvent(t){t.on("ended",this._handleTrackEnded.bind(this)),t.on("mute",()=>{this.emit(D.MUTE)}),t.on("unmute",()=>{this.emit(D.UNMUTE)})}_handleTrackEnded(){this.emit(D.ENDED),this.destroy()}handlePlayFailed(){this.emit(D.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 Fe 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 nn(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 Pn extends Fe{constructor(){super(...arguments);m(this,"logger",new L("MicrophoneAudioTrack"))}}class xn extends Fe{constructor(){super(...arguments);m(this,"logger",new L("ScreenAudioTrack"))}}class vr extends Fe{constructor(){super(...arguments);m(this,"logger",new L("MediaAudioTrack"))}handlePlayFailed(){this.emit(D.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 Rn extends Fe{constructor(){super(...arguments);m(this,"logger",new L("CustomAudioTrack"))}}let An=1;const ft=new L("PromiseQueue");class wn{constructor(e){m(this,"lockingPromise",Promise.resolve());m(this,"locks",0);m(this,"name","");m(this,"lockId");m(this,"closeReason");this.lockId=An++,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 On=300,In=3e3,G=new L("Devices");class Dn extends ht{constructor(){super();m(this,"_deviceMap",{audioinput:[],audiooutput:[],videoinput:[]});m(this,"_permissions",{[E.AUDIO]:!1,[E.VIDEO]:!1});m(this,"_changedQueue",new wn("device changed queue"));this._init()}async _init(){this._initDeviceChanged(),await this._initPermissionChanged();const t=Tr(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()},In);return}q.ondevicechange()&&navigator.mediaDevices.addEventListener("devicechange",()=>{G.info("devicechange"),setTimeout(()=>{this._handleDeviceChanged()},On)})}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&&Cr(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),Cr(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=Sr(this._deviceMap);let s=[];const n=Tr(this._permissions);n.length===0?G.warn("_handleDeviceChanged","no permission, use empty list"):(await this._refreshDevices(n),s=Sr(this._deviceMap)),s.forEach(a=>{i.findIndex(u=>yr(u,a))!==-1||this.emit("onDeviceStateChanged",{deviceInfo:a,deviceState:"active"})}),i.forEach(a=>{s.findIndex(u=>yr(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 Cr(r){r.getTracks().forEach(e=>e.stop())}function yr(r,e){return r.deviceId===e.deviceId}function Sr(r){return Array.from([...r.audioinput.values(),...r.videoinput.values(),...r.audiooutput.values()])}function Tr(r){const e=[];return r.audio&&e.push(E.AUDIO),r.video&&e.push(E.VIDEO),e}const _t=new Dn;class gt{constructor(){m(this,"id",oe())}position(e,t){return new Mn(this,{x:e,y:t})}scale(e){return new Ln(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 Ln 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 Fn extends gt{constructor(t){super();m(this,"previousNode",null);m(this,"_source");this._source=t}available(){return this._source.available()}}class Ne extends Fn{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 Ne(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 Nn 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 Ne(this);return this.logger.info("node",t),t}destroy(){this.logger.warn("destroy"),super.destroy()}}const Vn=500;class Ve 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(D.SIZE_CHANGE,{width:s,height:n})},Vn)})}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 Ne(this)}destroy(){clearTimeout(this.sizeChangeTimer),super.destroy()}}class Un extends Ve{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 $n extends Ve{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 Bn extends Ve{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 jn extends Ve{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 Er(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 zn(r){return _t.enumerateDevices(r)}async function Gn(r){_t.removeAllListeners("onDeviceStateChanged"),_t.on("onDeviceStateChanged",r)}async function Hn(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&&Er(t,r),!t)throw new C(y.UNEXPECTED_TYPE,"got falsy in track");return new Un(t)}async function qn(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(d){throw new C(y.CAPTURE_FAILED,"got error when capture screen",d)}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"&&Er(a,s);const u=[];return u.push(new $n(a)),o&&u.push(new xn(o)),u}async function Wn(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 vr(n)),i&&a.push(new Bn(n)),await n.isReady(),a}async function Xn(r){const e=new gr(r);return await e.isReady(),new Nn(e)}async function Kn(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 Pn(t)}function Jn(r){if(!r||r.kind!=="video")throw new C(y.UNEXPECTED_TYPE,"error custom video track type");return new jn(r)}function Yn(r){if(!r||r.kind!=="audio")throw new C(y.UNEXPECTED_TYPE,"error custom audio track type");return new Rn(r)}const Zn=W.invoke(zn,"enumerateInputDevices"),Qn=W.invoke(Hn,"createCameraTrack"),eo=W.invoke(Xn,"createPictureTrack"),br=W.invoke(Wn,"createMediaTracks"),to=W.invoke(Kn,"createMicrophoneTrack"),ro=W.invoke(qn,"createScreenTracks"),io=W.invoke(Gn,"onDeviceChanged"),so=W.invoke(Jn,"createCustomVideoTrack"),no=W.invoke(Yn,"createCustomAudioTrack");var vt=(r=>(r.PAUSING="pausing",r))(vt||{});const oo={sampleRate:48e3,keepAlive:!0},kr=new Map,be=new L("Mixer");class ao 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={...oo,...t},this._context=co(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 co(r){const{sampleRate:e,keepAlive:t}=r;let i=kr.get(e);return(!i||i.state==="closed")&&(i=new AudioContext({sampleRate:e}),kr.set(e,i)),t&&(i.onstatechange=()=>{Ct(i)}),i}function Ct(r){if(r.state==="suspended"||r.state==="interrupted")return r.resume()}const uo=r=>(e,t)=>(r.set(e,t),t),Pr=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,xr=536870912,Rr=xr*2,ho=(r,e)=>t=>{const i=e.get(t);let s=i===void 0?t.size:i<Rr?i+1:0;if(!t.has(s))return r(t,s);if(t.size<xr){for(;t.has(s);)s=Math.floor(Math.random()*Rr);return r(t,s)}if(t.size>Pr)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()*Pr);return r(t,s)},Ar=new WeakMap,po=uo(Ar),ee=ho(po,Ar),lo=r=>r.method!==void 0&&r.method==="call",mo=r=>typeof r.id=="number"&&typeof r.result=="boolean",wr=((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:d})=>{if(lo(d)){const{params:{timerId:c,timerType:h}}=d;if(h==="interval"){const p=e.get(c);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!==c||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(c);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!==c||l.timerType!==h)throw new Error("The timer is in an undefined state.")}else typeof p=="function"&&(p(),t.delete(c))}}else if(mo(d)){const{id:c}=d,h=i.get(c);if(h===void 0)throw new Error("The timer is in an undefined state.");const{timerId:p,timerType:l}=h;i.delete(c),l==="interval"?e.delete(p):t.delete(p)}else{const{error:{message:c}}=d;throw new Error(c)}}),{clearInterval:d=>{if(typeof e.get(d)=="function"){const c=ee(i);i.set(c,{timerId:d,timerType:"interval"}),e.set(d,c),s.postMessage({id:c,method:"clear",params:{timerId:d,timerType:"interval"}})}},clearTimeout:d=>{if(typeof t.get(d)=="function"){const c=ee(i);i.set(c,{timerId:d,timerType:"timeout"}),t.set(d,c),s.postMessage({id:c,method:"clear",params:{timerId:d,timerType:"timeout"}})}},setInterval:(d,c=0,...h)=>{const p=ee(e);return e.set(p,()=>{d(...h),typeof e.get(p)=="function"&&s.postMessage({id:null,method:"set",params:{delay:c,now:performance.timeOrigin+performance.now(),timerId:p,timerType:"interval"}})}),s.postMessage({id:null,method:"set",params:{delay:c,now:performance.timeOrigin+performance.now(),timerId:p,timerType:"interval"}}),p},setTimeout:(d,c=0,...h)=>{const p=ee(t);return t.set(p,()=>d(...h)),s.postMessage({id:null,method:"set",params:{delay:c,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})}}))})();`),fo=r=>wr().clearTimeout(r),_o=(...r)=>wr().setTimeout(...r),go=r=>r.method!==void 0&&r.method==="call",vo=r=>typeof r.id=="number"&&typeof r.result=="boolean",Co=r=>{const e=new Map([[0,()=>{}]]),t=new Map([[0,()=>{}]]),i=new Map,s=new Worker(r,{credentials:"omit"});return s.addEventListener("message",({data:d})=>{if(go(d)){const{params:{timerId:c,timerType:h}}=d;if(h==="interval"){const p=e.get(c);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!==c||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(c);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!==c||l.timerType!==h)throw new Error("The timer is in an undefined state.")}else typeof p=="function"&&(p(),t.delete(c))}}else if(vo(d)){const{id:c}=d,h=i.get(c);if(h===void 0)throw new Error("The timer is in an undefined state.");const{timerId:p,timerType:l}=h;i.delete(c),l==="interval"?e.delete(p):t.delete(p)}else{const{error:{message:c}}=d;throw new Error(c)}}),{clearInterval:d=>{if(typeof e.get(d)=="function"){const c=ee(i);i.set(c,{timerId:d,timerType:"interval"}),e.set(d,c),s.postMessage({id:c,method:"clear",params:{timerId:d,timerType:"interval"}})}},clearTimeout:d=>{if(typeof t.get(d)=="function"){const c=ee(i);i.set(c,{timerId:d,timerType:"timeout"}),t.set(d,c),s.postMessage({id:c,method:"clear",params:{timerId:d,timerType:"timeout"}})}},setInterval:(d,c=0,...h)=>{const p=ee(e);return e.set(p,()=>{d(...h),typeof e.get(p)=="function"&&s.postMessage({id:null,method:"set",params:{delay:c,now:performance.timeOrigin+performance.now(),timerId:p,timerType:"interval"}})}),s.postMessage({id:null,method:"set",params:{delay:c,now:performance.timeOrigin+performance.now(),timerId:p,timerType:"interval"}}),p},setTimeout:(d,c=0,...h)=>{const p=ee(t);return t.set(p,()=>d(...h)),s.postMessage({id:null,method:"set",params:{delay:c,now:performance.timeOrigin+performance.now(),timerId:p,timerType:"timeout"}}),p}}},yo={width:640,height:480,frameRate:30,backgroundColor:"#000000"},Ue=new L("View");class So{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)});Ue.info("ctor",e),this._config={...yo,...e};const{context:t,canvas:i}=pr(this._config);this._context=t,this._canvas=i,this._customSetTimeout=_o,this._customClearTimeout=fo}setWorkerTimerScriptUrl(e){if(this._workerTimerScriptUrl=e,this._workerTimerScriptUrl){const t=Co(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=[]){Ue.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(Ue.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 Ue.info("element"),this._paintLoop(),this._canvas}stop(){this._stopped=!0}}function To(){return Math.random().toString(36).slice(-8)}const Eo=`
|
|
1
|
+
(function($,D){typeof exports=="object"&&typeof module<"u"?module.exports=D():typeof define=="function"&&define.amd?define(D):($=typeof globalThis<"u"?globalThis:$||self,$["ve-pusher"]=D())})(this,function(){"use strict";var lh=Object.defineProperty;var mh=($,D,Z)=>D in $?lh($,D,{enumerable:!0,configurable:!0,writable:!0,value:Z}):$[D]=Z;var m=($,D,Z)=>mh($,typeof D!="symbol"?D+"":D,Z);var bs,ks,Ps,xs,Rs,As;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 D(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Z={exports:{}},tr;function tn(){return tr||(tr=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,d,c){this.fn=u,this.context=d,this.once=c||!1}function n(u,d,c,h,p){if(typeof c!="function")throw new TypeError("The listener must be a function");var l=new s(c,h||u,p),f=t?t+d:d;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,d){--u._eventsCount===0?u._events=new i:delete u._events[d]}function o(){this._events=new i,this._eventsCount=0}o.prototype.eventNames=function(){var d=[],c,h;if(this._eventsCount===0)return d;for(h in c=this._events)e.call(c,h)&&d.push(t?h.slice(1):h);return Object.getOwnPropertySymbols?d.concat(Object.getOwnPropertySymbols(c)):d},o.prototype.listeners=function(d){var c=t?t+d:d,h=this._events[c];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(d){var c=t?t+d:d,h=this._events[c];return h?h.fn?1:h.length:0},o.prototype.emit=function(d,c,h,p,l,f){var g=t?t+d:d;if(!this._events[g])return!1;var _=this._events[g],T=arguments.length,b,v;if(_.fn){switch(_.once&&this.removeListener(d,_.fn,void 0,!0),T){case 1:return _.fn.call(_.context),!0;case 2:return _.fn.call(_.context,c),!0;case 3:return _.fn.call(_.context,c,h),!0;case 4:return _.fn.call(_.context,c,h,p),!0;case 5:return _.fn.call(_.context,c,h,p,l),!0;case 6:return _.fn.call(_.context,c,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(d,_[v].fn,void 0,!0),T){case 1:_[v].fn.call(_[v].context);break;case 2:_[v].fn.call(_[v].context,c);break;case 3:_[v].fn.call(_[v].context,c,h);break;case 4:_[v].fn.call(_[v].context,c,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(d,c,h){return n(this,d,c,h,!1)},o.prototype.once=function(d,c,h){return n(this,d,c,h,!0)},o.prototype.removeListener=function(d,c,h,p){var l=t?t+d:d;if(!this._events[l])return this;if(!c)return a(this,l),this;var f=this._events[l];if(f.fn)f.fn===c&&(!p||f.once)&&(!h||f.context===h)&&a(this,l);else{for(var g=0,_=[],T=f.length;g<T;g++)(f[g].fn!==c||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(d){var c;return d?(c=t?t+d:d,this._events[c]&&a(this,c)):(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 rn=tn();const Q=D(rn);var rr=(r=>(r.LeftToRight="LeftToRight",r.UpToDown="UpToDown",r.All="All",r.None="None",r))(rr||{}),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||{}),ir=(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))(ir||{}),sr=(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))(sr||{}),nr=(r=>(r.STANDARD="48000x40",r.HIGH="48000x128",r))(nr||{}),ne=(r=>(r.VideoStreamChange="videoStreamChange",r.AudioStreamChange="audioStreamChange",r))(ne||{}),or=(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))(or||{}),it=(r=>(r.SizeChange="sizeChange",r))(it||{}),st=(r=>(r.Portrait="portrait",r.Landscape="landscape",r))(st||{});const ar="720p-1",cr="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||{}),I=(r=>(r.ENDED="ended",r.MUTE="mute",r.UNMUTE="unmute",r.PLAY_FAILED="play-failed",r.SIZE_CHANGE="size-change",r))(I||{});const O=[];for(let r=0;r<256;++r)O.push((r+256).toString(16).slice(1));function sn(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 nt;const nn=new Uint8Array(16);function on(){if(!nt){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");nt=crypto.getRandomValues.bind(crypto)}return nt(nn)}const dr={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function oe(r,e,t){var s;if(dr.randomUUID&&!r)return dr.randomUUID();r=r||{};const i=r.random??((s=r.rng)==null?void 0:s.call(r))??on();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,sn(i)}class ur{constructor(){m(this,"id",oe());m(this,"_nextNode");m(this,"_track");m(this,"_destNode")}gain(e){if(this._nextNode instanceof hr)return this._nextNode.g=e,this._nextNode;const t=new hr(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 hr extends ur{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 an extends ur{constructor(t){super();m(this,"previousNode",null);m(this,"source");this.source=t}available(){return this.source.available()}destroy(){super.destroy()}}class cn extends an{constructor(){super(...arguments);m(this,"_node")}createNode(t){if(this._node)return this._node;let i;if(this.source instanceof yr){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 pr={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"}},lr="__debug__",dn="[VE-CAPTURE]";function un(){if(typeof location>"u"||typeof localStorage>"u")return!1;let r=!1;return location.href.includes(lr)&&(r=!0),localStorage.getItem(lr)&&(r=!0),r}let L=class{constructor(e){m(this,"moduleName");this.moduleName=e}print(e,t,...i){const s=hn();un()&&console.log(`${s}-${dn}%c[${pr[e].text}]%c[${this.moduleName}][${t}]`,`background-color:${pr[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 hn(){const r=new Date;return`${r.toTimeString().split(" ")[0]}:${r.getMilliseconds().toString().padStart(3,"0")}`}function ot(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 mr({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 at{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 ct(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 fr=ct()==="firefox",Le=ct()==="safari";ct(),!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());const pn=!x()&&!!/(iphone|ipad|ipod)/i.exec(P());!x()&&/android/i.test(P()),!x()&&/windows/i.test(P()),!x()&&/openharmony/i.test(P());let _r="0";const ln=!x()&&((bs=P().match(/version\/(\d+)/i))==null?void 0:bs[1]);Le&&ln&&(_r=(ks=navigator.userAgent.match(/version\/(\d+\.\d+)/i))==null?void 0:ks[1]),!x()&&((Ps=P().match(/firefox\/(\d+)/i))==null||Ps[1]);const dt=_r;!x()&&((Rs=(xs=P().match(/ ([\d_]+) like mac os x/i))==null?void 0:xs[1])==null||Rs.split("_").map(r=>parseInt(r))),!x()&&((As=P().match(/chrome\/(\d+)/i))==null||As[1]);function mn(){var r;return!!((r=navigator==null?void 0:navigator.permissions)!=null&&r.query)}function ut(){return!!(navigator!=null&&navigator.mediaDevices)}function fn(){var r;return ut()&&!!((r=navigator==null?void 0:navigator.mediaDevices)!=null&&r.getUserMedia)}function _n(){return!!Promise.withResolvers}function gn(){return!(Le&&dt==="16.1")}function vn(){return!(Le&&dt&&["16.1","16.2","16.3"].includes(dt))}function Cn(){return!fr}function yn(){return typeof CanvasCaptureMediaStreamTrack<"u"}function Sn(r){return typeof r.requestFrame=="function"}function Tn(){return!!ut()&&typeof navigator.mediaDevices.ondevicechange<"u"&&typeof navigator.mediaDevices.addEventListener=="function"}const q={permissionQuery:mn,mediaDevices:ut,settingResolutionInGetDisplayMedia:gn,promiseWithResolvers:_n,getUserMedia:fn,isolateEnumerateDevices:Cn,supportIdealParamsInGetDisplayMedia:vn,canvasCaptureMediaStreamTrack:yn,requestFrameOnMediaStream:Sn,ondevicechange:Tn};function En(){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 gr(r={}){const{timeout:e,message:t}={timeout:0,message:new C(y.UNEXPECTED_ERROR,"unexpected timeout"),...r},{promise:i,resolve:s,reject:n}=En();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 bn={playsinline:"","webkit-playsinline":"","x5-playsinline":"","x5-video-player-type":"h5","x-webkit-airplay":"allow",preload:"metadata",muted:"",crossOrigin:"anonymous"},kn={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=Pn(o),this._stream=o}else if(e.url)i=xn(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}=gr({timeout:2e3,message:new C(y.PLAY_FAILED,"load media timeout")});this._readyLock=s,this._releaseReadyLock=n,this._throwReadyLock=a,this._element=new at(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 Pn(r){let e="audio";r.getVideoTracks().length>0&&(e="video");const t=vr(e==="video"?E.VIDEO:E.AUDIO);return t.srcObject=r,t}function xn(r){const{url:e,kind:t,loop:i}=r,s=vr(t);return s.src=e,s.loop=i,s}function vr(r){if(r===E.VIDEO)return ot(E.VIDEO,{style:{width:"100%",height:"100%"},attributes:bn});if(r===E.AUDIO)return ot(E.AUDIO,{style:{display:"none"},attributes:kn});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 Cr{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}=mr({width:t,height:i});this._context=n,this._canvas=a;const o=Rn({url:e.url,width:t,height:i});this._image=new at(o);const{promise:u,resolve:d,reject:c}=gr({timeout:2e3,message:new C(y.PLAY_FAILED,"load image timeout")});this._readyLock=u,this._releaseReadyLock=d,this._throwReadyLock=c,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 Rn({url:r,height:e,width:t}){const i=ot("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 at(t),this._bindTrackEvent(this._track)):t instanceof Ee?(this._element=t,t.addReferenceTrack(this)):t instanceof Cr&&(this._element=t)}_bindTrackEvent(t){t.on("ended",this._handleTrackEnded.bind(this)),t.on("mute",()=>{this.emit(I.MUTE)}),t.on("unmute",()=>{this.emit(I.UNMUTE)})}_handleTrackEnded(){this.emit(I.ENDED),this.destroy()}handlePlayFailed(){this.emit(I.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 Fe 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 cn(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 An extends Fe{constructor(){super(...arguments);m(this,"logger",new L("MicrophoneAudioTrack"))}}class wn extends Fe{constructor(){super(...arguments);m(this,"logger",new L("ScreenAudioTrack"))}}class yr extends Fe{constructor(){super(...arguments);m(this,"logger",new L("MediaAudioTrack"))}handlePlayFailed(){this.emit(I.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 On extends Fe{constructor(){super(...arguments);m(this,"logger",new L("CustomAudioTrack"))}}let Dn=1;const ft=new L("PromiseQueue");class In{constructor(e){m(this,"lockingPromise",Promise.resolve());m(this,"locks",0);m(this,"name","");m(this,"lockId");m(this,"closeReason");this.lockId=Dn++,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 Mn=300,Ln=3e3,G=new L("Devices");class Fn extends ht{constructor(){super();m(this,"_deviceMap",{audioinput:[],audiooutput:[],videoinput:[]});m(this,"_permissions",{[E.AUDIO]:!1,[E.VIDEO]:!1});m(this,"_changedQueue",new In("device changed queue"));this._init()}async _init(){this._initDeviceChanged(),await this._initPermissionChanged();const t=br(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()},Ln);return}q.ondevicechange()&&navigator.mediaDevices.addEventListener("devicechange",()=>{G.info("devicechange"),setTimeout(()=>{this._handleDeviceChanged()},Mn)})}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&&Sr(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),Sr(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=Er(this._deviceMap);let s=[];const n=br(this._permissions);n.length===0?G.warn("_handleDeviceChanged","no permission, use empty list"):(await this._refreshDevices(n),s=Er(this._deviceMap)),s.forEach(a=>{i.findIndex(u=>Tr(u,a))!==-1||this.emit("onDeviceStateChanged",{deviceInfo:a,deviceState:"active"})}),i.forEach(a=>{s.findIndex(u=>Tr(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 Sr(r){r.getTracks().forEach(e=>e.stop())}function Tr(r,e){return r.deviceId===e.deviceId}function Er(r){return Array.from([...r.audioinput.values(),...r.videoinput.values(),...r.audiooutput.values()])}function br(r){const e=[];return r.audio&&e.push(E.AUDIO),r.video&&e.push(E.VIDEO),e}const _t=new Fn,gt={LeftToRight:"LeftToRight",UpToDown:"UpToDown",All:"All"};class vt{constructor(){m(this,"id",oe())}position(e,t){return new Nn(this,{x:e,y:t})}scale(e){return new kr(this,{s:e})}mirror(e){return new kr(this,{mirrorType:e})}available(){var e;return((e=this.previousNode)==null?void 0:e.available())??!1}}class Nn extends vt{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 kr extends vt{constructor(t,i){super();m(this,"previousNode");m(this,"_scaleParams",[1,1]);if(this.previousNode=t,i.mirrorType)switch(i.mirrorType){case gt.LeftToRight:this._scaleParams=[-1,1];break;case gt.UpToDown:this._scaleParams=[1,-1];break;case gt.All:this._scaleParams=[-1,-1];break;default:this._scaleParams=[1,1];break}else i.s&&(this._scaleParams=[i.s,i.s])}paint(t){t.scale(this._scaleParams[0],this._scaleParams[1])}}class Vn extends vt{constructor(t){super();m(this,"previousNode",null);m(this,"_source");this._source=t}available(){return this._source.available()}}class Ne extends Vn{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 Ne(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 Un 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 Ne(this);return this.logger.info("node",t),t}destroy(){this.logger.warn("destroy"),super.destroy()}}const $n=500;class Ve 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(I.SIZE_CHANGE,{width:s,height:n})},$n)})}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 Ne(this)}destroy(){clearTimeout(this.sizeChangeTimer),super.destroy()}}class Bn extends Ve{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 jn extends Ve{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 zn extends Ve{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 Gn extends Ve{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 Pr(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 Hn(r){return _t.enumerateDevices(r)}async function qn(r){_t.removeAllListeners("onDeviceStateChanged"),_t.on("onDeviceStateChanged",r)}async function Wn(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&&Pr(t,r),!t)throw new C(y.UNEXPECTED_TYPE,"got falsy in track");return new Bn(t)}async function Xn(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(d){throw new C(y.CAPTURE_FAILED,"got error when capture screen",d)}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"&&Pr(a,s);const u=[];return u.push(new jn(a)),o&&u.push(new wn(o)),u}async function Kn(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 yr(n)),i&&a.push(new zn(n)),await n.isReady(),a}async function Jn(r){const e=new Cr(r);return await e.isReady(),new Un(e)}async function Yn(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 An(t)}function Zn(r){if(!r||r.kind!=="video")throw new C(y.UNEXPECTED_TYPE,"error custom video track type");return new Gn(r)}function Qn(r){if(!r||r.kind!=="audio")throw new C(y.UNEXPECTED_TYPE,"error custom audio track type");return new On(r)}const eo=W.invoke(Hn,"enumerateInputDevices"),to=W.invoke(Wn,"createCameraTrack"),ro=W.invoke(Jn,"createPictureTrack"),xr=W.invoke(Kn,"createMediaTracks"),io=W.invoke(Yn,"createMicrophoneTrack"),so=W.invoke(Xn,"createScreenTracks"),no=W.invoke(qn,"onDeviceChanged"),oo=W.invoke(Zn,"createCustomVideoTrack"),ao=W.invoke(Qn,"createCustomAudioTrack");var Ct=(r=>(r.PAUSING="pausing",r))(Ct||{});const co={sampleRate:48e3,keepAlive:!0},Rr=new Map,be=new L("Mixer");class uo 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={...co,...t},this._context=ho(this._config),this._bindContextEvent(this._context)}mix(t){be.info("mix",t),yt(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_",Ct.PAUSING),this.emit(Ct.PAUSING))}track(){if(be.info("track"),yt(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 ho(r){const{sampleRate:e,keepAlive:t}=r;let i=Rr.get(e);return(!i||i.state==="closed")&&(i=new AudioContext({sampleRate:e}),Rr.set(e,i)),t&&(i.onstatechange=()=>{yt(i)}),i}function yt(r){if(r.state==="suspended"||r.state==="interrupted")return r.resume()}const po=r=>(e,t)=>(r.set(e,t),t),Ar=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,wr=536870912,Or=wr*2,lo=(r,e)=>t=>{const i=e.get(t);let s=i===void 0?t.size:i<Or?i+1:0;if(!t.has(s))return r(t,s);if(t.size<wr){for(;t.has(s);)s=Math.floor(Math.random()*Or);return r(t,s)}if(t.size>Ar)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()*Ar);return r(t,s)},Dr=new WeakMap,mo=po(Dr),ee=lo(mo,Dr),fo=r=>r.method!==void 0&&r.method==="call",_o=r=>typeof r.id=="number"&&typeof r.result=="boolean",Ir=((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:d})=>{if(fo(d)){const{params:{timerId:c,timerType:h}}=d;if(h==="interval"){const p=e.get(c);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!==c||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(c);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!==c||l.timerType!==h)throw new Error("The timer is in an undefined state.")}else typeof p=="function"&&(p(),t.delete(c))}}else if(_o(d)){const{id:c}=d,h=i.get(c);if(h===void 0)throw new Error("The timer is in an undefined state.");const{timerId:p,timerType:l}=h;i.delete(c),l==="interval"?e.delete(p):t.delete(p)}else{const{error:{message:c}}=d;throw new Error(c)}}),{clearInterval:d=>{if(typeof e.get(d)=="function"){const c=ee(i);i.set(c,{timerId:d,timerType:"interval"}),e.set(d,c),s.postMessage({id:c,method:"clear",params:{timerId:d,timerType:"interval"}})}},clearTimeout:d=>{if(typeof t.get(d)=="function"){const c=ee(i);i.set(c,{timerId:d,timerType:"timeout"}),t.set(d,c),s.postMessage({id:c,method:"clear",params:{timerId:d,timerType:"timeout"}})}},setInterval:(d,c=0,...h)=>{const p=ee(e);return e.set(p,()=>{d(...h),typeof e.get(p)=="function"&&s.postMessage({id:null,method:"set",params:{delay:c,now:performance.timeOrigin+performance.now(),timerId:p,timerType:"interval"}})}),s.postMessage({id:null,method:"set",params:{delay:c,now:performance.timeOrigin+performance.now(),timerId:p,timerType:"interval"}}),p},setTimeout:(d,c=0,...h)=>{const p=ee(t);return t.set(p,()=>d(...h)),s.postMessage({id:null,method:"set",params:{delay:c,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})}}))})();`),go=r=>Ir().clearTimeout(r),vo=(...r)=>Ir().setTimeout(...r),Co=r=>r.method!==void 0&&r.method==="call",yo=r=>typeof r.id=="number"&&typeof r.result=="boolean",So=r=>{const e=new Map([[0,()=>{}]]),t=new Map([[0,()=>{}]]),i=new Map,s=new Worker(r,{credentials:"omit"});return s.addEventListener("message",({data:d})=>{if(Co(d)){const{params:{timerId:c,timerType:h}}=d;if(h==="interval"){const p=e.get(c);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!==c||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(c);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!==c||l.timerType!==h)throw new Error("The timer is in an undefined state.")}else typeof p=="function"&&(p(),t.delete(c))}}else if(yo(d)){const{id:c}=d,h=i.get(c);if(h===void 0)throw new Error("The timer is in an undefined state.");const{timerId:p,timerType:l}=h;i.delete(c),l==="interval"?e.delete(p):t.delete(p)}else{const{error:{message:c}}=d;throw new Error(c)}}),{clearInterval:d=>{if(typeof e.get(d)=="function"){const c=ee(i);i.set(c,{timerId:d,timerType:"interval"}),e.set(d,c),s.postMessage({id:c,method:"clear",params:{timerId:d,timerType:"interval"}})}},clearTimeout:d=>{if(typeof t.get(d)=="function"){const c=ee(i);i.set(c,{timerId:d,timerType:"timeout"}),t.set(d,c),s.postMessage({id:c,method:"clear",params:{timerId:d,timerType:"timeout"}})}},setInterval:(d,c=0,...h)=>{const p=ee(e);return e.set(p,()=>{d(...h),typeof e.get(p)=="function"&&s.postMessage({id:null,method:"set",params:{delay:c,now:performance.timeOrigin+performance.now(),timerId:p,timerType:"interval"}})}),s.postMessage({id:null,method:"set",params:{delay:c,now:performance.timeOrigin+performance.now(),timerId:p,timerType:"interval"}}),p},setTimeout:(d,c=0,...h)=>{const p=ee(t);return t.set(p,()=>d(...h)),s.postMessage({id:null,method:"set",params:{delay:c,now:performance.timeOrigin+performance.now(),timerId:p,timerType:"timeout"}}),p}}},To={width:640,height:480,frameRate:30,backgroundColor:"#000000"},Ue=new L("View");class Eo{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)});Ue.info("ctor",e),this._config={...To,...e};const{context:t,canvas:i}=mr(this._config);this._context=t,this._canvas=i,this._customSetTimeout=vo,this._customClearTimeout=go}setWorkerTimerScriptUrl(e){if(this._workerTimerScriptUrl=e,this._workerTimerScriptUrl){const t=So(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=[]){Ue.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(Ue.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 Ue.info("element"),this._paintLoop(),this._canvas}stop(){this._stopped=!0}}function bo(){return Math.random().toString(36).slice(-8)}const ko=`
|
|
2
2
|
const SMOOTHING_FACTOR = 0.8;
|
|
3
3
|
const MINIMUM_VALUE = 0.00001;
|
|
4
4
|
|
|
@@ -53,10 +53,10 @@ registerProcessor('vumeter', class extends AudioWorkletProcessor {
|
|
|
53
53
|
return true;
|
|
54
54
|
}
|
|
55
55
|
});
|
|
56
|
-
`,bo=URL.createObjectURL(new Blob([Eo],{type:"application/javascript"}));class ko{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||bo);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 $e{constructor(){this._volumeDetectScriptUrl=void 0}static get instance(){return this._instance||(this._instance=new $e),this._instance}get volumeDetectScriptUrl(){return this._volumeDetectScriptUrl}set volumeDetectScriptUrl(e){this._volumeDetectScriptUrl=e}}class Or 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=To(),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 ko),await this._volumeDetector.start(this.audioTrack,$e.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 Or{get isVideoStream(){return!0}get isAudioStream(){return!1}bindTrackSizeChangeEvent(e){e.on(D.SIZE_CHANGE,({width:t,height:i})=>{this._width=t,this._height=i,this.emit(it.SizeChange,{width:t,height:i})})}}class Be extends Or{get isVideoStream(){return!1}get isAudioStream(){return!0}}class Po 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(D.ENDED,e)}destroy(){this.source.destroy()}}var Ir=typeof global=="object"&&global&&global.Object===Object&&global,xo=typeof self=="object"&&self&&self.Object===Object&&self,X=Ir||xo||Function("return this")(),te=X.Symbol,Dr=Object.prototype,Ro=Dr.hasOwnProperty,Ao=Dr.toString,ke=te?te.toStringTag:void 0;function wo(r){var e=Ro.call(r,ke),t=r[ke];try{r[ke]=void 0;var i=!0}catch{}var s=Ao.call(r);return i&&(e?r[ke]=t:delete r[ke]),s}var Oo=Object.prototype,Io=Oo.toString;function Do(r){return Io.call(r)}var Mo="[object Null]",Lo="[object Undefined]",Mr=te?te.toStringTag:void 0;function me(r){return r==null?r===void 0?Lo:Mo:Mr&&Mr in Object(r)?wo(r):Do(r)}function fe(r){return r!=null&&typeof r=="object"}var Fo="[object Symbol]";function je(r){return typeof r=="symbol"||fe(r)&&me(r)==Fo}function Lr(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,Fr=te?te.prototype:void 0,Nr=Fr?Fr.toString:void 0;function Vr(r){if(typeof r=="string")return r;if(F(r))return Lr(r,Vr)+"";if(je(r))return Nr?Nr.call(r):"";var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}var No=/\s/;function Vo(r){for(var e=r.length;e--&&No.test(r.charAt(e)););return e}var Uo=/^\s+/;function $o(r){return r&&r.slice(0,Vo(r)+1).replace(Uo,"")}function Pe(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}var Ur=NaN,Bo=/^[-+]0x[0-9a-f]+$/i,jo=/^0b[01]+$/i,zo=/^0o[0-7]+$/i,Go=parseInt;function Ho(r){if(typeof r=="number")return r;if(je(r))return Ur;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=$o(r);var t=jo.test(r);return t||zo.test(r)?Go(r.slice(2),t?2:8):Bo.test(r)?Ur:+r}var qo=1/0,Wo=17976931348623157e292;function Xo(r){if(!r)return r===0?r:0;if(r=Ho(r),r===qo||r===-1/0){var e=r<0?-1:1;return e*Wo}return r===r?r:0}function Ko(r){var e=Xo(r),t=e%1;return e===e?t?e-t:e:0}function Jo(r){return r}var Yo="[object AsyncFunction]",Zo="[object Function]",Qo="[object GeneratorFunction]",ea="[object Proxy]";function $r(r){if(!Pe(r))return!1;var e=me(r);return e==Zo||e==Qo||e==Yo||e==ea}var yt=X["__core-js_shared__"],Br=function(){var r=/[^.]+$/.exec(yt&&yt.keys&&yt.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""}();function ta(r){return!!Br&&Br in r}var ra=Function.prototype,ia=ra.toString;function ae(r){if(r!=null){try{return ia.call(r)}catch{}try{return r+""}catch{}}return""}var sa=/[\\^$.*+?()[\]{}|]/g,na=/^\[object .+?Constructor\]$/,oa=Function.prototype,aa=Object.prototype,ca=oa.toString,da=aa.hasOwnProperty,ua=RegExp("^"+ca.call(da).replace(sa,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function ha(r){if(!Pe(r)||ta(r))return!1;var e=$r(r)?ua:na;return e.test(ae(r))}function pa(r,e){return r==null?void 0:r[e]}function _e(r,e){var t=pa(r,e);return ha(t)?t:void 0}var St=_e(X,"WeakMap");function la(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 ma=9007199254740991,fa=/^(?:0|[1-9]\d*)$/;function jr(r,e){var t=typeof r;return e=e??ma,!!e&&(t=="number"||t!="symbol"&&fa.test(r))&&r>-1&&r%1==0&&r<e}function zr(r,e){return r===e||r!==r&&e!==e}var _a=9007199254740991;function Tt(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=_a}function Et(r){return r!=null&&Tt(r.length)&&!$r(r)}var ga=Object.prototype;function va(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||ga;return r===t}function Ca(r,e){for(var t=-1,i=Array(r);++t<r;)i[t]=e(t);return i}var ya="[object Arguments]";function Gr(r){return fe(r)&&me(r)==ya}var Hr=Object.prototype,Sa=Hr.hasOwnProperty,Ta=Hr.propertyIsEnumerable,qr=Gr(function(){return arguments}())?Gr:function(r){return fe(r)&&Sa.call(r,"callee")&&!Ta.call(r,"callee")};function Ea(){return!1}var Wr=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Xr=Wr&&typeof module=="object"&&module&&!module.nodeType&&module,ba=Xr&&Xr.exports===Wr,Kr=ba?X.Buffer:void 0,ka=Kr?Kr.isBuffer:void 0,bt=ka||Ea,Pa="[object Arguments]",xa="[object Array]",Ra="[object Boolean]",Aa="[object Date]",wa="[object Error]",Oa="[object Function]",Ia="[object Map]",Da="[object Number]",Ma="[object Object]",La="[object RegExp]",Fa="[object Set]",Na="[object String]",Va="[object WeakMap]",Ua="[object ArrayBuffer]",$a="[object DataView]",Ba="[object Float32Array]",ja="[object Float64Array]",za="[object Int8Array]",Ga="[object Int16Array]",Ha="[object Int32Array]",qa="[object Uint8Array]",Wa="[object Uint8ClampedArray]",Xa="[object Uint16Array]",Ka="[object Uint32Array]",k={};k[Ba]=k[ja]=k[za]=k[Ga]=k[Ha]=k[qa]=k[Wa]=k[Xa]=k[Ka]=!0,k[Pa]=k[xa]=k[Ua]=k[Ra]=k[$a]=k[Aa]=k[wa]=k[Oa]=k[Ia]=k[Da]=k[Ma]=k[La]=k[Fa]=k[Na]=k[Va]=!1;function Ja(r){return fe(r)&&Tt(r.length)&&!!k[me(r)]}function Ya(r){return function(e){return r(e)}}var Jr=typeof exports=="object"&&exports&&!exports.nodeType&&exports,xe=Jr&&typeof module=="object"&&module&&!module.nodeType&&module,Za=xe&&xe.exports===Jr,kt=Za&&Ir.process,Yr=function(){try{var r=xe&&xe.require&&xe.require("util").types;return r||kt&&kt.binding&&kt.binding("util")}catch{}}(),Zr=Yr&&Yr.isTypedArray,Qr=Zr?Ya(Zr):Ja,Qa=Object.prototype,ec=Qa.hasOwnProperty;function tc(r,e){var t=F(r),i=!t&&qr(r),s=!t&&!i&&bt(r),n=!t&&!i&&!s&&Qr(r),a=t||i||s||n,o=a?Ca(r.length,String):[],u=o.length;for(var d in r)ec.call(r,d)&&!(a&&(d=="length"||s&&(d=="offset"||d=="parent")||n&&(d=="buffer"||d=="byteLength"||d=="byteOffset")||jr(d,u)))&&o.push(d);return o}function rc(r,e){return function(t){return r(e(t))}}var ic=rc(Object.keys,Object),sc=Object.prototype,nc=sc.hasOwnProperty;function oc(r){if(!va(r))return ic(r);var e=[];for(var t in Object(r))nc.call(r,t)&&t!="constructor"&&e.push(t);return e}function Re(r){return Et(r)?tc(r):oc(r)}var ac=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,cc=/^\w*$/;function Pt(r,e){if(F(r))return!1;var t=typeof r;return t=="number"||t=="symbol"||t=="boolean"||r==null||je(r)?!0:cc.test(r)||!ac.test(r)||e!=null&&r in Object(e)}var Ae=_e(Object,"create");function dc(){this.__data__=Ae?Ae(null):{},this.size=0}function uc(r){var e=this.has(r)&&delete this.__data__[r];return this.size-=e?1:0,e}var hc="__lodash_hash_undefined__",pc=Object.prototype,lc=pc.hasOwnProperty;function mc(r){var e=this.__data__;if(Ae){var t=e[r];return t===hc?void 0:t}return lc.call(e,r)?e[r]:void 0}var fc=Object.prototype,_c=fc.hasOwnProperty;function gc(r){var e=this.__data__;return Ae?e[r]!==void 0:_c.call(e,r)}var vc="__lodash_hash_undefined__";function Cc(r,e){var t=this.__data__;return this.size+=this.has(r)?0:1,t[r]=Ae&&e===void 0?vc: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=dc,ce.prototype.delete=uc,ce.prototype.get=mc,ce.prototype.has=gc,ce.prototype.set=Cc;function yc(){this.__data__=[],this.size=0}function ze(r,e){for(var t=r.length;t--;)if(zr(r[t][0],e))return t;return-1}var Sc=Array.prototype,Tc=Sc.splice;function Ec(r){var e=this.__data__,t=ze(e,r);if(t<0)return!1;var i=e.length-1;return t==i?e.pop():Tc.call(e,t,1),--this.size,!0}function bc(r){var e=this.__data__,t=ze(e,r);return t<0?void 0:e[t][1]}function kc(r){return ze(this.__data__,r)>-1}function Pc(r,e){var t=this.__data__,i=ze(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=yc,K.prototype.delete=Ec,K.prototype.get=bc,K.prototype.has=kc,K.prototype.set=Pc;var we=_e(X,"Map");function xc(){this.size=0,this.__data__={hash:new ce,map:new(we||K),string:new ce}}function Rc(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}function Ge(r,e){var t=r.__data__;return Rc(e)?t[typeof e=="string"?"string":"hash"]:t.map}function Ac(r){var e=Ge(this,r).delete(r);return this.size-=e?1:0,e}function wc(r){return Ge(this,r).get(r)}function Oc(r){return Ge(this,r).has(r)}function Ic(r,e){var t=Ge(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=xc,J.prototype.delete=Ac,J.prototype.get=wc,J.prototype.has=Oc,J.prototype.set=Ic;var Dc="Expected a function";function xt(r,e){if(typeof r!="function"||e!=null&&typeof e!="function")throw new TypeError(Dc);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 Lc(r){var e=xt(r,function(i){return t.size===Mc&&t.clear(),i}),t=e.cache;return e}var Fc=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Nc=/\\(\\)?/g,Vc=Lc(function(r){var e=[];return r.charCodeAt(0)===46&&e.push(""),r.replace(Fc,function(t,i,s,n){e.push(s?n.replace(Nc,"$1"):i||t)}),e});function Uc(r){return r==null?"":Vr(r)}function ei(r,e){return F(r)?r:Pt(r,e)?[r]:Vc(Uc(r))}function He(r){if(typeof r=="string"||je(r))return r;var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function ti(r,e){e=ei(e,r);for(var t=0,i=e.length;r!=null&&t<i;)r=r[He(e[t++])];return t&&t==i?r:void 0}function $c(r,e,t){var i=r==null?void 0:ti(r,e);return i===void 0?t:i}function Bc(r,e){for(var t=-1,i=e.length,s=r.length;++t<i;)r[s+t]=e[t];return r}function jc(){this.__data__=new K,this.size=0}function zc(r){var e=this.__data__,t=e.delete(r);return this.size=e.size,t}function Gc(r){return this.__data__.get(r)}function Hc(r){return this.__data__.has(r)}var qc=200;function Wc(r,e){var t=this.__data__;if(t instanceof K){var i=t.__data__;if(!we||i.length<qc-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=jc,Y.prototype.delete=zc,Y.prototype.get=Gc,Y.prototype.has=Hc,Y.prototype.set=Wc;function ri(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 Xc(){return[]}var Kc=Object.prototype,Jc=Kc.propertyIsEnumerable,ii=Object.getOwnPropertySymbols,Yc=ii?function(r){return r==null?[]:(r=Object(r),ri(ii(r),function(e){return Jc.call(r,e)}))}:Xc;function Zc(r,e,t){var i=e(r);return F(r)?i:Bc(i,t(r))}function si(r){return Zc(r,Re,Yc)}var Rt=_e(X,"DataView"),At=_e(X,"Promise"),wt=_e(X,"Set"),ni="[object Map]",Qc="[object Object]",oi="[object Promise]",ai="[object Set]",ci="[object WeakMap]",di="[object DataView]",ed=ae(Rt),td=ae(we),rd=ae(At),id=ae(wt),sd=ae(St),re=me;(Rt&&re(new Rt(new ArrayBuffer(1)))!=di||we&&re(new we)!=ni||At&&re(At.resolve())!=oi||wt&&re(new wt)!=ai||St&&re(new St)!=ci)&&(re=function(r){var e=me(r),t=e==Qc?r.constructor:void 0,i=t?ae(t):"";if(i)switch(i){case ed:return di;case td:return ni;case rd:return oi;case id:return ai;case sd:return ci}return e});var ui=X.Uint8Array,nd="__lodash_hash_undefined__";function od(r){return this.__data__.set(r,nd),this}function ad(r){return this.__data__.has(r)}function qe(r){var e=-1,t=r==null?0:r.length;for(this.__data__=new J;++e<t;)this.add(r[e])}qe.prototype.add=qe.prototype.push=od,qe.prototype.has=ad;function cd(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 dd(r,e){return r.has(e)}var ud=1,hd=2;function hi(r,e,t,i,s,n){var a=t&ud,o=r.length,u=e.length;if(o!=u&&!(a&&u>o))return!1;var d=n.get(r),c=n.get(e);if(d&&c)return d==e&&c==r;var h=-1,p=!0,l=t&hd?new qe: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(!cd(e,function(T,b){if(!dd(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 pd(r){var e=-1,t=Array(r.size);return r.forEach(function(i,s){t[++e]=[s,i]}),t}function ld(r){var e=-1,t=Array(r.size);return r.forEach(function(i){t[++e]=i}),t}var md=1,fd=2,_d="[object Boolean]",gd="[object Date]",vd="[object Error]",Cd="[object Map]",yd="[object Number]",Sd="[object RegExp]",Td="[object Set]",Ed="[object String]",bd="[object Symbol]",kd="[object ArrayBuffer]",Pd="[object DataView]",pi=te?te.prototype:void 0,Ot=pi?pi.valueOf:void 0;function xd(r,e,t,i,s,n,a){switch(t){case Pd:if(r.byteLength!=e.byteLength||r.byteOffset!=e.byteOffset)return!1;r=r.buffer,e=e.buffer;case kd:return!(r.byteLength!=e.byteLength||!n(new ui(r),new ui(e)));case _d:case gd:case yd:return zr(+r,+e);case vd:return r.name==e.name&&r.message==e.message;case Sd:case Ed:return r==e+"";case Cd:var o=pd;case Td:var u=i&md;if(o||(o=ld),r.size!=e.size&&!u)return!1;var d=a.get(r);if(d)return d==e;i|=fd,a.set(r,e);var c=hi(o(r),o(e),i,s,n,a);return a.delete(r),c;case bd:if(Ot)return Ot.call(r)==Ot.call(e)}return!1}var Rd=1,Ad=Object.prototype,wd=Ad.hasOwnProperty;function Od(r,e,t,i,s,n){var a=t&Rd,o=si(r),u=o.length,d=si(e),c=d.length;if(u!=c&&!a)return!1;for(var h=u;h--;){var p=o[h];if(!(a?p in e:wd.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 Id=1,li="[object Arguments]",mi="[object Array]",We="[object Object]",Dd=Object.prototype,fi=Dd.hasOwnProperty;function Md(r,e,t,i,s,n){var a=F(r),o=F(e),u=a?mi:re(r),d=o?mi:re(e);u=u==li?We:u,d=d==li?We:d;var c=u==We,h=d==We,p=u==d;if(p&&bt(r)){if(!bt(e))return!1;a=!0,c=!1}if(p&&!c)return n||(n=new Y),a||Qr(r)?hi(r,e,t,i,s,n):xd(r,e,u,t,i,s,n);if(!(t&Id)){var l=c&&fi.call(r,"__wrapped__"),f=h&&fi.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),Od(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 Ld=1,Fd=2;function Nd(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],d=a[1];if(a[2]){if(u===void 0&&!(o in r))return!1}else{var c=new Y,h;if(!(h===void 0?It(d,u,Ld|Fd,i,c):h))return!1}}return!0}function _i(r){return r===r&&!Pe(r)}function Vd(r){for(var e=Re(r),t=e.length;t--;){var i=e[t],s=r[i];e[t]=[i,s,_i(s)]}return e}function gi(r,e){return function(t){return t==null?!1:t[r]===e&&(e!==void 0||r in Object(t))}}function Ud(r){var e=Vd(r);return e.length==1&&e[0][2]?gi(e[0][0],e[0][1]):function(t){return t===r||Nd(t,r,e)}}function $d(r,e){return r!=null&&e in Object(r)}function Bd(r,e,t){e=ei(e,r);for(var i=-1,s=e.length,n=!1;++i<s;){var a=He(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)&&jr(a,s)&&(F(r)||qr(r)))}function jd(r,e){return r!=null&&Bd(r,e,$d)}var zd=1,Gd=2;function Hd(r,e){return Pt(r)&&_i(e)?gi(He(r),e):function(t){var i=$c(t,r);return i===void 0&&i===e?jd(t,r):It(e,i,zd|Gd)}}function qd(r){return function(e){return e==null?void 0:e[r]}}function Wd(r){return function(e){return ti(e,r)}}function Xd(r){return Pt(r)?qd(He(r)):Wd(r)}function Dt(r){return typeof r=="function"?r:r==null?Jo:typeof r=="object"?F(r)?Hd(r[0],r[1]):Ud(r):Xd(r)}function Kd(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 Jd=Kd();function Yd(r,e){return r&&Jd(r,e,Re)}function Zd(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 Qd=Zd(Yd);function eu(r,e){var t=[];return Qd(r,function(i,s,n){e(i,s,n)&&t.push(i)}),t}function vi(r,e){var t=F(r)?ri:eu;return t(r,Dt(e))}function tu(r){return function(e,t,i){var s=Object(e);if(!Et(e)){var n=Dt(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 ru=Math.max;function iu(r,e,t){var i=r==null?0:r.length;if(!i)return-1;var s=t==null?0:Ko(t);return s<0&&(s=ru(i+s,0)),la(r,Dt(e),s)}var Oe=tu(iu);function su(r,e){return Lr(e,function(t){return r[t]})}function ge(r){return r==null?[]:su(r,Re(r))}function nu(r){return r==null}class ou extends Be{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(D.ENDED,e)}destroy(){this.source.destroy()}}class au 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(D.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 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(D.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 du extends Be{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(D.ENDED,e)}destroy(){var e;(e=this._audioStream)==null||e.destroy()}}class uu 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(D.ENDED,e)}destroy(){this.source.destroy()}}class hu 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(D.ENDED,e)}destroy(){this.source.destroy()}}class pu extends Be{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(D.ENDED,e)}destroy(){var e;(e=this._audioStream)==null||e.destroy()}}const lu=["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=st.Landscape;if(e==="video"){const u=(i===st.Landscape?tr:rr)[r],[d,c,h,p]=u.split("x").map(l=>Number(l));return{width:d,height:c,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 mu 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 Zn(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={};lu.includes(e)?t={facingMode:e}:t={deviceId:e};try{const i=await Qn({...t,...this._videoConstraints}),s=new Po(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 to({...this._audioConstraints,deviceId:e}),i=new ou(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 ro({audio:e,video:this._videoConstraints}),i=new cu(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 br({url:e,video:!0,audio:!0,loop:!0}),i=new au(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 br({url:e,video:!1,audio:!0,loop:!0}),i=new du(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 eo({url:e,width:0,height:0,frameRate:30}),i=new uu(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=so(e);if(t){const i=new hu(t);return this._customVideoStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),i.id}}startCustomAudioCapture(e){const t=no(e);if(t){const i=new pu(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 Mt{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 Ci=new de("SingleComposer");class fu extends Mt{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){Ci.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):Ci.error("all video stream stop capture")}}_handleAudioStreamStopCapture(e){this._streamComposeController.removeAudioStream(e.id)}getComposedStream(){return this._composedStream}}class _u 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(it.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 yi 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 gu=Object.defineProperty,vu=Object.getOwnPropertyDescriptor,De=(r,e,t,i)=>{for(var s=vu(e,t),n=r.length-1,a;n>=0;n--)(a=r[n])&&(s=a(e,t,s)||s);return s&&gu(e,t,s),s};const Si=new de("composition-composer");function Me(r,e,t){const i=t.value;return t.value=function(...s){return this._active||Si.error("composer is not active"),i.apply(this,s)},t}class Ce extends Mt{constructor(e){super(e),this._compositionViewConfig={width:1080,height:720,frameRate:30,backgroundColor:"#000000"},this._sprites=[],this._videoMixer=new So}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 yi(e),this._composedStream.setVideoStream(this._mixedVideoStream)}disable(){super.disable(),this._videoMixer.stop()}_updateSpriteToMixer(){const e=vi(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=>{nu(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 yi(i),this._composedStream.setVideoStream(this._mixedVideoStream)}}addVideoStream(e,t){if(!e.viewNode){Si.error("have no viewNode for composition");return}e.audioTrack&&this._streamComposeController.addAudioStream({streamId:e.id,volume:100});const i=new _u(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)}}De([Me],Ce.prototype,"addVideoStream"),De([Me],Ce.prototype,"updateVideoStream"),De([Me],Ce.prototype,"removeVideoStream"),De([Me],Ce.prototype,"muteVideoStream"),De([Me],Ce.prototype,"unmuteVideoStream");class Cu 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 yu extends Be{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 Su extends Mt{constructor(e){super(e),this._spriteList=[],this._audioMixer=new ao}onStreamCapture(e){}onStreamStopCapture(e){e&&this.removeAudioStream(e.id)}_updateSpriteToMixer(){const e=vi(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 yu(e);this._composedStream.setAudioStream(t),this._audioMixer.mix([])}addAudioStream(e,t){const i=new Cu(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 Tu 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 Eu=new de("streamComposeController");class bu{constructor(e){this._streamManagerController=e,this._composedStream=new Tu,this.singleComposer=new fu({streamManagerController:this._streamManagerController,composedStream:this._composedStream,streamComposeController:this}),this.compositionComposer=new Ce({streamManagerController:this._streamManagerController,composedStream:this._composedStream,streamComposeController:this}),this.mixerComposer=new Su({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){Eu.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 Ti{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 ku extends Ti{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:{}},Ei;function Nt(){if(Ei)return Ft.exports;Ei=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 bi;function Pu(){return bi||(bi=1,function(r){var e=function(o){return String(Number(o))===o?Number(o):o},t=function(o,u,d,c){if(c&&!d)u[c]=e(o[1]);else for(var h=0;h<d.length;h+=1)o[h+1]!=null&&(u[d[h]]=e(o[h+1]))},i=function(o,u,d){var c=o.name&&o.names;o.push&&!u[o.push]?u[o.push]=[]:c&&!u[o.name]&&(u[o.name]={});var h=o.push?{}:c?u[o.name]:u;t(d.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={},d=[],c=u;return o.split(/(\r\n|\r|\n)/).filter(n).forEach(function(h){var p=h[0],l=h.slice(2);p==="m"&&(d.push({rtp:[],fmtp:[]}),c=d[d.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,c,l)}}),u.media=d,u};var a=function(o,u){var d=u.split(/=(.+)/,2);return d.length===2?o[d[0]]=e(d[1]):d.length===1&&u.length>1&&(o[d[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=[],d=o.split(" ").map(e),c=0;c<d.length;c+=3)u.push({component:d[c],ip:d[c+1],port:d[c+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(d){var c,h=!1;return d[0]!=="~"?c=e(d):(c=e(d.substring(1,d.length)),h=!0),{scid:c,paused:h}})})}}(Lt)),Lt}var Vt,ki;function xu(){if(ki)return Vt;ki=1;var r=Nt(),e=/%[sdv%]/g,t=function(a){var o=1,u=arguments,d=u.length;return a.replace(e,function(c){if(o>=d)return c;var h=u[o];switch(o+=1,c){case"%%":return"%";case"%s":return String(h);case"%d":return Number(h);case"%v":return""}})},i=function(a,o,u){var d=o.format instanceof Function?o.format(o.push?u:u[o.name]):o.format,c=[a+"="+d];if(o.names)for(var h=0;h<o.names.length;h+=1){var p=o.names[h];o.name?c.push(u[o.name][p]):c.push(u[o.names[h]])}else c.push(u[o.name]);return t.apply(null,c)},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,d=o.innerOrder||n,c=[];return u.forEach(function(h){r[h].forEach(function(p){p.name in a&&a[p.name]!=null?c.push(i(h,p,a)):p.push in a&&a[p.push]!=null&&a[p.push].forEach(function(l){c.push(i(h,p,l))})})}),a.media.forEach(function(h){c.push(i("m",r.m[0],h)),d.forEach(function(p){r[p].forEach(function(l){l.name in h&&h[l.name]!=null?c.push(i(p,l,h)):l.push in h&&h[l.push]!=null&&h[l.push].forEach(function(f){c.push(i(p,l,f))})})})}),c.join(`\r
|
|
56
|
+
`,Po=URL.createObjectURL(new Blob([ko],{type:"application/javascript"}));class xo{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||Po);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 $e{constructor(){this._volumeDetectScriptUrl=void 0}static get instance(){return this._instance||(this._instance=new $e),this._instance}get volumeDetectScriptUrl(){return this._volumeDetectScriptUrl}set volumeDetectScriptUrl(e){this._volumeDetectScriptUrl=e}}class Mr 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=bo(),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 xo),await this._volumeDetector.start(this.audioTrack,$e.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 Mr{get isVideoStream(){return!0}get isAudioStream(){return!1}bindTrackSizeChangeEvent(e){e.on(I.SIZE_CHANGE,({width:t,height:i})=>{this._width=t,this._height=i,this.emit(it.SizeChange,{width:t,height:i})})}}class Be extends Mr{get isVideoStream(){return!1}get isAudioStream(){return!0}}class Ro 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(I.ENDED,e)}destroy(){this.source.destroy()}}var Lr=typeof global=="object"&&global&&global.Object===Object&&global,Ao=typeof self=="object"&&self&&self.Object===Object&&self,X=Lr||Ao||Function("return this")(),te=X.Symbol,Fr=Object.prototype,wo=Fr.hasOwnProperty,Oo=Fr.toString,ke=te?te.toStringTag:void 0;function Do(r){var e=wo.call(r,ke),t=r[ke];try{r[ke]=void 0;var i=!0}catch{}var s=Oo.call(r);return i&&(e?r[ke]=t:delete r[ke]),s}var Io=Object.prototype,Mo=Io.toString;function Lo(r){return Mo.call(r)}var Fo="[object Null]",No="[object Undefined]",Nr=te?te.toStringTag:void 0;function me(r){return r==null?r===void 0?No:Fo:Nr&&Nr in Object(r)?Do(r):Lo(r)}function fe(r){return r!=null&&typeof r=="object"}var Vo="[object Symbol]";function je(r){return typeof r=="symbol"||fe(r)&&me(r)==Vo}function Vr(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,Ur=te?te.prototype:void 0,$r=Ur?Ur.toString:void 0;function Br(r){if(typeof r=="string")return r;if(F(r))return Vr(r,Br)+"";if(je(r))return $r?$r.call(r):"";var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}var Uo=/\s/;function $o(r){for(var e=r.length;e--&&Uo.test(r.charAt(e)););return e}var Bo=/^\s+/;function jo(r){return r&&r.slice(0,$o(r)+1).replace(Bo,"")}function Pe(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}var jr=NaN,zo=/^[-+]0x[0-9a-f]+$/i,Go=/^0b[01]+$/i,Ho=/^0o[0-7]+$/i,qo=parseInt;function Wo(r){if(typeof r=="number")return r;if(je(r))return jr;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=jo(r);var t=Go.test(r);return t||Ho.test(r)?qo(r.slice(2),t?2:8):zo.test(r)?jr:+r}var Xo=1/0,Ko=17976931348623157e292;function Jo(r){if(!r)return r===0?r:0;if(r=Wo(r),r===Xo||r===-1/0){var e=r<0?-1:1;return e*Ko}return r===r?r:0}function Yo(r){var e=Jo(r),t=e%1;return e===e?t?e-t:e:0}function Zo(r){return r}var Qo="[object AsyncFunction]",ea="[object Function]",ta="[object GeneratorFunction]",ra="[object Proxy]";function zr(r){if(!Pe(r))return!1;var e=me(r);return e==ea||e==ta||e==Qo||e==ra}var St=X["__core-js_shared__"],Gr=function(){var r=/[^.]+$/.exec(St&&St.keys&&St.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""}();function ia(r){return!!Gr&&Gr in r}var sa=Function.prototype,na=sa.toString;function ae(r){if(r!=null){try{return na.call(r)}catch{}try{return r+""}catch{}}return""}var oa=/[\\^$.*+?()[\]{}|]/g,aa=/^\[object .+?Constructor\]$/,ca=Function.prototype,da=Object.prototype,ua=ca.toString,ha=da.hasOwnProperty,pa=RegExp("^"+ua.call(ha).replace(oa,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function la(r){if(!Pe(r)||ia(r))return!1;var e=zr(r)?pa:aa;return e.test(ae(r))}function ma(r,e){return r==null?void 0:r[e]}function _e(r,e){var t=ma(r,e);return la(t)?t:void 0}var Tt=_e(X,"WeakMap");function fa(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 _a=9007199254740991,ga=/^(?:0|[1-9]\d*)$/;function Hr(r,e){var t=typeof r;return e=e??_a,!!e&&(t=="number"||t!="symbol"&&ga.test(r))&&r>-1&&r%1==0&&r<e}function qr(r,e){return r===e||r!==r&&e!==e}var va=9007199254740991;function Et(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=va}function bt(r){return r!=null&&Et(r.length)&&!zr(r)}var Ca=Object.prototype;function ya(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||Ca;return r===t}function Sa(r,e){for(var t=-1,i=Array(r);++t<r;)i[t]=e(t);return i}var Ta="[object Arguments]";function Wr(r){return fe(r)&&me(r)==Ta}var Xr=Object.prototype,Ea=Xr.hasOwnProperty,ba=Xr.propertyIsEnumerable,Kr=Wr(function(){return arguments}())?Wr:function(r){return fe(r)&&Ea.call(r,"callee")&&!ba.call(r,"callee")};function ka(){return!1}var Jr=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Yr=Jr&&typeof module=="object"&&module&&!module.nodeType&&module,Pa=Yr&&Yr.exports===Jr,Zr=Pa?X.Buffer:void 0,xa=Zr?Zr.isBuffer:void 0,kt=xa||ka,Ra="[object Arguments]",Aa="[object Array]",wa="[object Boolean]",Oa="[object Date]",Da="[object Error]",Ia="[object Function]",Ma="[object Map]",La="[object Number]",Fa="[object Object]",Na="[object RegExp]",Va="[object Set]",Ua="[object String]",$a="[object WeakMap]",Ba="[object ArrayBuffer]",ja="[object DataView]",za="[object Float32Array]",Ga="[object Float64Array]",Ha="[object Int8Array]",qa="[object Int16Array]",Wa="[object Int32Array]",Xa="[object Uint8Array]",Ka="[object Uint8ClampedArray]",Ja="[object Uint16Array]",Ya="[object Uint32Array]",k={};k[za]=k[Ga]=k[Ha]=k[qa]=k[Wa]=k[Xa]=k[Ka]=k[Ja]=k[Ya]=!0,k[Ra]=k[Aa]=k[Ba]=k[wa]=k[ja]=k[Oa]=k[Da]=k[Ia]=k[Ma]=k[La]=k[Fa]=k[Na]=k[Va]=k[Ua]=k[$a]=!1;function Za(r){return fe(r)&&Et(r.length)&&!!k[me(r)]}function Qa(r){return function(e){return r(e)}}var Qr=typeof exports=="object"&&exports&&!exports.nodeType&&exports,xe=Qr&&typeof module=="object"&&module&&!module.nodeType&&module,ec=xe&&xe.exports===Qr,Pt=ec&&Lr.process,ei=function(){try{var r=xe&&xe.require&&xe.require("util").types;return r||Pt&&Pt.binding&&Pt.binding("util")}catch{}}(),ti=ei&&ei.isTypedArray,ri=ti?Qa(ti):Za,tc=Object.prototype,rc=tc.hasOwnProperty;function ic(r,e){var t=F(r),i=!t&&Kr(r),s=!t&&!i&&kt(r),n=!t&&!i&&!s&&ri(r),a=t||i||s||n,o=a?Sa(r.length,String):[],u=o.length;for(var d in r)rc.call(r,d)&&!(a&&(d=="length"||s&&(d=="offset"||d=="parent")||n&&(d=="buffer"||d=="byteLength"||d=="byteOffset")||Hr(d,u)))&&o.push(d);return o}function sc(r,e){return function(t){return r(e(t))}}var nc=sc(Object.keys,Object),oc=Object.prototype,ac=oc.hasOwnProperty;function cc(r){if(!ya(r))return nc(r);var e=[];for(var t in Object(r))ac.call(r,t)&&t!="constructor"&&e.push(t);return e}function Re(r){return bt(r)?ic(r):cc(r)}var dc=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,uc=/^\w*$/;function xt(r,e){if(F(r))return!1;var t=typeof r;return t=="number"||t=="symbol"||t=="boolean"||r==null||je(r)?!0:uc.test(r)||!dc.test(r)||e!=null&&r in Object(e)}var Ae=_e(Object,"create");function hc(){this.__data__=Ae?Ae(null):{},this.size=0}function pc(r){var e=this.has(r)&&delete this.__data__[r];return this.size-=e?1:0,e}var lc="__lodash_hash_undefined__",mc=Object.prototype,fc=mc.hasOwnProperty;function _c(r){var e=this.__data__;if(Ae){var t=e[r];return t===lc?void 0:t}return fc.call(e,r)?e[r]:void 0}var gc=Object.prototype,vc=gc.hasOwnProperty;function Cc(r){var e=this.__data__;return Ae?e[r]!==void 0:vc.call(e,r)}var yc="__lodash_hash_undefined__";function Sc(r,e){var t=this.__data__;return this.size+=this.has(r)?0:1,t[r]=Ae&&e===void 0?yc: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=hc,ce.prototype.delete=pc,ce.prototype.get=_c,ce.prototype.has=Cc,ce.prototype.set=Sc;function Tc(){this.__data__=[],this.size=0}function ze(r,e){for(var t=r.length;t--;)if(qr(r[t][0],e))return t;return-1}var Ec=Array.prototype,bc=Ec.splice;function kc(r){var e=this.__data__,t=ze(e,r);if(t<0)return!1;var i=e.length-1;return t==i?e.pop():bc.call(e,t,1),--this.size,!0}function Pc(r){var e=this.__data__,t=ze(e,r);return t<0?void 0:e[t][1]}function xc(r){return ze(this.__data__,r)>-1}function Rc(r,e){var t=this.__data__,i=ze(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=Tc,K.prototype.delete=kc,K.prototype.get=Pc,K.prototype.has=xc,K.prototype.set=Rc;var we=_e(X,"Map");function Ac(){this.size=0,this.__data__={hash:new ce,map:new(we||K),string:new ce}}function wc(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}function Ge(r,e){var t=r.__data__;return wc(e)?t[typeof e=="string"?"string":"hash"]:t.map}function Oc(r){var e=Ge(this,r).delete(r);return this.size-=e?1:0,e}function Dc(r){return Ge(this,r).get(r)}function Ic(r){return Ge(this,r).has(r)}function Mc(r,e){var t=Ge(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=Ac,J.prototype.delete=Oc,J.prototype.get=Dc,J.prototype.has=Ic,J.prototype.set=Mc;var Lc="Expected a function";function Rt(r,e){if(typeof r!="function"||e!=null&&typeof e!="function")throw new TypeError(Lc);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(Rt.Cache||J),t}Rt.Cache=J;var Fc=500;function Nc(r){var e=Rt(r,function(i){return t.size===Fc&&t.clear(),i}),t=e.cache;return e}var Vc=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Uc=/\\(\\)?/g,$c=Nc(function(r){var e=[];return r.charCodeAt(0)===46&&e.push(""),r.replace(Vc,function(t,i,s,n){e.push(s?n.replace(Uc,"$1"):i||t)}),e});function Bc(r){return r==null?"":Br(r)}function ii(r,e){return F(r)?r:xt(r,e)?[r]:$c(Bc(r))}function He(r){if(typeof r=="string"||je(r))return r;var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function si(r,e){e=ii(e,r);for(var t=0,i=e.length;r!=null&&t<i;)r=r[He(e[t++])];return t&&t==i?r:void 0}function jc(r,e,t){var i=r==null?void 0:si(r,e);return i===void 0?t:i}function zc(r,e){for(var t=-1,i=e.length,s=r.length;++t<i;)r[s+t]=e[t];return r}function Gc(){this.__data__=new K,this.size=0}function Hc(r){var e=this.__data__,t=e.delete(r);return this.size=e.size,t}function qc(r){return this.__data__.get(r)}function Wc(r){return this.__data__.has(r)}var Xc=200;function Kc(r,e){var t=this.__data__;if(t instanceof K){var i=t.__data__;if(!we||i.length<Xc-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=Gc,Y.prototype.delete=Hc,Y.prototype.get=qc,Y.prototype.has=Wc,Y.prototype.set=Kc;function ni(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 Jc(){return[]}var Yc=Object.prototype,Zc=Yc.propertyIsEnumerable,oi=Object.getOwnPropertySymbols,Qc=oi?function(r){return r==null?[]:(r=Object(r),ni(oi(r),function(e){return Zc.call(r,e)}))}:Jc;function ed(r,e,t){var i=e(r);return F(r)?i:zc(i,t(r))}function ai(r){return ed(r,Re,Qc)}var At=_e(X,"DataView"),wt=_e(X,"Promise"),Ot=_e(X,"Set"),ci="[object Map]",td="[object Object]",di="[object Promise]",ui="[object Set]",hi="[object WeakMap]",pi="[object DataView]",rd=ae(At),id=ae(we),sd=ae(wt),nd=ae(Ot),od=ae(Tt),re=me;(At&&re(new At(new ArrayBuffer(1)))!=pi||we&&re(new we)!=ci||wt&&re(wt.resolve())!=di||Ot&&re(new Ot)!=ui||Tt&&re(new Tt)!=hi)&&(re=function(r){var e=me(r),t=e==td?r.constructor:void 0,i=t?ae(t):"";if(i)switch(i){case rd:return pi;case id:return ci;case sd:return di;case nd:return ui;case od:return hi}return e});var li=X.Uint8Array,ad="__lodash_hash_undefined__";function cd(r){return this.__data__.set(r,ad),this}function dd(r){return this.__data__.has(r)}function qe(r){var e=-1,t=r==null?0:r.length;for(this.__data__=new J;++e<t;)this.add(r[e])}qe.prototype.add=qe.prototype.push=cd,qe.prototype.has=dd;function ud(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 hd(r,e){return r.has(e)}var pd=1,ld=2;function mi(r,e,t,i,s,n){var a=t&pd,o=r.length,u=e.length;if(o!=u&&!(a&&u>o))return!1;var d=n.get(r),c=n.get(e);if(d&&c)return d==e&&c==r;var h=-1,p=!0,l=t&ld?new qe: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(!ud(e,function(T,b){if(!hd(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 md(r){var e=-1,t=Array(r.size);return r.forEach(function(i,s){t[++e]=[s,i]}),t}function fd(r){var e=-1,t=Array(r.size);return r.forEach(function(i){t[++e]=i}),t}var _d=1,gd=2,vd="[object Boolean]",Cd="[object Date]",yd="[object Error]",Sd="[object Map]",Td="[object Number]",Ed="[object RegExp]",bd="[object Set]",kd="[object String]",Pd="[object Symbol]",xd="[object ArrayBuffer]",Rd="[object DataView]",fi=te?te.prototype:void 0,Dt=fi?fi.valueOf:void 0;function Ad(r,e,t,i,s,n,a){switch(t){case Rd:if(r.byteLength!=e.byteLength||r.byteOffset!=e.byteOffset)return!1;r=r.buffer,e=e.buffer;case xd:return!(r.byteLength!=e.byteLength||!n(new li(r),new li(e)));case vd:case Cd:case Td:return qr(+r,+e);case yd:return r.name==e.name&&r.message==e.message;case Ed:case kd:return r==e+"";case Sd:var o=md;case bd:var u=i&_d;if(o||(o=fd),r.size!=e.size&&!u)return!1;var d=a.get(r);if(d)return d==e;i|=gd,a.set(r,e);var c=mi(o(r),o(e),i,s,n,a);return a.delete(r),c;case Pd:if(Dt)return Dt.call(r)==Dt.call(e)}return!1}var wd=1,Od=Object.prototype,Dd=Od.hasOwnProperty;function Id(r,e,t,i,s,n){var a=t&wd,o=ai(r),u=o.length,d=ai(e),c=d.length;if(u!=c&&!a)return!1;for(var h=u;h--;){var p=o[h];if(!(a?p in e:Dd.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 Md=1,_i="[object Arguments]",gi="[object Array]",We="[object Object]",Ld=Object.prototype,vi=Ld.hasOwnProperty;function Fd(r,e,t,i,s,n){var a=F(r),o=F(e),u=a?gi:re(r),d=o?gi:re(e);u=u==_i?We:u,d=d==_i?We:d;var c=u==We,h=d==We,p=u==d;if(p&&kt(r)){if(!kt(e))return!1;a=!0,c=!1}if(p&&!c)return n||(n=new Y),a||ri(r)?mi(r,e,t,i,s,n):Ad(r,e,u,t,i,s,n);if(!(t&Md)){var l=c&&vi.call(r,"__wrapped__"),f=h&&vi.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),Id(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:Fd(r,e,t,i,It,s)}var Nd=1,Vd=2;function Ud(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],d=a[1];if(a[2]){if(u===void 0&&!(o in r))return!1}else{var c=new Y,h;if(!(h===void 0?It(d,u,Nd|Vd,i,c):h))return!1}}return!0}function Ci(r){return r===r&&!Pe(r)}function $d(r){for(var e=Re(r),t=e.length;t--;){var i=e[t],s=r[i];e[t]=[i,s,Ci(s)]}return e}function yi(r,e){return function(t){return t==null?!1:t[r]===e&&(e!==void 0||r in Object(t))}}function Bd(r){var e=$d(r);return e.length==1&&e[0][2]?yi(e[0][0],e[0][1]):function(t){return t===r||Ud(t,r,e)}}function jd(r,e){return r!=null&&e in Object(r)}function zd(r,e,t){e=ii(e,r);for(var i=-1,s=e.length,n=!1;++i<s;){var a=He(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&&Et(s)&&Hr(a,s)&&(F(r)||Kr(r)))}function Gd(r,e){return r!=null&&zd(r,e,jd)}var Hd=1,qd=2;function Wd(r,e){return xt(r)&&Ci(e)?yi(He(r),e):function(t){var i=jc(t,r);return i===void 0&&i===e?Gd(t,r):It(e,i,Hd|qd)}}function Xd(r){return function(e){return e==null?void 0:e[r]}}function Kd(r){return function(e){return si(e,r)}}function Jd(r){return xt(r)?Xd(He(r)):Kd(r)}function Mt(r){return typeof r=="function"?r:r==null?Zo:typeof r=="object"?F(r)?Wd(r[0],r[1]):Bd(r):Jd(r)}function Yd(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 Zd=Yd();function Qd(r,e){return r&&Zd(r,e,Re)}function eu(r,e){return function(t,i){if(t==null)return t;if(!bt(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 tu=eu(Qd);function ru(r,e){var t=[];return tu(r,function(i,s,n){e(i,s,n)&&t.push(i)}),t}function Si(r,e){var t=F(r)?ni:ru;return t(r,Mt(e))}function iu(r){return function(e,t,i){var s=Object(e);if(!bt(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 su=Math.max;function nu(r,e,t){var i=r==null?0:r.length;if(!i)return-1;var s=t==null?0:Yo(t);return s<0&&(s=su(i+s,0)),fa(r,Mt(e),s)}var Oe=iu(nu);function ou(r,e){return Vr(e,function(t){return r[t]})}function ge(r){return r==null?[]:ou(r,Re(r))}function au(r){return r==null}class cu extends Be{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(I.ENDED,e)}destroy(){this.source.destroy()}}class du 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(I.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 uu 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(I.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 hu extends Be{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(I.ENDED,e)}destroy(){var e;(e=this._audioStream)==null||e.destroy()}}class pu 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(I.ENDED,e)}destroy(){this.source.destroy()}}class lu 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(I.ENDED,e)}destroy(){this.source.destroy()}}class mu extends Be{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(I.ENDED,e)}destroy(){var e;(e=this._audioStream)==null||e.destroy()}}const fu=["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 De extends Error{constructor(e,t,i){super(),this.code=e,this.message=t,i&&(this.ext=i)}}function ve(r,e,t){const i=st.Landscape;if(e==="video"){const u=(i===st.Landscape?ir:sr)[r],[d,c,h,p]=u.split("x").map(l=>Number(l));return{width:d,height:c,frameRate:h,bitrate:p*1e3}}const s=nr[r],[n,a]=s.split("x").map(o=>Number(o));return{sampleRate:n,bitrate:a*1e3}}class _u 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(ar,"video"),{sampleRate:s}=ve(cr,"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 De(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 eo(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={};fu.includes(e)?t={facingMode:e}:t={deviceId:e};try{const i=await to({...t,...this._videoConstraints}),s=new Ro(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 io({...this._audioConstraints,deviceId:e}),i=new cu(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 so({audio:e,video:this._videoConstraints}),i=new uu(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 xr({url:e,video:!0,audio:!0,loop:!0}),i=new du(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 xr({url:e,video:!1,audio:!0,loop:!0}),i=new hu(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 ro({url:e,width:0,height:0,frameRate:30}),i=new pu(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=oo(e);if(t){const i=new lu(t);return this._customVideoStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),i.id}}startCustomAudioCapture(e){const t=ao(e);if(t){const i=new mu(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]||this._customVideoStreams[e]}getAudioStream(e){return this._microphoneStreams[e]||this._audioFileStreams[e]||this._customAudioStreams[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 Lt{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 Ti=new de("SingleComposer");class gu extends Lt{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){Ti.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):Ti.error("all video stream stop capture")}}_handleAudioStreamStopCapture(e){this._streamComposeController.removeAudioStream(e.id)}getComposedStream(){return this._composedStream}}class vu extends Q{constructor(e,{width:t,height:i,x:s,y:n,zOrder:a,keepRatio:o,mirrorType:u}){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._rect.mirrorType=u,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(it.SizeChange,({width:e,height:t})=>{this.setBaseProps("sourceWidth",e),this.setBaseProps("sourceHeight",t)})}getViewNode(){var s;if(!this._stream)return;let e={width:this._rect.width,height:this._rect.height};this._rect.keepRatio&&(e=this._getPaintSize({elementWidth:this._stream.width,elementHeight:this._stream.height})),this._paintSize=e;const t=(s=this._stream.viewNode)==null?void 0:s.size(e.width,e.height);let i;return this._rect.mirrorType!==void 0&&this._rect.mirrorType!==rr.None?i=t==null?void 0:t.mirror(this._rect.mirrorType):i=t,i=i==null?void 0:i.position(this._rect.x,this._rect.y),i}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)}set mirrorType(e){this.setBaseProps("mirrorType",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;case"mirrorType":this._rect.mirrorType=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 Ei 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 Cu=Object.defineProperty,yu=Object.getOwnPropertyDescriptor,Ie=(r,e,t,i)=>{for(var s=yu(e,t),n=r.length-1,a;n>=0;n--)(a=r[n])&&(s=a(e,t,s)||s);return s&&Cu(e,t,s),s};const bi=new de("composition-composer");function Me(r,e,t){const i=t.value;return t.value=function(...s){return this._active||bi.error("composer is not active"),i.apply(this,s)},t}class Ce extends Lt{constructor(e){super(e),this._compositionViewConfig={width:1080,height:720,frameRate:30,backgroundColor:"#000000"},this._sprites=[],this._videoMixer=new Eo}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 Ei(e),this._composedStream.setVideoStream(this._mixedVideoStream)}disable(){super.disable(),this._videoMixer.stop()}_updateSpriteToMixer(){const e=Si(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=>{au(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 Ei(i),this._composedStream.setVideoStream(this._mixedVideoStream)}}addVideoStream(e,t){if(!e.viewNode){bi.error("have no viewNode for composition");return}e.audioTrack&&this._streamComposeController.addAudioStream({streamId:e.id,volume:100});const i=new vu(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,i.mirrorType=e.mirrorType)}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)}}Ie([Me],Ce.prototype,"addVideoStream"),Ie([Me],Ce.prototype,"updateVideoStream"),Ie([Me],Ce.prototype,"removeVideoStream"),Ie([Me],Ce.prototype,"muteVideoStream"),Ie([Me],Ce.prototype,"unmuteVideoStream");class Su 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 Tu extends Be{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 Eu extends Lt{constructor(e){super(e),this._spriteList=[],this._audioMixer=new uo}onStreamCapture(e){}onStreamStopCapture(e){e&&this.removeAudioStream(e.id)}_updateSpriteToMixer(){const e=Si(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 Tu(e);this._composedStream.setAudioStream(t),this._audioMixer.mix([])}addAudioStream(e,t){const i=new Su(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 bu 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 ku=new de("streamComposeController");class Pu{constructor(e){this._streamManagerController=e,this._composedStream=new bu,this.singleComposer=new gu({streamManagerController:this._streamManagerController,composedStream:this._composedStream,streamComposeController:this}),this.compositionComposer=new Ce({streamManagerController:this._streamManagerController,composedStream:this._composedStream,streamComposeController:this}),this.mixerComposer=new Eu({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){ku.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 ki{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 xu extends ki{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={},Ft={},Nt={exports:{}},Pi;function Vt(){if(Pi)return Nt.exports;Pi=1;var r=Nt.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")})}),Nt.exports}var xi;function Ru(){return xi||(xi=1,function(r){var e=function(o){return String(Number(o))===o?Number(o):o},t=function(o,u,d,c){if(c&&!d)u[c]=e(o[1]);else for(var h=0;h<d.length;h+=1)o[h+1]!=null&&(u[d[h]]=e(o[h+1]))},i=function(o,u,d){var c=o.name&&o.names;o.push&&!u[o.push]?u[o.push]=[]:c&&!u[o.name]&&(u[o.name]={});var h=o.push?{}:c?u[o.name]:u;t(d.match(o.reg),h,o.names,o.name),o.push&&u[o.push].push(h)},s=Vt(),n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);r.parse=function(o){var u={},d=[],c=u;return o.split(/(\r\n|\r|\n)/).filter(n).forEach(function(h){var p=h[0],l=h.slice(2);p==="m"&&(d.push({rtp:[],fmtp:[]}),c=d[d.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,c,l)}}),u.media=d,u};var a=function(o,u){var d=u.split(/=(.+)/,2);return d.length===2?o[d[0]]=e(d[1]):d.length===1&&u.length>1&&(o[d[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=[],d=o.split(" ").map(e),c=0;c<d.length;c+=3)u.push({component:d[c],ip:d[c+1],port:d[c+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(d){var c,h=!1;return d[0]!=="~"?c=e(d):(c=e(d.substring(1,d.length)),h=!0),{scid:c,paused:h}})})}}(Ft)),Ft}var Ut,Ri;function Au(){if(Ri)return Ut;Ri=1;var r=Vt(),e=/%[sdv%]/g,t=function(a){var o=1,u=arguments,d=u.length;return a.replace(e,function(c){if(o>=d)return c;var h=u[o];switch(o+=1,c){case"%%":return"%";case"%s":return String(h);case"%d":return Number(h);case"%v":return""}})},i=function(a,o,u){var d=o.format instanceof Function?o.format(o.push?u:u[o.name]):o.format,c=[a+"="+d];if(o.names)for(var h=0;h<o.names.length;h+=1){var p=o.names[h];o.name?c.push(u[o.name][p]):c.push(u[o.names[h]])}else c.push(u[o.name]);return t.apply(null,c)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],n=["i","c","b","a"];return Ut=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,d=o.innerOrder||n,c=[];return u.forEach(function(h){r[h].forEach(function(p){p.name in a&&a[p.name]!=null?c.push(i(h,p,a)):p.push in a&&a[p.push]!=null&&a[p.push].forEach(function(l){c.push(i(h,p,l))})})}),a.media.forEach(function(h){c.push(i("m",r.m[0],h)),d.forEach(function(p){r[p].forEach(function(l){l.name in h&&h[l.name]!=null?c.push(i(p,l,h)):l.push in h&&h[l.push]!=null&&h[l.push].forEach(function(f){c.push(i(p,l,f))})})})}),c.join(`\r
|
|
57
57
|
`)+`\r
|
|
58
|
-
`},Vt}var Pi;function Ru(){if(Pi)return B;Pi=1;var r=Pu(),e=xu(),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 Au=Ru();const Xe=I(Au);function xi(r){return new Promise(e=>{setTimeout(e,r)})}async function wu(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 Ri(r,e={},t={}){const{timeout:i=0,retryDelay:s=0}=t;let{retryCount:n=0}=t;try{return await wu(r,e,i)}catch(a){if(n--,t.retryCount=n,n<0)throw a;return await xi(s),await Ri(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 Ou(r,e,t){var c,h,p,l,f,g,_,T,b,v,j,R,xs,Rs,As,ws,Os,Is,Ds,Ms,Ls,Fs,Ns,Vs,Us,$s,Bs,js,zs,Gs,Hs,qs,Ws,Xs,Ks,Js;const i=await Ut(e,t);await xi(r);const s=await Ut(e,t),{audio:n,video:a}=i,{audio:o,video:u}=s,d={};if(n!=null&&n.codec&&(o!=null&&o.codec)){const Jt=((c=o.outboundRtp)==null?void 0:c.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);d.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)-((xs=a.outboundRtp)==null?void 0:xs.timestamp),Yt=((Rs=u.outboundRtp)==null?void 0:Rs.bytesSent)-((As=a.outboundRtp)==null?void 0:As.bytesSent),Zt=((ws=u.outboundRtp)==null?void 0:ws.framesEncoded)-((Os=a.outboundRtp)==null?void 0:Os.framesEncoded),Qt=((Is=u.outboundRtp)==null?void 0:Is.totalEncodeTime)-((Ds=a.outboundRtp)==null?void 0:Ds.totalEncodeTime),Ys=((Ms=u.outboundRtp)==null?void 0:Ms.packetsSent)-((Ls=a.outboundRtp)==null?void 0:Ls.packetsSent),dh=((Fs=u.outboundRtp)==null?void 0:Fs.totalPacketSendDelay)-((Ns=a.outboundRtp)==null?void 0:Ns.totalPacketSendDelay),uh=((Vs=u.remoteInboundRtp)==null?void 0:Vs.packetsLost)-((Us=a.remoteInboundRtp)==null?void 0:Us.packetsLost);d.video={codec:u.codec.mimeType,sendBitrate:Yt/Jt*8e3,frameWidth:($s=u.outboundRtp)==null?void 0:$s.frameWidth,frameHeight:(Bs=u.outboundRtp)==null?void 0:Bs.frameHeight,framesPerSecond:(js=u.outboundRtp)==null?void 0:js.framesPerSecond,framesEncoded:(zs=u.outboundRtp)==null?void 0:zs.framesEncoded,keyFramesEncoded:(Gs=u.outboundRtp)==null?void 0:Gs.keyFramesEncoded,framesSent:(Hs=u.outboundRtp)==null?void 0:Hs.frameHeight,frameEncodeAvgTime:Qt*1e3/Zt,packetsSent:(qs=u.outboundRtp)==null?void 0:qs.packetsSent,packetSendDelay:dh*1e3/Ys,nackCount:(Ws=u.outboundRtp)==null?void 0:Ws.nackCount,firCount:(Xs=u.outboundRtp)==null?void 0:Xs.firCount,pliCount:(Ks=u.outboundRtp)==null?void 0:Ks.pliCount,packetsLost:(Js=u.remoteInboundRtp)==null?void 0:Js.packetsLost,packetsLostPercent:uh/Ys}}return d}const Iu=r=>{var t;if(!lr)return;const e=(t=r.rtp.filter(i=>i.codec==="opus")[0])==null?void 0:t.payload;e&&r.fmtp.forEach(i=>{i.payload===e&&(i.config="minptime=10;useinbandfec=1")})},Du=r=>{r.ext&&(dn||Le)&&(r.ext=r.ext.filter(e=>{var t;return!((t=e.uri)!=null&&t.includes("video-orientation"))}))};function Mu(r,e){r==null||r.rtp.forEach(({codec:t,payload:i})=>{if(["vp8","h264"].includes(t.toLocaleLowerCase())){const s=r.fmtp.find(n=>n.payload===i);s?s.config=[...s.config.split(";"),"x-google-min-bitrate=100",`x-google-start-bitrate=${e}`].join(";"):r.fmtp.push({payload:i,config:`x-google-min-bitrate=100;x-google-start-bitrate=${e}`})}})}const M=new de("PCConnect");class Lu{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;this._pc=i,this._bindRTCEvent();const s=e.filter(c=>(c==null?void 0:c.kind)==="audio")[0],n=e.filter(c=>(c==null?void 0:c.kind)==="video")[0];s&&this._ms.addTrack(s),n&&this._ms.addTrack(n),this._audioTransceiver=i.addTransceiver(s||"audio",{direction:"sendonly",sendEncodings:[{maxBitrate:t[0]}],streams:[this._ms]}),M.log("add track to pc,",s),this._videoTransceiver=i.addTransceiver(n||"video",{direction:"sendonly",sendEncodings:[{maxBitrate:t[1]}],streams:[this._ms]}),M.log("add track to pc,",n);const a=await i.createOffer();M.groupCollapsed("local offer"),M.log(a.sdp);const o=Xe.parse(a.sdp);o.media.forEach(c=>{c.type==="audio"?Iu(c):c.type==="video"&&(Du(c),Mu(c,t[1]))}),a.sdp=Xe.write(o),M.log("local offer modified"),M.log(a.sdp),await i.setLocalDescription(a);const u=await Ri(this._signalUrl,{method:"POST",mode:"cors",body:JSON.stringify({sessionId:""+this._sessionId,version:"1.0-html",localSdp:a,metadata:{platform:"Web"}})},this._opts);if((u==null?void 0:u.code)!==200)throw{code:u.code,message:u.message};M.log("remote answer:"),M.log(u.remoteSdp.sdp);const d=Xe.parse(u.remoteSdp.sdp);d.media.forEach(c=>{var h;(h=c.fingerprint)!=null&&h.hash&&(c.fingerprint.hash=c.fingerprint.hash.toUpperCase())}),u.remoteSdp.sdp=Xe.write(d),M.log("remote answer modified"),M.log(u.remoteSdp.sdp),M.groupEnd(),await i.setRemoteDescription(u.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)),M.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),M.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,M.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 Ou(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",()=>{M.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:{}},Ai;function Fu(){return Ai||(Ai=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,d,c){this.fn=u,this.context=d,this.once=c||!1}function n(u,d,c,h,p){if(typeof c!="function")throw new TypeError("The listener must be a function");var l=new s(c,h||u,p),f=t?t+d:d;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,d){--u._eventsCount===0?u._events=new i:delete u._events[d]}function o(){this._events=new i,this._eventsCount=0}o.prototype.eventNames=function(){var d=[],c,h;if(this._eventsCount===0)return d;for(h in c=this._events)e.call(c,h)&&d.push(t?h.slice(1):h);return Object.getOwnPropertySymbols?d.concat(Object.getOwnPropertySymbols(c)):d},o.prototype.listeners=function(d){var c=t?t+d:d,h=this._events[c];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(d){var c=t?t+d:d,h=this._events[c];return h?h.fn?1:h.length:0},o.prototype.emit=function(d,c,h,p,l,f){var g=t?t+d:d;if(!this._events[g])return!1;var _=this._events[g],T=arguments.length,b,v;if(_.fn){switch(_.once&&this.removeListener(d,_.fn,void 0,!0),T){case 1:return _.fn.call(_.context),!0;case 2:return _.fn.call(_.context,c),!0;case 3:return _.fn.call(_.context,c,h),!0;case 4:return _.fn.call(_.context,c,h,p),!0;case 5:return _.fn.call(_.context,c,h,p,l),!0;case 6:return _.fn.call(_.context,c,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(d,_[v].fn,void 0,!0),T){case 1:_[v].fn.call(_[v].context);break;case 2:_[v].fn.call(_[v].context,c);break;case 3:_[v].fn.call(_[v].context,c,h);break;case 4:_[v].fn.call(_[v].context,c,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(d,c,h){return n(this,d,c,h,!1)},o.prototype.once=function(d,c,h){return n(this,d,c,h,!0)},o.prototype.removeListener=function(d,c,h,p){var l=t?t+d:d;if(!this._events[l])return this;if(!c)return a(this,l),this;var f=this._events[l];if(f.fn)f.fn===c&&(!p||f.once)&&(!h||f.context===h)&&a(this,l);else{for(var g=0,_=[],T=f.length;g<T;g++)(f[g].fn!==c||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(d){var c;return d?(c=t?t+d:d,this._events[c]&&a(this,c)):(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 Nu=Fu();const Vu=I(Nu);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 Uu 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 wi(r,e,t){return new Uu(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 $u{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 Oi='(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||{}),I=(i=>(i.Video="video",i.Audio="audio",i))(I||{}),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||{}),w=(i=>(i.Ready="ready",i.Error="error",i.FirstFramePushed="firstframepushed",i.Flvfile="flvfile",i.STATS="stats",i.Close="close",i))(w||{});function $(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var k={exports:{}},U;function q(){return U||(U=1,function(i){var t=Object.prototype.hasOwnProperty,e="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(e=!1));function r(u,a,n){this.fn=u,this.context=a,this.once=n||!1}function o(u,a,n,h,m){if(typeof n!="function")throw new TypeError("The listener must be a function");var g=new r(n,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=[],n,h;if(this._eventsCount===0)return a;for(h in n=this._events)t.call(n,h)&&a.push(e?h.slice(1):h);return Object.getOwnPropertySymbols?a.concat(Object.getOwnPropertySymbols(n)):a},c.prototype.listeners=function(a){var n=e?e+a:a,h=this._events[n];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 n=e?e+a:a,h=this._events[n];return h?h.fn?1:h.length:0},c.prototype.emit=function(a,n,h,m,g,f){var F=e?e+a:a;if(!this._events[F])return!1;var d=this._events[F],C=arguments.length,N,p;if(d.fn){switch(d.once&&this.removeListener(a,d.fn,void 0,!0),C){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,n),!0;case 3:return d.fn.call(d.context,n,h),!0;case 4:return d.fn.call(d.context,n,h,m),!0;case 5:return d.fn.call(d.context,n,h,m,g),!0;case 6:return d.fn.call(d.context,n,h,m,g,f),!0}for(p=1,N=new Array(C-1);p<C;p++)N[p-1]=arguments[p];d.fn.apply(d.context,N)}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),C){case 1:d[p].fn.call(d[p].context);break;case 2:d[p].fn.call(d[p].context,n);break;case 3:d[p].fn.call(d[p].context,n,h);break;case 4:d[p].fn.call(d[p].context,n,h,m);break;default:if(!N)for(R=1,N=new Array(C-1);R<C;R++)N[R-1]=arguments[R];d[p].fn.apply(d[p].context,N)}}return!0},c.prototype.on=function(a,n,h){return o(this,a,n,h,!1)},c.prototype.once=function(a,n,h){return o(this,a,n,h,!0)},c.prototype.removeListener=function(a,n,h,m){var g=e?e+a:a;if(!this._events[g])return this;if(!n)return _(this,g),this;var f=this._events[g];if(f.fn)f.fn===n&&(!m||f.once)&&(!h||f.context===h)&&_(this,g);else{for(var F=0,d=[],C=f.length;F<C;F++)(f[F].fn!==n||m&&!f[F].once||h&&f[F].context!==h)&&d.push(f[F]);d.length?this._events[g]=d.length===1?d[0]:d:_(this,g)}return this},c.prototype.removeAllListeners=function(a){var n;return a?(n=e?e+a:a,this._events[n]&&_(this,n)):(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(),H=$(z);const x=class x{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 x.enable}get _enableLong(){return x.enableLong}get long(){return this._enableLong}};x.enable=!1,x.enableLong=!1;let E=x;function S(i){i=i.filter(Boolean);const t=new Uint8Array(i.reduce((s,r)=>s+r.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",ignoreRelPublish:!1},T=new E("RTMP_AudioEncoder");class j{constructor(t){this._encodedFrameCount=0,this._ready=!1,this._lastFrame=null,this._aacOutput=(e,s)=>{const r=this._module.HEAPU8.subarray(e,e+s);if(!this._lastFrame)return;this._encodedFrameCount++;const{props:o}=this._lastFrame,_={buffer:new Uint8Array(r),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,r;const o=new Promise((_,c)=>{r=_,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(()=>{r(),T.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 r=0;r<e;r++)t[r]=t[r]*32768;(s=this._rnnoiseModule)==null||s.processFrame(t);for(let r=0;r<e;r++)t[r]=t[r]/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 r=this._module._encode_one_frame(s);if(r<0)throw new Error(`encode aac frame error, code:${r}`)}_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,T.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 r=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:r.data.audioData.timestamp,sampleRate:r.data.audioData.sampleRate,numberOfChannels:r.data.audioData.numberOfChannels}}}}var y=(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))(y||{});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 b(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 r=this._audioFrameQueue.compose({offset:0,data:{audioData:e,buffer:s}});if(r)try{this._encoder.encode(r)}catch(o){this._core.emit(O.OnError,b(y.AUDIO_ENCODE_FAIL,o.message))}},this._core=t,this._encoder=new j(t)}async init(){try{await this._encoder.init()}catch(t){throw b(y.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 L=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){L.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(),L.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,r)=>{const o=new Uint8Array(s.byteLength);s.copyTo(o),this._emitFrame(o,s,r)},error:s=>{this._clearEncodeTimer(),this._core.emit(O.OnError,b(y.VIDEO_ENCODE_FAIL,s.message))}}),this._encoder.configure(t),L.log("encoder configured")}).then(this._startTimer).catch(e=>{throw b(y.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,L.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);L.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(r){this._core.emit(O.OnError,r)}}encode(t){this._encoder.encode(t)}startLoopEncodeLastFrame(){this._encoder.startLoop(this._core.getSetting().frameRate)}flushEncoder(){this._encoder.flush()}destroy(){this._encoder.destroy()}}const V=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 r=Date.now()-this._lastVideoReceived;this._videoNextDts=this._videoNextDts===this._audioNextDts?this._videoNextDts+this.videoRefDuration:this._audioNextDts||this._videoNextDts+r,this._videoBaseDts=this._videoNextDts-e.timestamp,V.warn(`video stream timestamp breaked! dts:${this._videoNextDts} -> ${e.timestamp}, videoBaseDts=${this._videoBaseDts}, deltaToLastFrame=${r}`)}e.timestamp=e.timestamp+this._videoBaseDts;const s=e.timestamp-this._videoLastDts;return s>100&&V.warn("video frame large gap",s),this._videoLastDts=this._videoNextDts=e.timestamp,V.long&&V.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,I.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,V.warn(`audio stream timestamp breaked! dts:${this._audioNextDts} -> ${e.timestamp}, audioBaseDts=${this._audioBaseDts}`)),this._audioNextDts=e.timestamp=e.timestamp-this._audioBaseDts,V.long&&V.log(`A frame, dts: ${e.timestamp}, originDts:${e.originTs}`),this._core.emit(l.OnEncodedFrame,I.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===I.Video&&this._videoEncode.setConfiguration({videoBitrate:s}),e===I.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 B=(i=>(i[i.AUDIO=8]="AUDIO",i[i.VIDEO=9]="VIDEO",i[i.SCRIPT_DATA=18]="SCRIPT_DATA",i))(B||{});const te=10,ie=1,se=7,oe={96e3:0,48e3:3,44100:4,22050:7,16e3:8,8e3:11};function re(i){const t=(i[4]&3)+1;let e;const s=[],r=[];let o=6;const _=i[5]&31;let c;for(let n=0;n<_;n++){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 n=0;n<u;n++)a=i[o]<<8|i[o+1],o+=2,a&&(r.push(i.subarray(o,o+a)),o+=a);return{sps:e,spsArr:s,ppsArr:r,nalUnitSize:t}}class ne{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 r=this._genTagHeader(t,s.length,e.props.timestamp),o=r.length+s.length;return S([r,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 r=this._genTagHeader(t,s.length,e.props.timestamp),o=r.length+s.length;return S([r,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 S(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 S(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=re(new Uint8Array(t.cfg.description)),s=e.spsArr[0].length,r=e.ppsArr[0].length;return S([new Uint8Array([0,0,s>>8,s%256]),e.spsArr[0],new Uint8Array([0,0,r>>8,r%256]),e.ppsArr[0],t.buffer])}}const ae=new E("RTMP_Packet");class de{constructor(t){this._firstFrame=!0,this._flv=new ne,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(B.VIDEO,s);this._core.emit(l.OnPacketed,c)}if(o.hasAudio){const c=this._flv.genSeqTag(B.AUDIO,s);this._core.emit(l.OnPacketed,c)}this._firstFrame=!1,ae.log("first frame encoded & packed")}const r=this._flv.genFrameTag(e==="video"?B.VIDEO:B.AUDIO,s);this._core.emit(l.OnPacketed,r,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 D=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;D.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(){D.log("add timer to check uplink speed increased"),clearInterval(this._increaseTimer),this._increaseTimer=setTimeout(()=>{const t=this._core.getSetting();D.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&&(D.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 b(y.WTP_OPEN_FAIL,e.message)}}async _connect(){const t=new WebTransport(this._url);let e;t.closed.then(()=>{D.log("webtransport closed")}).catch(r=>{e=r.message,D.log("webtransport closed due to",r)}).finally(()=>{this._connectClosed=!0,this._core.emit(O.OnConnectClosed,e),this._core.emit(O.OnError,b(y.WTP_CONNECT_FAIL,e))}),await t.ready,this._transport=t;const s=await t.createBidirectionalStream();this._writer=s.writable.getWriter(),this._write(),D.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),D.log("first frame pushed")),this._upSpeed.addSample(t.length);try{await this._write()}catch(s){D.log("writer error:",s)}}getFile(){return S(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 H{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)}async checkVideoHardwareAcceleration(){const t=["prefer-hardware","prefer-software","no-preference"],e=this.getSetting(),s={codec:e.codec,width:1280,height:720,framerate:15,bitrate:e.videoBitrate};for(const r of t)try{if((await VideoEncoder.isConfigSupported({...s,hardwareAcceleration:r})).supported)return this.updateSetting({hardwareAcceleration:r}),Promise.resolve()}catch{throw b(y.VIDEO_ENCODE_CONFIGURE_FAIL,`VideoEncoder not support hardwareAcceleration, ${JSON.stringify({...s,hardwareAcceleration:r})}`)}throw b(y.VIDEO_ENCODE_CONFIGURE_FAIL,"VideoEncoder not support hardwareAcceleration")}async ready(){await Promise.all([this.checkVideoHardwareAcceleration(),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===I.Video&&this.updateSetting({videoBitrate:e}),t===I.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:w.Error,data:s.toJson()})}),i.on(O.OnConnectClosed,()=>{self.postMessage({type:w.Close})}),i.on(O.OnFirstFramePushed,()=>{self.postMessage({type:w.FirstFramePushed})});try{await i.ready(),self.postMessage({type:w.Ready})}catch(s){self.postMessage({type:w.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:w.Error,data:s.toJson()})}}break;case v.GetStats:self.postMessage({type:w.STATS,data:i.getStats()});break;case v.EncodeConfig:{i.setEncodeCapacity(t.data.cfg);break}case v.Download:{const e=i.down();self.postMessage({type:w.Flvfile,buffer:e},[e.buffer])}break;case v.UnPublish:{i.destroy();break}}})}})();\n',Ii=typeof self<"u"&&self.Blob&&new Blob([Oi],{type:"text/javascript;charset=utf-8"});function Bu(r){let e;try{if(e=Ii&&(self.URL||self.webkitURL).createObjectURL(Ii),!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(Oi),{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 Ke=new se("Bridge");class Di extends Vu{constructor(){super(),this._worker=null,this._audioMsTrack=null,this._videoMsTrack=null,this._capture=new $u(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(),Ke.log("rtmp ready!"),e(!0)}};try{this._worker=new Bu}catch(o){t(wi(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:Ke.table(i.data.data),this.emit(ue.OnError,i.data.data);break;case he.Flvfile:ju(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,wi(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;Ke.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;Ke.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 ju(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 zu{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 Di,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 Gu=new de("PushController");class Hu extends Ti{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 Lu(e,this._pushConfig,this._OnRtcStateChange):n=new zu(e,this._pushConfig,this._OnRTMPError,this._OnRTMPSuccess),this._connect=n;try{await n.publish([s,i],[this._audioBitrate,this._videoBitrate],t)}catch(a){Gu.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 qu extends Q{constructor(e){super(),this._previewConsumer=new ku(e.getComposedStream(),{streamConsumeController:this}),this._pushConsumer=new Hu(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 Wu=()=>typeof window>"u",H={},Je=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 Li(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 Xu=async()=>{let r=await Je("sendonly");return navigator.userAgent.includes("VivoBrowser")&&(r=await Je("sendonly")),H.h264encode=Li(r),H.vp8encode=r.indexOf("vp8")>-1,H},Ku=async()=>{let r=await Je("recvonly");return navigator.userAgent.includes("VivoBrowser")&&(r=await Je("recvonly")),H.h264decode=Li(r),H.vp8decode=r.indexOf("vp8")>-1,H},Ju=async()=>{if(typeof H.h264encode>"u")try{await Xu()}catch{return!1}return H.h264encode||!1},Yu=async()=>{if(typeof H.h264decode>"u")try{await Ku()}catch{return!1}return H.h264decode||!1};class Zu{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 Qu=new Zu;let Fi=!0,Ni=!0;function Ye(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=d=>{const c=t(d);c&&(o.handleEvent?o.handleEvent(c):o(c))};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 eh(r){return typeof r!="boolean"?new Error("Argument type: "+typeof r+". Please use a boolean."):(Fi=r,r?"adapter.js logging disabled":"adapter.js logging enabled")}function th(r){return typeof r!="boolean"?new Error("Argument type: "+typeof r+". Please use a boolean."):(Ni=!r,"adapter.js deprecation warnings "+(r?"disabled":"enabled"))}function Vi(){if(typeof window=="object"){if(Fi)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function jt(r,e){Ni&&console.warn(r+" is deprecated, please use "+e+" instead.")}function rh(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=Ye(t.userAgent,/Firefox\/(\d+)\./,1);else if(t.webkitGetUserMedia||r.isSecureContext===!1&&r.webkitRTCPeerConnection)e.browser="chrome",e.version=Ye(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(r.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=Ye(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 Ui(r){return Object.prototype.toString.call(r)==="[object Object]"}function $i(r){return Ui(r)?Object.keys(r).reduce(function(e,t){const i=Ui(r[t]),s=i?$i(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 Bi(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 ji=Vi;function zi(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(d=>{if(d==="require"||d==="advanced"||d==="mediaSource")return;const c=typeof o[d]=="object"?o[d]:{ideal:o[d]};c.exact!==void 0&&typeof c.exact=="number"&&(c.min=c.max=c.exact);const h=function(p,l){return p?p+l.charAt(0).toUpperCase()+l.slice(1):l==="deviceId"?"sourceId":l};if(c.ideal!==void 0){u.optional=u.optional||[];let p={};typeof c.ideal=="number"?(p[h("min",d)]=c.ideal,u.optional.push(p),p={},p[h("max",d)]=c.ideal,u.optional.push(p)):(p[h("",d)]=c.ideal,u.optional.push(p))}c.exact!==void 0&&typeof c.exact!="number"?(u.mandatory=u.mandatory||{},u.mandatory[h("",d)]=c.exact):["min","max"].forEach(p=>{c[p]!==void 0&&(u.mandatory=u.mandatory||{},u.mandatory[h(p,d)]=c[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 d=function(c,h,p){h in c&&!(p in c)&&(c[p]=c[h],delete c[h])};o=JSON.parse(JSON.stringify(o)),d(o.audio,"autoGainControl","googAutoGainControl"),d(o.audio,"noiseSuppression","googNoiseSuppression"),o.audio=i(o.audio)}if(o&&typeof o.video=="object"){let d=o.video.facingMode;d=d&&(typeof d=="object"?d:{ideal:d});const c=e.version<66;if(d&&(d.exact==="user"||d.exact==="environment"||d.ideal==="user"||d.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!c)){delete o.video.facingMode;let h;if(d.exact==="environment"||d.ideal==="environment"?h=["back","rear"]:(d.exact==="user"||d.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=d.exact?{exact:l.deviceId}:{ideal:l.deviceId}),o.video=i(o.video),ji("chrome: "+JSON.stringify(o)),u(o)})}o.video=i(o.video)}return ji("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,d){s(o,c=>{t.webkitGetUserMedia(c,u,h=>{d&&d(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,d=>o(d).then(c=>{if(d.audio&&!c.getAudioTracks().length||d.video&&!c.getVideoTracks().length)throw c.getTracks().forEach(h=>{h.stop()}),new DOMException("","NotFoundError");return c},c=>Promise.reject(n(c))))}}}function Gi(r){r.MediaStream=r.MediaStream||r.webkitMediaStream}function Hi(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 qi(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 d=s.apply(this,arguments);return d||(d=e(this,o),this._senders.push(d)),d};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 Wi(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=>Bi(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=>Bi(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 Xi(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(d=>{if(this.getSenders().find(h=>h.track===d))throw new DOMException("Track already exists.","InvalidAccessError")});const o=this.getSenders();t.apply(this,arguments);const u=this.getSenders().filter(d=>o.indexOf(d)===-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 Ki(r,e){if(!r.RTCPeerConnection)return;if(r.RTCPeerConnection.prototype.addTrack&&e.version>=65)return Xi(r);const t=r.RTCPeerConnection.prototype.getLocalStreams;r.RTCPeerConnection.prototype.getLocalStreams=function(){const c=t.apply(this);return this._reverseStreams=this._reverseStreams||{},c.map(h=>this._reverseStreams[h.id])};const i=r.RTCPeerConnection.prototype.addStream;r.RTCPeerConnection.prototype.addStream=function(c){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},c.getTracks().forEach(h=>{if(this.getSenders().find(l=>l.track===h))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[c.id]){const h=new r.MediaStream(c.getTracks());this._streams[c.id]=h,this._reverseStreams[h.id]=c,c=h}i.apply(this,[c])};const s=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(c){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.apply(this,[this._streams[c.id]||c]),delete this._reverseStreams[this._streams[c.id]?this._streams[c.id].id:c.id],delete this._streams[c.id]},r.RTCPeerConnection.prototype.addTrack=function(c,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===c))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===c))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(c),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const g=new r.MediaStream([c]);this._streams[h.id]=g,this._reverseStreams[g.id]=h,this.addStream(g)}return this.getSenders().find(g=>g.track===c)};function n(d,c){let h=c.sdp;return Object.keys(d._reverseStreams||[]).forEach(p=>{const l=d._reverseStreams[p],f=d._streams[l.id];h=h.replace(new RegExp(f.id,"g"),l.id)}),new RTCSessionDescription({type:c.type,sdp:h})}function a(d,c){let h=c.sdp;return Object.keys(d._reverseStreams||[]).forEach(p=>{const l=d._reverseStreams[p],f=d._streams[l.id];h=h.replace(new RegExp(l.id,"g"),f.id)}),new RTCSessionDescription({type:c.type,sdp:h})}["createOffer","createAnswer"].forEach(function(d){const c=r.RTCPeerConnection.prototype[d],h={[d](){const p=arguments;return arguments.length&&typeof arguments[0]=="function"?c.apply(this,[f=>{const g=n(this,f);p[0].apply(null,[g])},f=>{p[1]&&p[1].apply(null,f)},arguments[2]]):c.apply(this,arguments).then(f=>n(this,f))}};r.RTCPeerConnection.prototype[d]=h[d]});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 d=u.get.apply(this);return d.type===""?d:n(this,d)}}),r.RTCPeerConnection.prototype.removeTrack=function(c){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!c._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(c._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=>c.track===g)&&(p=this._streams[l])}),p&&(p.getTracks().length===1?this.removeStream(this._reverseStreams[p.id]):p.removeTrack(c.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 Ji(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 Yi=Object.freeze(Object.defineProperty({__proto__:null,fixNegotiationNeeded:Ji,shimAddTrackRemoveTrack:Ki,shimAddTrackRemoveTrackWithNative:Xi,shimGetSendersWithDtmf:qi,shimGetUserMedia:zi,shimMediaStream:Gi,shimOnTrack:Hi,shimPeerConnection:Gt,shimSenderReceiverGetStats:Wi},Symbol.toStringTag,{value:"Module"}));function Zi(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 ih(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 Qi(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(d=>{d.type=t[d.type]||d.type})}catch(d){if(d.name!=="TypeError")throw d;u.forEach((c,h)=>{u.set(h,Object.assign({},c,{type:t[c.type]||c.type}))})}return u}).then(a,o)}}function es(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 ts(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 rs(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 is(r){r.DataChannel&&!r.RTCDataChannel&&(r.RTCDataChannel=r.DataChannel)}function ss(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 ns(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 os(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 as(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 cs=Object.freeze(Object.defineProperty({__proto__:null,shimAddTransceiver:ss,shimCreateAnswer:as,shimCreateOffer:os,shimGetDisplayMedia:ih,shimGetParameters:ns,shimGetUserMedia:Zi,shimOnTrack:Qi,shimPeerConnection:Ht,shimRTCDataChannel:is,shimReceiverGetStats:ts,shimRemoveStream:rs,shimSenderGetStats:es},Symbol.toStringTag,{value:"Module"}));function ds(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 us(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 hs(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(d,c){const h=arguments.length>=2?arguments[2]:arguments[0],p=t.apply(this,[h]);return c?(p.then(d,c),Promise.resolve()):p},e.createAnswer=function(d,c){const h=arguments.length>=2?arguments[2]:arguments[0],p=i.apply(this,[h]);return c?(p.then(d,c),Promise.resolve()):p};let o=function(u,d,c){const h=s.apply(this,[u]);return c?(h.then(d,c),Promise.resolve()):h};e.setLocalDescription=o,o=function(u,d,c){const h=n.apply(this,[u]);return c?(h.then(d,c),Promise.resolve()):h},e.setRemoteDescription=o,o=function(u,d,c){const h=a.apply(this,[u]);return c?(h.then(d,c),Promise.resolve()):h},e.addIceCandidate=o}function ps(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(ls(s))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(i,s,n){e.mediaDevices.getUserMedia(i).then(s,n)}).bind(e))}function ls(r){return r&&r.video!==void 0?Object.assign({},r,{video:$i(r.video)}):r}function ms(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 fs(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 _s(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 gs(r){typeof r!="object"||r.AudioContext||(r.AudioContext=r.webkitAudioContext)}const vs=Object.freeze(Object.defineProperty({__proto__:null,shimAudioContext:gs,shimCallbacksAPI:hs,shimConstraints:ls,shimCreateOfferLegacy:_s,shimGetUserMedia:ps,shimLocalStreamsAPI:ds,shimRTCIceServerUrls:ms,shimRemoteStreamsAPI:us,shimTrackEventTransceiver:fs},Symbol.toStringTag,{value:"Module"}));var qt={exports:{}},Cs;function sh(){return Cs||(Cs=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(`
|
|
58
|
+
`},Ut}var Ai;function wu(){if(Ai)return B;Ai=1;var r=Ru(),e=Au(),t=Vt();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 Ou=wu();const Xe=D(Ou);function wi(r){return new Promise(e=>{setTimeout(e,r)})}async function Du(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 Oi(r,e={},t={}){const{timeout:i=0,retryDelay:s=0}=t;let{retryCount:n=0}=t;try{return await Du(r,e,i)}catch(a){if(n--,t.retryCount=n,n<0)throw a;return await wi(s),await Oi(r,e,t)}}function w(r,e){let t;return e.forEach(i=>{i.type===r&&(t=i)}),t}async function $t(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 Iu(r,e,t){var c,h,p,l,f,g,_,T,b,v,j,R,ws,Os,Ds,Is,Ms,Ls,Fs,Ns,Vs,Us,$s,Bs,js,zs,Gs,Hs,qs,Ws,Xs,Ks,Js,Ys,Zs,Qs;const i=await $t(e,t);await wi(r);const s=await $t(e,t),{audio:n,video:a}=i,{audio:o,video:u}=s,d={};if(n!=null&&n.codec&&(o!=null&&o.codec)){const Yt=((c=o.outboundRtp)==null?void 0:c.timestamp)-((h=n.outboundRtp)==null?void 0:h.timestamp),Zt=((p=o.outboundRtp)==null?void 0:p.bytesSent)-((l=n.outboundRtp)==null?void 0:l.bytesSent),Qt=((f=o.remoteInboundRtp)==null?void 0:f.packetsLost)-((g=n.remoteInboundRtp)==null?void 0:g.packetsLost),er=((_=o.outboundRtp)==null?void 0:_.packetsSent)-((T=n.outboundRtp)==null?void 0:T.packetsSent);d.audio={codec:o.codec.mimeType,channels:o.codec.channels,sendBitrate:Zt/Yt*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:Qt/er}}if(a!=null&&a.codec&&(u!=null&&u.codec)){const Yt=((R=u.outboundRtp)==null?void 0:R.timestamp)-((ws=a.outboundRtp)==null?void 0:ws.timestamp),Zt=((Os=u.outboundRtp)==null?void 0:Os.bytesSent)-((Ds=a.outboundRtp)==null?void 0:Ds.bytesSent),Qt=((Is=u.outboundRtp)==null?void 0:Is.framesEncoded)-((Ms=a.outboundRtp)==null?void 0:Ms.framesEncoded),er=((Ls=u.outboundRtp)==null?void 0:Ls.totalEncodeTime)-((Fs=a.outboundRtp)==null?void 0:Fs.totalEncodeTime),en=((Ns=u.outboundRtp)==null?void 0:Ns.packetsSent)-((Vs=a.outboundRtp)==null?void 0:Vs.packetsSent),hh=((Us=u.outboundRtp)==null?void 0:Us.totalPacketSendDelay)-(($s=a.outboundRtp)==null?void 0:$s.totalPacketSendDelay),ph=((Bs=u.remoteInboundRtp)==null?void 0:Bs.packetsLost)-((js=a.remoteInboundRtp)==null?void 0:js.packetsLost);d.video={codec:u.codec.mimeType,sendBitrate:Zt/Yt*8e3,frameWidth:(zs=u.outboundRtp)==null?void 0:zs.frameWidth,frameHeight:(Gs=u.outboundRtp)==null?void 0:Gs.frameHeight,framesPerSecond:(Hs=u.outboundRtp)==null?void 0:Hs.framesPerSecond,framesEncoded:(qs=u.outboundRtp)==null?void 0:qs.framesEncoded,keyFramesEncoded:(Ws=u.outboundRtp)==null?void 0:Ws.keyFramesEncoded,framesSent:(Xs=u.outboundRtp)==null?void 0:Xs.frameHeight,frameEncodeAvgTime:er*1e3/Qt,packetsSent:(Ks=u.outboundRtp)==null?void 0:Ks.packetsSent,packetSendDelay:hh*1e3/en,nackCount:(Js=u.outboundRtp)==null?void 0:Js.nackCount,firCount:(Ys=u.outboundRtp)==null?void 0:Ys.firCount,pliCount:(Zs=u.outboundRtp)==null?void 0:Zs.pliCount,packetsLost:(Qs=u.remoteInboundRtp)==null?void 0:Qs.packetsLost,packetsLostPercent:ph/en}}return d}const Mu=r=>{var t;if(!fr)return;const e=(t=r.rtp.filter(i=>i.codec==="opus")[0])==null?void 0:t.payload;e&&r.fmtp.forEach(i=>{i.payload===e&&(i.config="minptime=10;useinbandfec=1")})},Lu=r=>{r.ext&&(pn||Le)&&(r.ext=r.ext.filter(e=>{var t;return!((t=e.uri)!=null&&t.includes("video-orientation"))}))};function Fu(r,e){r==null||r.rtp.forEach(({codec:t,payload:i})=>{if(["vp8","h264"].includes(t.toLocaleLowerCase())){const s=r.fmtp.find(n=>n.payload===i);s?s.config=[...s.config.split(";"),"x-google-min-bitrate=100",`x-google-start-bitrate=${e}`].join(";"):r.fmtp.push({payload:i,config:`x-google-min-bitrate=100;x-google-start-bitrate=${e}`})}})}const M=new de("PCConnect");class Nu{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;this._pc=i,this._bindRTCEvent();const s=e.filter(c=>(c==null?void 0:c.kind)==="audio")[0],n=e.filter(c=>(c==null?void 0:c.kind)==="video")[0];s&&this._ms.addTrack(s),n&&this._ms.addTrack(n),this._audioTransceiver=i.addTransceiver(s||"audio",{direction:"sendonly",sendEncodings:[{maxBitrate:t[0]}],streams:[this._ms]}),M.log("add track to pc,",s),this._videoTransceiver=i.addTransceiver(n||"video",{direction:"sendonly",sendEncodings:[{maxBitrate:t[1]}],streams:[this._ms]}),M.log("add track to pc,",n);const a=await i.createOffer();M.groupCollapsed("local offer"),M.log(a.sdp);const o=Xe.parse(a.sdp);o.media.forEach(c=>{c.type==="audio"?Mu(c):c.type==="video"&&(Lu(c),Fu(c,t[1]))}),a.sdp=Xe.write(o),M.log("local offer modified"),M.log(a.sdp),await i.setLocalDescription(a);const u=await Oi(this._signalUrl,{method:"POST",mode:"cors",body:JSON.stringify({sessionId:""+this._sessionId,version:"1.0-html",localSdp:a,metadata:{platform:"Web"}})},this._opts);if((u==null?void 0:u.code)!==200)throw{code:u.code,message:u.message};M.log("remote answer:"),M.log(u.remoteSdp.sdp);const d=Xe.parse(u.remoteSdp.sdp);d.media.forEach(c=>{var h;(h=c.fingerprint)!=null&&h.hash&&(c.fingerprint.hash=c.fingerprint.hash.toUpperCase())}),u.remoteSdp.sdp=Xe.write(d),M.log("remote answer modified"),M.log(u.remoteSdp.sdp),M.groupEnd(),await i.setRemoteDescription(u.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)),M.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),M.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,M.log("close pc!")}getStats(){var e,t;return $t((e=this._audioTransceiver)==null?void 0:e.sender,(t=this._videoTransceiver)==null?void 0:t.sender)}getStatsSnapshoot(e){var t,i;return Iu(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",()=>{M.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||{}),Bt={exports:{}},Di;function Vu(){return Di||(Di=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,d,c){this.fn=u,this.context=d,this.once=c||!1}function n(u,d,c,h,p){if(typeof c!="function")throw new TypeError("The listener must be a function");var l=new s(c,h||u,p),f=t?t+d:d;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,d){--u._eventsCount===0?u._events=new i:delete u._events[d]}function o(){this._events=new i,this._eventsCount=0}o.prototype.eventNames=function(){var d=[],c,h;if(this._eventsCount===0)return d;for(h in c=this._events)e.call(c,h)&&d.push(t?h.slice(1):h);return Object.getOwnPropertySymbols?d.concat(Object.getOwnPropertySymbols(c)):d},o.prototype.listeners=function(d){var c=t?t+d:d,h=this._events[c];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(d){var c=t?t+d:d,h=this._events[c];return h?h.fn?1:h.length:0},o.prototype.emit=function(d,c,h,p,l,f){var g=t?t+d:d;if(!this._events[g])return!1;var _=this._events[g],T=arguments.length,b,v;if(_.fn){switch(_.once&&this.removeListener(d,_.fn,void 0,!0),T){case 1:return _.fn.call(_.context),!0;case 2:return _.fn.call(_.context,c),!0;case 3:return _.fn.call(_.context,c,h),!0;case 4:return _.fn.call(_.context,c,h,p),!0;case 5:return _.fn.call(_.context,c,h,p,l),!0;case 6:return _.fn.call(_.context,c,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(d,_[v].fn,void 0,!0),T){case 1:_[v].fn.call(_[v].context);break;case 2:_[v].fn.call(_[v].context,c);break;case 3:_[v].fn.call(_[v].context,c,h);break;case 4:_[v].fn.call(_[v].context,c,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(d,c,h){return n(this,d,c,h,!1)},o.prototype.once=function(d,c,h){return n(this,d,c,h,!0)},o.prototype.removeListener=function(d,c,h,p){var l=t?t+d:d;if(!this._events[l])return this;if(!c)return a(this,l),this;var f=this._events[l];if(f.fn)f.fn===c&&(!p||f.once)&&(!h||f.context===h)&&a(this,l);else{for(var g=0,_=[],T=f.length;g<T;g++)(f[g].fn!==c||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(d){var c;return d?(c=t?t+d:d,this._events[c]&&a(this,c)):(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}(Bt)),Bt.exports}var Uu=Vu();const $u=D(Uu);var jt=(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))(jt||{});class Bu 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 Ii(r,e,t){return new Bu(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 ju{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 Mi='(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||{}),I=(i=>(i.Video="video",i.Audio="audio",i))(I||{}),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||{}),w=(i=>(i.Ready="ready",i.Error="error",i.FirstFramePushed="firstframepushed",i.Flvfile="flvfile",i.STATS="stats",i.Close="close",i))(w||{});function $(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var k={exports:{}},U;function q(){return U||(U=1,function(i){var t=Object.prototype.hasOwnProperty,e="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(e=!1));function r(u,a,n){this.fn=u,this.context=a,this.once=n||!1}function o(u,a,n,h,m){if(typeof n!="function")throw new TypeError("The listener must be a function");var g=new r(n,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=[],n,h;if(this._eventsCount===0)return a;for(h in n=this._events)t.call(n,h)&&a.push(e?h.slice(1):h);return Object.getOwnPropertySymbols?a.concat(Object.getOwnPropertySymbols(n)):a},c.prototype.listeners=function(a){var n=e?e+a:a,h=this._events[n];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 n=e?e+a:a,h=this._events[n];return h?h.fn?1:h.length:0},c.prototype.emit=function(a,n,h,m,g,f){var F=e?e+a:a;if(!this._events[F])return!1;var d=this._events[F],C=arguments.length,N,p;if(d.fn){switch(d.once&&this.removeListener(a,d.fn,void 0,!0),C){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,n),!0;case 3:return d.fn.call(d.context,n,h),!0;case 4:return d.fn.call(d.context,n,h,m),!0;case 5:return d.fn.call(d.context,n,h,m,g),!0;case 6:return d.fn.call(d.context,n,h,m,g,f),!0}for(p=1,N=new Array(C-1);p<C;p++)N[p-1]=arguments[p];d.fn.apply(d.context,N)}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),C){case 1:d[p].fn.call(d[p].context);break;case 2:d[p].fn.call(d[p].context,n);break;case 3:d[p].fn.call(d[p].context,n,h);break;case 4:d[p].fn.call(d[p].context,n,h,m);break;default:if(!N)for(R=1,N=new Array(C-1);R<C;R++)N[R-1]=arguments[R];d[p].fn.apply(d[p].context,N)}}return!0},c.prototype.on=function(a,n,h){return o(this,a,n,h,!1)},c.prototype.once=function(a,n,h){return o(this,a,n,h,!0)},c.prototype.removeListener=function(a,n,h,m){var g=e?e+a:a;if(!this._events[g])return this;if(!n)return _(this,g),this;var f=this._events[g];if(f.fn)f.fn===n&&(!m||f.once)&&(!h||f.context===h)&&_(this,g);else{for(var F=0,d=[],C=f.length;F<C;F++)(f[F].fn!==n||m&&!f[F].once||h&&f[F].context!==h)&&d.push(f[F]);d.length?this._events[g]=d.length===1?d[0]:d:_(this,g)}return this},c.prototype.removeAllListeners=function(a){var n;return a?(n=e?e+a:a,this._events[n]&&_(this,n)):(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(),H=$(z);const x=class x{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 x.enable}get _enableLong(){return x.enableLong}get long(){return this._enableLong}};x.enable=!1,x.enableLong=!1;let E=x;function S(i){i=i.filter(Boolean);const t=new Uint8Array(i.reduce((s,r)=>s+r.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",ignoreRelPublish:!1},T=new E("RTMP_AudioEncoder");class j{constructor(t){this._encodedFrameCount=0,this._ready=!1,this._lastFrame=null,this._aacOutput=(e,s)=>{const r=this._module.HEAPU8.subarray(e,e+s);if(!this._lastFrame)return;this._encodedFrameCount++;const{props:o}=this._lastFrame,_={buffer:new Uint8Array(r),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,r;const o=new Promise((_,c)=>{r=_,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(()=>{r(),T.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 r=0;r<e;r++)t[r]=t[r]*32768;(s=this._rnnoiseModule)==null||s.processFrame(t);for(let r=0;r<e;r++)t[r]=t[r]/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 r=this._module._encode_one_frame(s);if(r<0)throw new Error(`encode aac frame error, code:${r}`)}_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,T.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 r=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:r.data.audioData.timestamp,sampleRate:r.data.audioData.sampleRate,numberOfChannels:r.data.audioData.numberOfChannels}}}}var y=(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))(y||{});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 b(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 r=this._audioFrameQueue.compose({offset:0,data:{audioData:e,buffer:s}});if(r)try{this._encoder.encode(r)}catch(o){this._core.emit(O.OnError,b(y.AUDIO_ENCODE_FAIL,o.message))}},this._core=t,this._encoder=new j(t)}async init(){try{await this._encoder.init()}catch(t){throw b(y.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 L=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){L.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(),L.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,r)=>{const o=new Uint8Array(s.byteLength);s.copyTo(o),this._emitFrame(o,s,r)},error:s=>{this._clearEncodeTimer(),this._core.emit(O.OnError,b(y.VIDEO_ENCODE_FAIL,s.message))}}),this._encoder.configure(t),L.log("encoder configured")}).then(this._startTimer).catch(e=>{throw b(y.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,L.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);L.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(r){this._core.emit(O.OnError,r)}}encode(t){this._encoder.encode(t)}startLoopEncodeLastFrame(){this._encoder.startLoop(this._core.getSetting().frameRate)}flushEncoder(){this._encoder.flush()}destroy(){this._encoder.destroy()}}const V=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 r=Date.now()-this._lastVideoReceived;this._videoNextDts=this._videoNextDts===this._audioNextDts?this._videoNextDts+this.videoRefDuration:this._audioNextDts||this._videoNextDts+r,this._videoBaseDts=this._videoNextDts-e.timestamp,V.warn(`video stream timestamp breaked! dts:${this._videoNextDts} -> ${e.timestamp}, videoBaseDts=${this._videoBaseDts}, deltaToLastFrame=${r}`)}e.timestamp=e.timestamp+this._videoBaseDts;const s=e.timestamp-this._videoLastDts;return s>100&&V.warn("video frame large gap",s),this._videoLastDts=this._videoNextDts=e.timestamp,V.long&&V.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,I.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,V.warn(`audio stream timestamp breaked! dts:${this._audioNextDts} -> ${e.timestamp}, audioBaseDts=${this._audioBaseDts}`)),this._audioNextDts=e.timestamp=e.timestamp-this._audioBaseDts,V.long&&V.log(`A frame, dts: ${e.timestamp}, originDts:${e.originTs}`),this._core.emit(l.OnEncodedFrame,I.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===I.Video&&this._videoEncode.setConfiguration({videoBitrate:s}),e===I.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 B=(i=>(i[i.AUDIO=8]="AUDIO",i[i.VIDEO=9]="VIDEO",i[i.SCRIPT_DATA=18]="SCRIPT_DATA",i))(B||{});const te=10,ie=1,se=7,oe={96e3:0,48e3:3,44100:4,22050:7,16e3:8,8e3:11};function re(i){const t=(i[4]&3)+1;let e;const s=[],r=[];let o=6;const _=i[5]&31;let c;for(let n=0;n<_;n++){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 n=0;n<u;n++)a=i[o]<<8|i[o+1],o+=2,a&&(r.push(i.subarray(o,o+a)),o+=a);return{sps:e,spsArr:s,ppsArr:r,nalUnitSize:t}}class ne{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 r=this._genTagHeader(t,s.length,e.props.timestamp),o=r.length+s.length;return S([r,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 r=this._genTagHeader(t,s.length,e.props.timestamp),o=r.length+s.length;return S([r,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 S(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 S(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=re(new Uint8Array(t.cfg.description)),s=e.spsArr[0].length,r=e.ppsArr[0].length;return S([new Uint8Array([0,0,s>>8,s%256]),e.spsArr[0],new Uint8Array([0,0,r>>8,r%256]),e.ppsArr[0],t.buffer])}}const ae=new E("RTMP_Packet");class de{constructor(t){this._firstFrame=!0,this._flv=new ne,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(B.VIDEO,s);this._core.emit(l.OnPacketed,c)}if(o.hasAudio){const c=this._flv.genSeqTag(B.AUDIO,s);this._core.emit(l.OnPacketed,c)}this._firstFrame=!1,ae.log("first frame encoded & packed")}const r=this._flv.genFrameTag(e==="video"?B.VIDEO:B.AUDIO,s);this._core.emit(l.OnPacketed,r,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 D=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;D.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(){D.log("add timer to check uplink speed increased"),clearInterval(this._increaseTimer),this._increaseTimer=setTimeout(()=>{const t=this._core.getSetting();D.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&&(D.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 b(y.WTP_OPEN_FAIL,e.message)}}async _connect(){const t=new WebTransport(this._url);let e;t.closed.then(()=>{D.log("webtransport closed")}).catch(r=>{e=r.message,D.log("webtransport closed due to",r)}).finally(()=>{this._connectClosed=!0,this._core.emit(O.OnConnectClosed,e),this._core.emit(O.OnError,b(y.WTP_CONNECT_FAIL,e))}),await t.ready,this._transport=t;const s=await t.createBidirectionalStream();this._writer=s.writable.getWriter(),this._write(),D.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),D.log("first frame pushed")),this._upSpeed.addSample(t.length);try{await this._write()}catch(s){D.log("writer error:",s)}}getFile(){return S(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 H{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)}async checkVideoHardwareAcceleration(){const t=["prefer-hardware","prefer-software","no-preference"],e=this.getSetting(),s={codec:e.codec,width:1280,height:720,framerate:15,bitrate:e.videoBitrate};for(const r of t)try{if((await VideoEncoder.isConfigSupported({...s,hardwareAcceleration:r})).supported)return this.updateSetting({hardwareAcceleration:r}),Promise.resolve()}catch{throw b(y.VIDEO_ENCODE_CONFIGURE_FAIL,`VideoEncoder not support hardwareAcceleration, ${JSON.stringify({...s,hardwareAcceleration:r})}`)}throw b(y.VIDEO_ENCODE_CONFIGURE_FAIL,"VideoEncoder not support hardwareAcceleration")}async ready(){await Promise.all([this.checkVideoHardwareAcceleration(),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===I.Video&&this.updateSetting({videoBitrate:e}),t===I.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:w.Error,data:s.toJson()})}),i.on(O.OnConnectClosed,()=>{self.postMessage({type:w.Close})}),i.on(O.OnFirstFramePushed,()=>{self.postMessage({type:w.FirstFramePushed})});try{await i.ready(),self.postMessage({type:w.Ready})}catch(s){self.postMessage({type:w.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:w.Error,data:s.toJson()})}}break;case v.GetStats:self.postMessage({type:w.STATS,data:i.getStats()});break;case v.EncodeConfig:{i.setEncodeCapacity(t.data.cfg);break}case v.Download:{const e=i.down();self.postMessage({type:w.Flvfile,buffer:e},[e.buffer])}break;case v.UnPublish:{i.destroy();break}}})}})();\n',Li=typeof self<"u"&&self.Blob&&new Blob([Mi],{type:"text/javascript;charset=utf-8"});function zu(r){let e;try{if(e=Li&&(self.URL||self.webkitURL).createObjectURL(Li),!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(Mi),{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 Ke=new se("Bridge");class Fi extends $u{constructor(){super(),this._worker=null,this._audioMsTrack=null,this._videoMsTrack=null,this._capture=new ju(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(),Ke.log("rtmp ready!"),e(!0)}};try{this._worker=new zu}catch(o){t(Ii(jt.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:Ke.table(i.data.data),this.emit(ue.OnError,i.data.data);break;case he.Flvfile:Gu(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,Ii(jt.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;Ke.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;Ke.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 Gu(r){const e=document.createElement("a");e.href=URL.createObjectURL(new Blob([r])),e.download=Date.now()+".flv",e.click()}const Ni=new de("RTMPConnect");class Hu{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 Fi,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){Ni.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(){Ni.warn("unpublish"),this._rtmp.unpublish(),this._isPushing=!1}}const qu=new de("PushController");class Wu extends ki{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(cr,"audio").bitrate,this._videoBitrate=ve(ar,"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 De(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 De(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 Nu(e,this._pushConfig,this._OnRtcStateChange):n=new Hu(e,this._pushConfig,this._OnRTMPError,this._OnRTMPSuccess),this._connect=n;try{await n.publish([s,i],[this._audioBitrate,this._videoBitrate],t)}catch(a){qu.groupEnd(),n.unpublish();const o=new De(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 De(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 Xu extends Q{constructor(e){super(),this._previewConsumer=new xu(e.getComposedStream(),{streamConsumeController:this}),this._pushConsumer=new Wu(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 Ku=()=>typeof window>"u",H={},Je=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 Vi(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 Ju=async()=>{let r=await Je("sendonly");return navigator.userAgent.includes("VivoBrowser")&&(r=await Je("sendonly")),H.h264encode=Vi(r),H.vp8encode=r.indexOf("vp8")>-1,H},Yu=async()=>{let r=await Je("recvonly");return navigator.userAgent.includes("VivoBrowser")&&(r=await Je("recvonly")),H.h264decode=Vi(r),H.vp8decode=r.indexOf("vp8")>-1,H},Zu=async()=>{if(typeof H.h264encode>"u")try{await Ju()}catch{return!1}return H.h264encode||!1},Qu=async()=>{if(typeof H.h264decode>"u")try{await Yu()}catch{return!1}return H.h264decode||!1};class eh{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 th=new eh;let Ui=!0,$i=!0;function Ye(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=d=>{const c=t(d);c&&(o.handleEvent?o.handleEvent(c):o(c))};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 rh(r){return typeof r!="boolean"?new Error("Argument type: "+typeof r+". Please use a boolean."):(Ui=r,r?"adapter.js logging disabled":"adapter.js logging enabled")}function ih(r){return typeof r!="boolean"?new Error("Argument type: "+typeof r+". Please use a boolean."):($i=!r,"adapter.js deprecation warnings "+(r?"disabled":"enabled"))}function Bi(){if(typeof window=="object"){if(Ui)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function zt(r,e){$i&&console.warn(r+" is deprecated, please use "+e+" instead.")}function sh(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=Ye(t.userAgent,/Firefox\/(\d+)\./,1);else if(t.webkitGetUserMedia||r.isSecureContext===!1&&r.webkitRTCPeerConnection)e.browser="chrome",e.version=Ye(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(r.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=Ye(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 ji(r){return Object.prototype.toString.call(r)==="[object Object]"}function zi(r){return ji(r)?Object.keys(r).reduce(function(e,t){const i=ji(r[t]),s=i?zi(r[t]):r[t],n=i&&!Object.keys(s).length;return s===void 0||n?e:Object.assign(e,{[t]:s})},{}):r}function Gt(r,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(i=>{i.endsWith("Id")?Gt(r,r.get(e[i]),t):i.endsWith("Ids")&&e[i].forEach(s=>{Gt(r,r.get(s),t)})}))}function Gi(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&&Gt(r,o,s)})}),s}const Hi=Bi;function qi(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(d=>{if(d==="require"||d==="advanced"||d==="mediaSource")return;const c=typeof o[d]=="object"?o[d]:{ideal:o[d]};c.exact!==void 0&&typeof c.exact=="number"&&(c.min=c.max=c.exact);const h=function(p,l){return p?p+l.charAt(0).toUpperCase()+l.slice(1):l==="deviceId"?"sourceId":l};if(c.ideal!==void 0){u.optional=u.optional||[];let p={};typeof c.ideal=="number"?(p[h("min",d)]=c.ideal,u.optional.push(p),p={},p[h("max",d)]=c.ideal,u.optional.push(p)):(p[h("",d)]=c.ideal,u.optional.push(p))}c.exact!==void 0&&typeof c.exact!="number"?(u.mandatory=u.mandatory||{},u.mandatory[h("",d)]=c.exact):["min","max"].forEach(p=>{c[p]!==void 0&&(u.mandatory=u.mandatory||{},u.mandatory[h(p,d)]=c[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 d=function(c,h,p){h in c&&!(p in c)&&(c[p]=c[h],delete c[h])};o=JSON.parse(JSON.stringify(o)),d(o.audio,"autoGainControl","googAutoGainControl"),d(o.audio,"noiseSuppression","googNoiseSuppression"),o.audio=i(o.audio)}if(o&&typeof o.video=="object"){let d=o.video.facingMode;d=d&&(typeof d=="object"?d:{ideal:d});const c=e.version<66;if(d&&(d.exact==="user"||d.exact==="environment"||d.ideal==="user"||d.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!c)){delete o.video.facingMode;let h;if(d.exact==="environment"||d.ideal==="environment"?h=["back","rear"]:(d.exact==="user"||d.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=d.exact?{exact:l.deviceId}:{ideal:l.deviceId}),o.video=i(o.video),Hi("chrome: "+JSON.stringify(o)),u(o)})}o.video=i(o.video)}return Hi("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,d){s(o,c=>{t.webkitGetUserMedia(c,u,h=>{d&&d(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,d=>o(d).then(c=>{if(d.audio&&!c.getAudioTracks().length||d.video&&!c.getVideoTracks().length)throw c.getTracks().forEach(h=>{h.stop()}),new DOMException("","NotFoundError");return c},c=>Promise.reject(n(c))))}}}function Wi(r){r.MediaStream=r.MediaStream||r.webkitMediaStream}function Xi(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 Ki(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 d=s.apply(this,arguments);return d||(d=e(this,o),this._senders.push(d)),d};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 Ji(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=>Gi(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=>Gi(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 Yi(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(d=>{if(this.getSenders().find(h=>h.track===d))throw new DOMException("Track already exists.","InvalidAccessError")});const o=this.getSenders();t.apply(this,arguments);const u=this.getSenders().filter(d=>o.indexOf(d)===-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 Zi(r,e){if(!r.RTCPeerConnection)return;if(r.RTCPeerConnection.prototype.addTrack&&e.version>=65)return Yi(r);const t=r.RTCPeerConnection.prototype.getLocalStreams;r.RTCPeerConnection.prototype.getLocalStreams=function(){const c=t.apply(this);return this._reverseStreams=this._reverseStreams||{},c.map(h=>this._reverseStreams[h.id])};const i=r.RTCPeerConnection.prototype.addStream;r.RTCPeerConnection.prototype.addStream=function(c){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},c.getTracks().forEach(h=>{if(this.getSenders().find(l=>l.track===h))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[c.id]){const h=new r.MediaStream(c.getTracks());this._streams[c.id]=h,this._reverseStreams[h.id]=c,c=h}i.apply(this,[c])};const s=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(c){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.apply(this,[this._streams[c.id]||c]),delete this._reverseStreams[this._streams[c.id]?this._streams[c.id].id:c.id],delete this._streams[c.id]},r.RTCPeerConnection.prototype.addTrack=function(c,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===c))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===c))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(c),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const g=new r.MediaStream([c]);this._streams[h.id]=g,this._reverseStreams[g.id]=h,this.addStream(g)}return this.getSenders().find(g=>g.track===c)};function n(d,c){let h=c.sdp;return Object.keys(d._reverseStreams||[]).forEach(p=>{const l=d._reverseStreams[p],f=d._streams[l.id];h=h.replace(new RegExp(f.id,"g"),l.id)}),new RTCSessionDescription({type:c.type,sdp:h})}function a(d,c){let h=c.sdp;return Object.keys(d._reverseStreams||[]).forEach(p=>{const l=d._reverseStreams[p],f=d._streams[l.id];h=h.replace(new RegExp(l.id,"g"),f.id)}),new RTCSessionDescription({type:c.type,sdp:h})}["createOffer","createAnswer"].forEach(function(d){const c=r.RTCPeerConnection.prototype[d],h={[d](){const p=arguments;return arguments.length&&typeof arguments[0]=="function"?c.apply(this,[f=>{const g=n(this,f);p[0].apply(null,[g])},f=>{p[1]&&p[1].apply(null,f)},arguments[2]]):c.apply(this,arguments).then(f=>n(this,f))}};r.RTCPeerConnection.prototype[d]=h[d]});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 d=u.get.apply(this);return d.type===""?d:n(this,d)}}),r.RTCPeerConnection.prototype.removeTrack=function(c){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!c._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(c._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=>c.track===g)&&(p=this._streams[l])}),p&&(p.getTracks().length===1?this.removeStream(this._reverseStreams[p.id]):p.removeTrack(c.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Ht(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 Qi(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 es=Object.freeze(Object.defineProperty({__proto__:null,fixNegotiationNeeded:Qi,shimAddTrackRemoveTrack:Zi,shimAddTrackRemoveTrackWithNative:Yi,shimGetSendersWithDtmf:Ki,shimGetUserMedia:qi,shimMediaStream:Wi,shimOnTrack:Xi,shimPeerConnection:Ht,shimSenderReceiverGetStats:Ji},Symbol.toStringTag,{value:"Module"}));function ts(r,e){const t=r&&r.navigator,i=r&&r.MediaStreamTrack;if(t.getUserMedia=function(s,n,a){zt("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 nh(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 rs(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 qt(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(d=>{d.type=t[d.type]||d.type})}catch(d){if(d.name!=="TypeError")throw d;u.forEach((c,h)=>{u.set(h,Object.assign({},c,{type:t[c.type]||c.type}))})}return u}).then(a,o)}}function is(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 ss(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 ns(r){!r.RTCPeerConnection||"removeStream"in r.RTCPeerConnection.prototype||(r.RTCPeerConnection.prototype.removeStream=function(t){zt("removeStream","removeTrack"),this.getSenders().forEach(i=>{i.track&&t.getTracks().includes(i.track)&&this.removeTrack(i)})})}function os(r){r.DataChannel&&!r.RTCDataChannel&&(r.RTCDataChannel=r.DataChannel)}function as(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 cs(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 ds(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 us(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 hs=Object.freeze(Object.defineProperty({__proto__:null,shimAddTransceiver:as,shimCreateAnswer:us,shimCreateOffer:ds,shimGetDisplayMedia:nh,shimGetParameters:cs,shimGetUserMedia:ts,shimOnTrack:rs,shimPeerConnection:qt,shimRTCDataChannel:os,shimReceiverGetStats:ss,shimRemoveStream:ns,shimSenderGetStats:is},Symbol.toStringTag,{value:"Module"}));function ps(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 ls(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 ms(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(d,c){const h=arguments.length>=2?arguments[2]:arguments[0],p=t.apply(this,[h]);return c?(p.then(d,c),Promise.resolve()):p},e.createAnswer=function(d,c){const h=arguments.length>=2?arguments[2]:arguments[0],p=i.apply(this,[h]);return c?(p.then(d,c),Promise.resolve()):p};let o=function(u,d,c){const h=s.apply(this,[u]);return c?(h.then(d,c),Promise.resolve()):h};e.setLocalDescription=o,o=function(u,d,c){const h=n.apply(this,[u]);return c?(h.then(d,c),Promise.resolve()):h},e.setRemoteDescription=o,o=function(u,d,c){const h=a.apply(this,[u]);return c?(h.then(d,c),Promise.resolve()):h},e.addIceCandidate=o}function fs(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(_s(s))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(i,s,n){e.mediaDevices.getUserMedia(i).then(s,n)}).bind(e))}function _s(r){return r&&r.video!==void 0?Object.assign({},r,{video:zi(r.video)}):r}function gs(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?(zt("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 vs(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 Cs(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 ys(r){typeof r!="object"||r.AudioContext||(r.AudioContext=r.webkitAudioContext)}const Ss=Object.freeze(Object.defineProperty({__proto__:null,shimAudioContext:ys,shimCallbacksAPI:ms,shimConstraints:_s,shimCreateOfferLegacy:Cs,shimGetUserMedia:fs,shimLocalStreamsAPI:ps,shimRTCIceServerUrls:gs,shimRemoteStreamsAPI:ls,shimTrackEventTransceiver:vs},Symbol.toStringTag,{value:"Module"}));var Wt={exports:{}},Ts;function oh(){return Ts||(Ts=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
60
|
`).map(i=>i.trim())},e.splitSections=function(t){return t.split(`
|
|
61
61
|
m=`).map((s,n)=>(n>0?"m="+s:s).trim()+`\r
|
|
62
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
|
|
@@ -87,7 +87,7 @@ a=ice-pwd:`+t.password+`\r
|
|
|
87
87
|
o=`+(s||"thisisadapterortc")+" "+n+" "+a+` IN IP4 127.0.0.1\r
|
|
88
88
|
s=-\r
|
|
89
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}(
|
|
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}(Wt)),Wt.exports}var Es=oh();const Se=D(Es),ah=$({__proto__:null,default:Se},[Es]);function Ze(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 Xt(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 Qe(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(d=>{const c=Se.parseMLine(d);return c&&c.kind==="application"&&c.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 d=parseInt(u[1],10);return d!==d?-1:d},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 d=65536;e.browser==="firefox"&&e.version===57&&(d=65535);const c=Se.matchPrefix(o.sdp,"a=max-message-size:");return c.length>0?d=parseInt(c[0].substring(19),10):e.browser==="firefox"&&u!==-1&&(d=2147483637),d},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]),d=s(u),c=n(arguments[0],u);let h;d===0&&c===0?h=Number.POSITIVE_INFINITY:d===0||c===0?h=Math.max(d,c):h=Math.min(d,c);const p={};Object.defineProperty(p,"maxMessageSize",{get(){return h}}),this._sctp=p}return a.apply(this,arguments)}}function et(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 Kt(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 Jt(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
91
|
a=extmap-allow-mixed`)!==-1){const n=s.sdp.split(`
|
|
92
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 tt(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 rt(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 oh=Object.freeze(Object.defineProperty({__proto__:null,removeExtmapAllowMixed:Kt,shimAddIceCandidateNullOrEmpty:tt,shimConnectionState:Xt,shimMaxMessageSize:Qe,shimParameterlessSetLocalDescription:rt,shimRTCIceCandidate:Ze,shimRTCIceCandidateRelayProtocol:Wt,shimSendThrowTypeError:et},Symbol.toStringTag,{value:"Module"}));function ah({window:r}={},e={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const t=Vi,i=rh(r),s={browserDetails:i,commonShim:oh,extractVersion:Ye,disableLog:eh,disableWarnings:th,sdp:nh};switch(i.browser){case"chrome":if(!Yi||!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=Yi,tt(r,i),rt(r),zi(r,i),Gi(r),Gt(r,i),Hi(r),Ki(r,i),qi(r),Wi(r),Ji(r,i),Ze(r),Wt(r),Xt(r),Qe(r,i),et(r),Kt(r,i);break;case"firefox":if(!cs||!Ht||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),s;t("adapter.js shimming firefox."),s.browserShim=cs,tt(r,i),rt(r),Zi(r,i),Ht(r,i),Qi(r),rs(r),es(r),ts(r),is(r),ss(r),ns(r),os(r),as(r),Ze(r),Xt(r),Qe(r,i),et(r);break;case"safari":if(!vs||!e.shimSafari)return t("Safari shim is not included in this adapter release."),s;t("adapter.js shimming safari."),s.browserShim=vs,tt(r,i),rt(r),ms(r),_s(r),hs(r),ds(r),us(r),fs(r),ps(r),gs(r),Ze(r),Wt(r),Qe(r,i),et(r),Kt(r,i);break;default:t("Unsupported browser!");break}return s}ah({window:typeof window>"u"?void 0:window});class ch extends Q{static async isSupported(e){if(e==="webTransport")return Promise.resolve(Di.isSupported());try{return Wu()||!window.RTCPeerConnection||!window.RTCPeerConnection.prototype.addTransceiver||!window.RTCPeerConnection.prototype.createDataChannel?!1:await Yu()&&await Ju()}catch{return!1}}constructor(e){super(),this._streamManagerController=new mu,this._streamComposeController=new bu(this._streamManagerController),this._streamConsumeController=new qu(this._streamComposeController),this._streamConsumeController.setPushConfig(e),this._observer=Qu,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":$e.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()}),io(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 ch});
|
|
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 tt(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 rt(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 ch=Object.freeze(Object.defineProperty({__proto__:null,removeExtmapAllowMixed:Jt,shimAddIceCandidateNullOrEmpty:tt,shimConnectionState:Kt,shimMaxMessageSize:Qe,shimParameterlessSetLocalDescription:rt,shimRTCIceCandidate:Ze,shimRTCIceCandidateRelayProtocol:Xt,shimSendThrowTypeError:et},Symbol.toStringTag,{value:"Module"}));function dh({window:r}={},e={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const t=Bi,i=sh(r),s={browserDetails:i,commonShim:ch,extractVersion:Ye,disableLog:rh,disableWarnings:ih,sdp:ah};switch(i.browser){case"chrome":if(!es||!Ht||!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=es,tt(r,i),rt(r),qi(r,i),Wi(r),Ht(r,i),Xi(r),Zi(r,i),Ki(r),Ji(r),Qi(r,i),Ze(r),Xt(r),Kt(r),Qe(r,i),et(r),Jt(r,i);break;case"firefox":if(!hs||!qt||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),s;t("adapter.js shimming firefox."),s.browserShim=hs,tt(r,i),rt(r),ts(r,i),qt(r,i),rs(r),ns(r),is(r),ss(r),os(r),as(r),cs(r),ds(r),us(r),Ze(r),Kt(r),Qe(r,i),et(r);break;case"safari":if(!Ss||!e.shimSafari)return t("Safari shim is not included in this adapter release."),s;t("adapter.js shimming safari."),s.browserShim=Ss,tt(r,i),rt(r),gs(r),Cs(r),ms(r),ps(r),ls(r),vs(r),fs(r),ys(r),Ze(r),Xt(r),Qe(r,i),et(r),Jt(r,i);break;default:t("Unsupported browser!");break}return s}dh({window:typeof window>"u"?void 0:window});class uh extends Q{static async isSupported(e){if(e==="webTransport")return Promise.resolve(Fi.isSupported());try{return Ku()||!window.RTCPeerConnection||!window.RTCPeerConnection.prototype.addTransceiver||!window.RTCPeerConnection.prototype.createDataChannel?!1:await Qu()&&await Zu()}catch{return!1}}constructor(e){super(),this._streamManagerController=new _u,this._streamComposeController=new Pu(this._streamManagerController),this._streamConsumeController=new Xu(this._streamComposeController),this._streamConsumeController.setPushConfig(e),this._observer=th,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":$e.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(or[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()}),no(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 uh});
|