trtc-sdk-v5 5.11.2-beta.6 → 5.11.2-wasm.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/assets/av_processing.wasm +0 -0
- package/assets/worker.js +17 -0
- package/package.json +4 -6
- package/plugins/cdn-streaming/cdn-streaming.esm.js +1 -1
- package/plugins/cdn-streaming/cdn-streaming.umd.js +1 -1
- package/plugins/cdn-streaming/package.json +1 -1
- package/plugins/cross-room/cross-room.esm.js +1 -1
- package/plugins/cross-room/cross-room.umd.js +1 -1
- package/plugins/cross-room/package.json +1 -1
- package/plugins/custom-encryption/custom-encryption.esm.js +1 -1
- package/plugins/custom-encryption/custom-encryption.umd.js +1 -1
- package/plugins/custom-encryption/package.json +1 -1
- package/plugins/device-detector/device-detector.esm.js +36 -24
- package/plugins/device-detector/device-detector.umd.js +21 -7
- package/plugins/device-detector/package.json +1 -1
- package/plugins/small-stream-auto-switcher/package.json +1 -1
- package/plugins/small-stream-auto-switcher/small-stream-auto-switcher.esm.js +1 -1
- package/plugins/small-stream-auto-switcher/small-stream-auto-switcher.umd.js +1 -1
- package/plugins/video-decoder/package.json +1 -1
- package/plugins/video-decoder/video-decoder.esm.js +1 -1
- package/plugins/video-decoder/video-decoder.umd.js +1 -1
- package/plugins/video-effect/basic-beauty/basic-beauty.esm.js +1 -1
- package/plugins/video-effect/basic-beauty/basic-beauty.umd.js +1 -1
- package/plugins/video-effect/basic-beauty/package.json +1 -1
- package/plugins/video-effect/beauty/beauty.esm.js +1 -1
- package/plugins/video-effect/beauty/beauty.umd.js +1 -1
- package/plugins/video-effect/beauty/package.json +1 -1
- package/plugins/video-effect/video-mixer/package.json +1 -1
- package/plugins/video-effect/video-mixer/video-mixer.esm.js +1 -1
- package/plugins/video-effect/video-mixer/video-mixer.umd.js +1 -1
- package/plugins/video-effect/virtual-background/package.json +1 -1
- package/plugins/video-effect/virtual-background/virtual-background.esm.js +1 -1
- package/plugins/video-effect/virtual-background/virtual-background.umd.js +1 -1
- package/plugins/video-effect/watermark/package.json +1 -1
- package/plugins/video-effect/watermark/watermark.esm.js +1 -1
- package/plugins/video-effect/watermark/watermark.umd.js +1 -1
- package/plugins/voice-changer/package.json +1 -1
- package/plugins/voice-changer/voice-changer.esm.js +1 -1
- package/plugins/voice-changer/voice-changer.umd.js +1 -1
- package/trtc.esm.js +64 -43
- package/trtc.js +1 -1
|
Binary file
|
package/assets/worker.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
var bu=Object.create;var nr=Object.defineProperty;var Fs=Object.getOwnPropertyDescriptor;var gu=Object.getOwnPropertyNames,Vs=Object.getOwnPropertySymbols,Eu=Object.getPrototypeOf,Hs=Object.prototype.hasOwnProperty,Tu=Object.prototype.propertyIsEnumerable;var Zr=(n,t,e)=>t in n?nr(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,en=(n,t)=>{for(var e in t||(t={}))Hs.call(t,e)&&Zr(n,e,t[e]);if(Vs)for(var e of Vs(t))Tu.call(t,e)&&Zr(n,e,t[e]);return n};var Su=(n,t)=>()=>(t||n((t={exports:{}}).exports,t),t.exports);var Iu=(n,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of gu(t))!Hs.call(n,i)&&i!==e&&nr(n,i,{get:()=>t[i],enumerable:!(r=Fs(t,i))||r.enumerable});return n};var sr=(n,t,e)=>(e=n!=null?bu(Eu(n)):{},Iu(t||!n||!n.__esModule?nr(e,"default",{value:n,enumerable:!0}):e,n));var ce=(n,t,e,r)=>{for(var i=r>1?void 0:r?Fs(t,e):t,a=n.length-1,c;a>=0;a--)(c=n[a])&&(i=(r?c(t,e,i):c(i))||i);return r&&i&&nr(t,e,i),i};var l=(n,t,e)=>Zr(n,typeof t!="symbol"?t+"":t,e);var Mt=Su((Nm,$n)=>{"use strict";var Lu=Object.prototype.hasOwnProperty,me="~";function wt(){}Object.create&&(wt.prototype=Object.create(null),new wt().__proto__||(me=!1));function ku(n,t,e){this.fn=n,this.context=t,this.once=e||!1}function oi(n,t,e,r,i){if(typeof e!="function")throw new TypeError("The listener must be a function");var a=new ku(e,r||n,i),c=me?me+t:t;return n._events[c]?n._events[c].fn?n._events[c]=[n._events[c],a]:n._events[c].push(a):(n._events[c]=a,n._eventsCount++),n}function Rr(n,t){--n._eventsCount===0?n._events=new wt:delete n._events[t]}function ae(){this._events=new wt,this._eventsCount=0}ae.prototype.eventNames=function(){var t=[],e,r;if(this._eventsCount===0)return t;for(r in e=this._events)Lu.call(e,r)&&t.push(me?r.slice(1):r);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(e)):t};ae.prototype.listeners=function(t){var e=me?me+t:t,r=this._events[e];if(!r)return[];if(r.fn)return[r.fn];for(var i=0,a=r.length,c=new Array(a);i<a;i++)c[i]=r[i].fn;return c};ae.prototype.listenerCount=function(t){var e=me?me+t:t,r=this._events[e];return r?r.fn?1:r.length:0};ae.prototype.emit=function(t,e,r,i,a,c){var _=me?me+t:t;if(!this._events[_])return!1;var m=this._events[_],d=arguments.length,f,h;if(m.fn){switch(m.once&&this.removeListener(t,m.fn,void 0,!0),d){case 1:return m.fn.call(m.context),!0;case 2:return m.fn.call(m.context,e),!0;case 3:return m.fn.call(m.context,e,r),!0;case 4:return m.fn.call(m.context,e,r,i),!0;case 5:return m.fn.call(m.context,e,r,i,a),!0;case 6:return m.fn.call(m.context,e,r,i,a,c),!0}for(h=1,f=new Array(d-1);h<d;h++)f[h-1]=arguments[h];m.fn.apply(m.context,f)}else{var R=m.length,U;for(h=0;h<R;h++)switch(m[h].once&&this.removeListener(t,m[h].fn,void 0,!0),d){case 1:m[h].fn.call(m[h].context);break;case 2:m[h].fn.call(m[h].context,e);break;case 3:m[h].fn.call(m[h].context,e,r);break;case 4:m[h].fn.call(m[h].context,e,r,i);break;default:if(!f)for(U=1,f=new Array(d-1);U<d;U++)f[U-1]=arguments[U];m[h].fn.apply(m[h].context,f)}}return!0};ae.prototype.on=function(t,e,r){return oi(this,t,e,r,!1)};ae.prototype.once=function(t,e,r){return oi(this,t,e,r,!0)};ae.prototype.removeListener=function(t,e,r,i){var a=me?me+t:t;if(!this._events[a])return this;if(!e)return Rr(this,a),this;var c=this._events[a];if(c.fn)c.fn===e&&(!i||c.once)&&(!r||c.context===r)&&Rr(this,a);else{for(var _=0,m=[],d=c.length;_<d;_++)(c[_].fn!==e||i&&!c[_].once||r&&c[_].context!==r)&&m.push(c[_]);m.length?this._events[a]=m.length===1?m[0]:m:Rr(this,a)}return this};ae.prototype.removeAllListeners=function(t){var e;return t?(e=me?me+t:t,this._events[e]&&Rr(this,e)):(this._events=new wt,this._eventsCount=0),this};ae.prototype.off=ae.prototype.removeListener;ae.prototype.addListener=ae.prototype.on;ae.prefixed=me;ae.EventEmitter=ae;typeof $n!="undefined"&&($n.exports=ae)});function G(...n){}var Ru=n=>n();function rn(){this.dispose()}var Au=()=>typeof __FASTRX_DEVTOOLS__!="undefined",yu=1,Ne=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(t){let e=new tn(t,this,this.streamId++);return ee.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},ct=class{constructor(){this.defers=new Set,this.disposed=!1}next(t){}complete(){this.dispose()}error(t){this.dispose()}get bindDispose(){return()=>this.dispose()}dispose(){this.disposed=!0,this.complete=G,this.error=G,this.next=G,this.dispose=G,this.subscribe=G,this.doDefer()}subscribe(t){return t instanceof Ne?t.subscribe(this):t(this),this}get bindSubscribe(){return t=>this.subscribe(t)}doDefer(){this.defers.forEach(Ru),this.defers.clear()}defer(t){this.defers.add(t)}removeDefer(t){this.defers.delete(t)}reset(){this.disposed=!1,delete this.complete,delete this.next,delete this.dispose,delete this.next,delete this.subscribe}resetNext(){delete this.next}resetComplete(){delete this.complete}resetError(){delete this.error}},N=class extends ct{constructor(t){super(),this.sink=t,t.defer(this.bindDispose)}next(t){this.sink.next(t)}complete(){this.sink.complete()}error(t){this.sink.error(t)}},ir=class extends ct{constructor(t,e=G,r=G,i=G){if(super(),this._next=e,this._error=r,this._complete=i,this.then=G,t instanceof Ne){let a={toString:()=>"subscribe",id:0,source:t};this.defer(()=>{ee.defer(a,0)}),ee.create(a),ee.pipe(a),this.sourceId=a.id,this.subscribe(t),ee.subscribe({id:a.id,end:!0}),e==G?this._next=c=>ee.next(a,0,c):this.next=c=>{ee.next(a,0,c),e(c)},i==G?this._complete=()=>ee.complete(a,0):this.complete=()=>{this.dispose(),ee.complete(a,0),i()},r==G?this._error=c=>ee.complete(a,0,c):this.error=c=>{this.dispose(),ee.complete(a,0,c),r()}}else this.subscribe(t)}next(t){this._next(t)}complete(){this.dispose(),this._complete()}error(t){this.dispose(),this._error(t)}};function V(n,...t){return t.reduce((e,r)=>r(e),n)}function le(n,t,e){if(Au()){let r=Object.defineProperties(Object.setPrototypeOf(n,Ne.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:t,writable:!0,configurable:!0},args:{value:e,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});ee.create(r);for(let i=0;i<e.length;i++){let a=e[i];typeof a=="function"&&a instanceof Ne&&ee.addSource(r,a)}return r}return n}function w(n,t){return function(...e){return r=>{if(r instanceof Ne){let i=le(a=>{let c=new n(a,...e);c.sourceId=i.id,c.subscribe(r)},t,arguments);return i.source=r,ee.pipe(i),i}else return i=>r(new n(i,...e))}}}function He(n,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:n,payload:t}})}var tn=class extends N{constructor(t,e,r){super(t),this.source=e,this.id=r,this.sourceId=t.sourceId,this.defer(()=>{ee.defer(this.source,this.id)})}next(t){ee.next(this.source,this.id,t),this.sink.next(t)}complete(){ee.complete(this.source,this.id),this.sink.complete()}error(t){ee.complete(this.source,this.id,t),this.sink.error(t)}},ee={addSource(n,t){He("addSource",{id:n.id,name:n.toString(),source:{id:t.id,name:t.toString()}})},next(n,t,e){He("next",{id:n.id,streamId:t,data:e&&e.toString()})},subscribe({id:n,end:t},e){He("subscribe",{id:n,end:t,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(n,t,e){He("complete",{id:n.id,streamId:t,err:e?e.toString():null})},defer(n,t){He("defer",{id:n.id,streamId:t})},pipe(n){He("pipe",{name:n.toString(),id:n.id,source:{id:n.source.id,name:n.source.toString()}})},update(n){He("update",{id:n.id,name:n.toString()})},create(n){n.id||(n.id=yu++),He("create",{name:n.toString(),id:n.id})}},or=class extends Error{constructor(t){super(`timeout after ${t}ms`),this.timeout=t}};var nn=class extends ct{constructor(t){super(),this.source=t,this.sinks=new Set}add(t){t.defer(()=>this.remove(t)),this.sinks.add(t).size===1&&(this.reset(),this.subscribe(this.source))}remove(t){this.sinks.delete(t),this.sinks.size===0&&this.dispose()}next(t){this.sinks.forEach(e=>e.next(t))}complete(){this.sinks.forEach(t=>t.complete()),this.sinks.clear()}error(t){this.sinks.forEach(e=>e.error(t)),this.sinks.clear()}};function qe(){return n=>{let t=new nn(n);if(n instanceof Ne){let e=le(r=>{t.add(r)},"share",arguments);return t.sourceId=e.id,e.source=n,ee.pipe(e),e}return le(t.add.bind(t),"share",arguments)}}function qs(...n){return le(t=>{let e=new N(t),r=n.length;e.complete=()=>{--r===0&&t.complete()},n.forEach(e.bindSubscribe)},"merge",arguments)}function Ou(...n){return le(t=>{let e=n.length,r=e,i=e,a=new Array(e),c=()=>{--i===0&&t.complete()},_=(m,d)=>{let f=new N(t);f.next=h=>{--r===0?(f.next=R=>{a[d]=R,t.next(a)},f.next(h)):a[d]=h},f.complete=c,f.subscribe(m)};n.forEach(_)},"combineLatest",arguments)}function Ws(...n){return le(t=>{let e=n.length,r=e,i=new Array(e),a=()=>{--r===0&&t.complete()},c=(_,m)=>{let d=new N(t),f=[];i[m]=f,d.next=h=>{f.push(h),i.every(R=>R.length)&&t.next(i.map(R=>R.shift()))},d.complete=a,d.subscribe(_)};n.forEach(c)},"zip",arguments)}var sn=class extends N{constructor(t,...e){super(t);let r=new N(this.sink);r.next=i=>this.buffer=i,r.complete=G,r.subscribe(Ou(...e))}next(t){this.buffer&&this.sink.next([t,...this.buffer])}},$c=w(sn,"withLatestFrom"),on=class extends N{constructor(t,e,r){super(t),this.bufferSize=e,this.startBufferEvery=r,this.buffer=[],this.count=0,this.startBufferEvery&&(this.buffers=[[]])}next(t){this.startBufferEvery?(this.count++===this.startBufferEvery&&(this.buffers.push([]),this.count=1),this.buffers.forEach(e=>{e.push(t)}),this.buffers[0].length===this.bufferSize&&this.sink.next(this.buffers.shift())):(this.buffer.push(t),this.buffer.length===this.bufferSize&&(this.sink.next(this.buffer),this.buffer=[]))}complete(){this.buffer.length?this.sink.next(this.buffer):this.buffers.length&&this.buffers.forEach(t=>this.sink.next(t)),super.complete()}},Yc=w(on,"bufferCount"),an=class extends N{constructor(t,e){super(t),this.buffer=[];let r=new N(t);r.next=i=>{t.next(this.buffer),this.buffer=[]},r.complete=G,r.subscribe(e)}next(t){this.buffer.push(t)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},Kc=w(an,"buffer");function Qe(n){let t=arguments,e=qe()(le(r=>{e.next=i=>r.next(i),e.complete=()=>r.complete(),e.error=i=>r.error(i),n&&r.subscribe(n)},"subject",t));return e.next=G,e.complete=G,e.error=G,e}function lt(n){return le(t=>{let e=0,r=setInterval(()=>t.next(e++),n);return t.defer(()=>{clearInterval(r)}),"interval"},"interval",arguments)}function Gs(n,t){return le(e=>{let r=0,i=setTimeout(()=>{if(e.removeDefer(a),e.next(r++),t){let c=setInterval(()=>e.next(r++),t);e.defer(()=>{clearInterval(c)})}else e.complete()},n),a=()=>{clearTimeout(i)};e.defer(a)},"timer",arguments)}function un(n,t){return e=>{let r=i=>e.next(i);e.defer(()=>t(r)),n(r)}}function Ee(n,t){if("on"in n&&"off"in n)return le(un(e=>n.on(t,e),e=>n.off(t,e)),"fromEvent",arguments);if("addListener"in n&&"removeListener"in n)return le(un(e=>n.addListener(t,e),e=>n.removeListener(t,e)),"fromEvent",arguments);if("addEventListener"in n)return le(un(e=>n.addEventListener(t,e),e=>n.removeEventListener(t,e)),"fromEvent",arguments);throw"target is not a EventDispachter"}var cn=class extends N{constructor(t,e,r){super(t),this.f=e;let i=()=>{this.sink.next(this.acc),this.sink.complete()};typeof r=="undefined"?this.next=a=>{this.acc=a,this.complete=i,this.resetNext()}:(this.acc=r,this.complete=i)}next(t){this.acc=this.f(this.acc,t)}},vu=w(cn,"reduce");var ln=class extends N{constructor(t,e,r){super(t),this.filter=e,this.thisArg=r}next(t){this.filter.call(this.thisArg,t)&&this.sink.next(t)}},mt=w(ln,"filter"),mn=class extends N{next(t){}},sl=w(mn,"ignoreElements"),dn=class extends N{constructor(t,e){super(t),this.count=e}next(t){this.sink.next(t),--this.count===0&&this.complete()}},ur=w(dn,"take"),pn=class extends N{constructor(t,e){super(t);let r=new N(t);r.next=()=>t.complete(),r.complete=rn,r.subscribe(e)}},ye=w(pn,"takeUntil"),_n=class extends N{constructor(t,e){super(t),this.f=e}next(t){this.f(t)?this.sink.next(t):this.complete()}},On=w(_n,"takeWhile");var fn=class extends N{constructor(t,e){super(t),this.count=e}next(t){--this.count===0&&(this.next=super.next)}},il=w(fn,"skip"),hn=class extends N{constructor(t,e){super(t),t.next=G;let r=new N(t);r.next=()=>{r.dispose(),t.resetNext()},r.complete=rn,r.subscribe(e)}},ol=w(hn,"skipUntil"),bn=class extends N{constructor(t,e){super(t),this.f=e}next(t){this.f(t)||(this.next=super.next,this.next(t))}},js=w(bn,"skipWhile"),Uu={leading:!0,trailing:!1},gn=class extends N{constructor(t,e,r){super(t),this.durationSelector=e,this.trailing=r}cacheValue(t){this.last=t,this.disposed&&this.throttle(t)}send(t){this.sink.next(t),this.throttle(t)}throttle(t){this.reset(),this.subscribe(this.durationSelector(t))}next(){this.complete()}complete(){this.dispose(),this.trailing&&this.send(this.last)}},En=class extends N{constructor(t,e,r=Uu){super(t),this.durationSelector=e,this.config=r,this._throttle=new gn(this.sink,this.durationSelector,this.config.trailing),this._throttle.dispose()}next(t){this._throttle.disposed&&this.config.leading?this._throttle.send(t):this._throttle.cacheValue(t)}complete(){this._throttle.throttle=G,this._throttle.complete(),super.complete()}},$s=w(En,"throttle");var Tn=class extends N{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},ar=class extends N{constructor(t,e){super(t),this.durationSelector=e,this._debounce=new Tn(this.sink),this._debounce.dispose()}next(t){this._debounce.dispose(),this._debounce.reset(),this._debounce.last=t,this._debounce.subscribe(this.durationSelector(t))}complete(){this._debounce.complete(),super.complete()}},Ys=w(ar,"debounce"),Ks=n=>w(ar,"debounceTime")(t=>Gs(n)),Sn=class extends N{constructor(t,e,r){super(t),this.count=e,this.defaultValue=r}next(t){this.count--===0&&(this.defaultValue=t,this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("not enough elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},al=w(Sn,"elementAt");var In=class extends N{constructor(t,e){super(t),this.f=e,this.i=0}next(t){this.f(t)?(this.sink.next(this.i++),this.complete()):++this.i}},ul=w(In,"findIndex"),Rn=class extends N{constructor(t,e,r){super(t),this.f=e,this.defaultValue=r,this.index=0}next(t){(!this.f||this.f(t,this.index++))&&(this.defaultValue=t,this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},cl=w(Rn,"first"),An=class extends N{constructor(t,e,r){super(t),this.f=e,this.defaultValue=r,this.index=0}next(t){(!this.f||this.f(t,this.index++))&&(this.defaultValue=t)}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},ll=w(An,"last"),yn=class extends N{constructor(t,e){super(t),this.predicate=e,this.index=0}next(t){this.predicate(t,this.index++)?this.result=!0:(this.result=!1,this.complete())}complete(){if(this.result===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.result);super.complete()}},ml=w(yn,"every");var vn=class extends N{constructor(t,e,r){super(t),this.f=e,typeof r=="undefined"?this.next=i=>{this.acc=i,this.resetNext(),this.sink.next(this.acc)}:this.acc=r}next(t){this.sink.next(this.acc=this.f(this.acc,t))}},fl=w(vn,"scan"),Un=class extends N{constructor(){super(...arguments),this.hasLast=!1}next(t){this.hasLast?this.sink.next([this.last,t]):this.hasLast=!0,this.last=t}},hl=w(Un,"pairwise"),cr=class extends N{constructor(t,e,r){super(t),this.mapper=e,this.thisArg=r}next(t){super.next(this.mapper.call(this.thisArg,t))}},ze=w(cr,"map"),kn=n=>w(cr,"mapTo")(t=>n),dt=class extends N{constructor(t,e,r){super(t),this.data=e,this.context=r}next(t){let e=this.context.combineResults;e?this.sink.next(e(this.data,t)):this.sink.next(t)}tryComplete(){this.context.resetComplete(),this.dispose()}},pt=class extends N{constructor(t,e,r){super(t),this.makeSource=e,this.combineResults=r,this.index=0}subInner(t,e){let r=this.currentSink=new e(this.sink,t,this);this.complete=this.tryComplete,r.complete=r.tryComplete,r.subscribe(this.makeSource(t,this.index++))}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},lr=class extends dt{},mr=class extends pt{next(t){this.subInner(t,lr),this.next=e=>{this.currentSink.dispose(),this.subInner(e,lr)}}},Bn=w(mr,"switchMap");function fr(n){return(t,e)=>n(()=>t,e)}var Pt=fr(w(mr,"switchMapTo")),xn=class extends dt{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},dr=class extends pt{constructor(){super(...arguments),this.sources=[],this.next2=this.sources.push.bind(this.sources)}next(t){this.next2(t),this.subNext()}subNext(){this.next=this.next2,this.subInner(this.sources.shift(),xn),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},bl=w(dr,"concatMap"),gl=fr(w(dr,"concatMapTo")),Pn=class extends dt{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},pr=class extends pt{constructor(){super(...arguments),this.inners=new Set}next(t){this.subInner(t,Pn),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(t=>t.resetComplete()):this.dispose()}},El=w(pr,"mergeMap"),Tl=fr(w(pr,"mergeMapTo")),Nn=class extends dt{dispose(){this.context.resetNext(),super.dispose()}},_r=class extends pt{next(t){this.next=G,this.subInner(t,Nn)}},Sl=w(_r,"exhaustMap"),Il=fr(w(_r,"exhaustMapTo")),Dn=class extends N{constructor(t,e){super(t),this.f=e,this.groups=new Map}next(t){let e=this.f(t),r=this.groups.get(e);typeof r=="undefined"&&(r=Qe(),r.key=e,this.groups.set(e,r),super.next(r)),r.next(t)}complete(){this.groups.forEach(t=>t.complete()),super.complete()}error(t){this.groups.forEach(e=>e.error(t)),super.error(t)}},Rl=w(Dn,"groupBy"),Cn=class extends N{constructor(){super(...arguments),this.start=new Date}next(t){this.sink.next({value:t,interval:Number(new Date)-Number(this.start)}),this.start=new Date}},Al=w(Cn,"timeInterval"),wn=class extends N{constructor(t,e){super(t),this.miniseconds=e,this.buffer=[],this.id=setInterval(()=>{this.sink.next(this.buffer.concat()),this.buffer.length=0},this.miniseconds)}next(t){this.buffer.push(t)}complete(){this.sink.next(this.buffer),super.complete()}dispose(){clearInterval(this.id),super.dispose()}},yl=w(wn,"bufferTime"),Mn=class extends N{constructor(t,e){super(t),this.buffer=[],this.delayTime=e}dispose(){clearTimeout(this.timeoutId),super.dispose()}delay(t){this.timeoutId=setTimeout(()=>{let e=this.buffer.shift();if(e){let{time:r,data:i}=e;super.next(i),this.buffer.length&&this.delay(Number(this.buffer[0].time)-Number(r))}},t)}next(t){this.buffer.length||this.delay(this.delayTime),this.buffer.push({time:new Date,data:t})}complete(){this.timeoutId=setTimeout(()=>super.complete(),this.delayTime)}},Ol=w(Mn,"delay"),Ln=class extends N{constructor(t,e){super(t),this.selector=e}error(t){this.dispose(),this.selector(t)(this.sink)}},vl=w(Ln,"catchError");var X=(n=G,t=G,e=G)=>r=>new ir(r,n,t,e),Vn=class extends N{constructor(t,e){super(t),e instanceof Function?this.next=r=>{e(r),t.next(r)}:(e.next&&(this.next=r=>{e.next(r),t.next(r)}),e.complete&&(this.complete=()=>{e.complete(),t.complete()}),e.error&&(this.error=r=>{e.error(r),t.error(r)}))}},hr=w(Vn,"tap"),Fn=class extends N{constructor(t,e){super(t),this.timeout=e,this.id=setTimeout(()=>this.error(new or(this.timeout)),this.timeout)}next(t){super.next(t),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},Pl=w(Fn,"timeout");var Ze="5.0.0";var Js=typeof importScripts!="undefined",br=typeof registerProcessor!="undefined";var Hn="";var xu="web.sdk.qcloud.com";var Pu=`https://${xu}/trtc/webrtc/v5/doc`,Fl=`${Pu}/zh-cn/`,Xs="https://yun.tim.qq.com",Qs="https://apisgp.my-imcloud.com";var zs={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"};var Le=(c=>(c[c.TRACE=0]="TRACE",c[c.DEBUG=1]="DEBUG",c[c.INFO=2]="INFO",c[c.WARN=3]="WARN",c[c.ERROR=4]="ERROR",c[c.NONE=5]="NONE",c))(Le||{}),Zs=18e3;var Hl=7*24*3600*1e3;var ei={"120p":{width:160,height:120,frameRate:15,bitrate:200},"120p_2":{width:160,height:120,frameRate:15,bitrate:100},"180p":{width:320,height:180,frameRate:15,bitrate:350},"180p_2":{width:320,height:180,frameRate:15,bitrate:150},"240p":{width:320,height:240,frameRate:15,bitrate:400},"240p_2":{width:320,height:240,frameRate:15,bitrate:200},"360p":{width:640,height:360,frameRate:15,bitrate:800},"360p_2":{width:640,height:360,frameRate:15,bitrate:400},"480p":{width:640,height:480,frameRate:15,bitrate:900},"480p_2":{width:640,height:480,frameRate:15,bitrate:500},"720p":{width:1280,height:720,frameRate:15,bitrate:1500},"1080p":{width:1920,height:1080,frameRate:15,bitrate:2e3},"1440p":{width:2560,height:1440,frameRate:30,bitrate:4860},"4K":{width:3840,height:2160,frameRate:30,bitrate:9e3}},ql=ei["480p_2"],Wl=ei["120p_2"];var Nt={CANVAS:"canvas",AUDIO:"audio",VIDEO:"video",SCREEN:"screen",SMALL:"small",BIG:"big",AUXILIARY:"auxiliary",SMALL_VIDEO:"smallVideo",FACING_MODE_USER:"user",FACING_MODE_ENVIRONMENT:"environment",MUTE:"mute",UNMUTE:"unmute",ENDED:"ended",PLAYING:"playing",PAUSE:"pause",ERROR:"error",LOADEDDATA:"loadeddata",LOADEDMETADATA:"loadedmetadata",AUDIO_INPUT:"audioinput",VIDEO_INPUT:"videoinput",DETAIL:"detail",TEXT:"text",MAIN:"main",BACKUP:"backup",BANNED:"banned",KICK:"kick",USER_TIME_OUT:"user_time_out",ROOM_DISBAND:"room_disband",SEI_MESSAGE:"sei-message",ADD:"add",REMOVE:"remove",REPLACE:"replace",TRACK:"track",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",TRANSCEIVER_DIRECTION_SENDONLY:"sendonly",TRANSCEIVER_DIRECTION_RECVONLY:"recvonly",ENTER_PICTURE_IN_PICTURE:"enterpictureinpicture",LEAVE_PICTURE_IN_PICTURE:"leavepictureinpicture"};var _t=1,gr=2,Er=4,ft=8,ht=64,bt=16;var Gl=Nt.MAIN,jl=Nt.AUXILIARY;var ti=30;var $l=Nt.BIG,Yl=Nt.SMALL,Kl=10*1e3;var Jl=Object.keys(Le),ri=["normal leave","timeout leave","kick","role change"];var Xl=10*1e3;var Du=n=>Number(n)<14e8,ni=function(n,t){let e;Hn?e=Hn:e=Du(n)?Qs:Xs;let r=Math.floor(Math.random()*2**31);return`${e}/v5/AVQualityReportSvc/C2S?random=${r}&sdkappid=${n}&cmdtype=${t}`};var am=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{};var Tr=n=>typeof n=="undefined",qn=n=>typeof n=="string",si=n=>typeof n=="number";var{toString:um}=Object.prototype;function Wn(n,t){return{userId:t,hasAudio:!!(n&ft),hasVideo:!!(n&_t),hasAuxiliary:!!(n&Er),hasSmall:!!(n&gr),audioMuted:!!(n&ht),videoMuted:!!(n&bt),audioAvailable:!!(n&ft)&&!(n&ht),videoAvailable:!!(n&_t)&&!(n&bt)}}function Dt(n,t=!1){let e=Object.defineProperties(Qe(),{postMessage:{value:n.postMessage.bind(n)},port:{get(){return n},set(i){n.onmessage=G,n.onmessageerror=G,n=i,r()}}});function r(){n.onmessage=i=>{i.data?i.ports.length||t?e.next(i):e.next(i.data):(e.complete(),n.close())},n.onmessageerror=i=>{e.error(i),n.close()}}return r(),e}var Gn=class extends N{constructor(t,e){super(t);let r=new N(t);r.next=G,e(r)}},ke=w(Gn,"takeUntilComplete");var re={useWt:!0,useAINS:!0,useHardDecoder:"prefer-software",useHardEncoder:"prefer-software",unreliable:!1,debug:!1,assetsPath:"",enableUpload:!0},Cu="__INLINE__WORKER__",wu="__INLINE__WASM__",{debug:Sr}=console;re.debug||(console.debug=()=>{});var Tm=!Cu.startsWith("__"),Sm=!wu.startsWith("__");var ii=V(lt(250),ze(()=>performance.now()),qe()),Oe=n=>t=>{let e=0,r=performance.now();V(ii,ze(i=>(i-r)/n>>0),mt(i=>i!=e?(e=i,!0):!1))(t)},We=n=>t=>{let e=performance.now();V(ii,js(r=>r-e<n),ur(1))(t)};function Ge(n,t,e){let r=t.aborted?Promise.reject(t.reason):new Promise((i,a)=>{t.addEventListener("abort",()=>a(t.reason),{once:!0}),typeof n=="function"?n(i,a):n.then(i,a)});return e?r.catch(e):r}var Mu=new Intl.DateTimeFormat("zh-CN",{dateStyle:"short",timeStyle:"medium"}),et=()=>Mu.format(new Date),se=(A=>(A[A.JOIN_ROOM=0]="JOIN_ROOM",A[A.LEAVE_ROOM=1]="LEAVE_ROOM",A[A.PUBLISH=2]="PUBLISH",A[A.UNPUBLISH=3]="UNPUBLISH",A[A.SUBSCRIBE=4]="SUBSCRIBE",A[A.UNSUBSCRIBE=5]="UNSUBSCRIBE",A[A.GET_WHOLE_LIST=6]="GET_WHOLE_LIST",A[A.QUALITY_REPORT=7]="QUALITY_REPORT",A[A.MUTE=8]="MUTE",A[A.UNMUTE=9]="UNMUTE",A[A.CONFIG=10]="CONFIG",A[A.REQUEST_PLI=11]="REQUEST_PLI",A[A.HEARTBEAT=12]="HEARTBEAT",A[A.START_PUSH_CDN=13]="START_PUSH_CDN",A[A.STOP_PUSH_CDN=14]="STOP_PUSH_CDN",A[A.START_MCU_MIX=15]="START_MCU_MIX",A[A.STOP_MCU_MIX=16]="STOP_MCU_MIX",A[A.UDPATE_TRACK=17]="UDPATE_TRACK",A[A.START_PUSHING=18]="START_PUSHING",A[A.STOP_PUSHING=19]="STOP_PUSHING",A[A.SWITCH_ROLE=20]="SWITCH_ROLE",A[A.WHOLE_LIST_UPDATE=255]="WHOLE_LIST_UPDATE",A[A.PEER_JOINED=256]="PEER_JOINED",A[A.PEER_LEFT=257]="PEER_LEFT",A[A.PEER_UDPATED_TRACK=258]="PEER_UDPATED_TRACK",A[A.SELECT_ABILITY=259]="SELECT_ABILITY",A[A.PEER_REQUEST_PLI=260]="PEER_REQUEST_PLI",A[A.AUDIO_DATA=4095]="AUDIO_DATA",A[A.VIDEO_DATA=4096]="VIDEO_DATA",A[A.SCREEN_DATA=4097]="SCREEN_DATA",A[A.NACK=4098]="NACK",A[A.ACK=4099]="ACK",A[A.REQUEST_RTT=4100]="REQUEST_RTT",A[A.RESPONSE_RTT=4101]="RESPONSE_RTT",A[A.PIP_DATA=4102]="PIP_DATA",A[A.LAYER_DATA=4103]="LAYER_DATA",A[A.MAX_FORCE=65535]="MAX_FORCE",A))(se||{});function jn(n,t,e){let r=t>65535?1:0;return e.setUint8(0,0<<4|r),e.setUint16(1,n),r?e.setUint32(3,t):e.setUint16(3,t),r?7:5}function Ct(n,t){let e=n>=255&&n<4095;e&&(t+=4);let i=(t>65535?1:0)?7:5,a=new DataView(new ArrayBuffer(i+t));jn(n,t,a),e&&(a.setUint32(i,0),i+=4),a=new DataView(a.buffer,i),i=0;let c=R=>{a.setUint8(i,R),i++},_=R=>{a.setUint16(i,R),i+=2},m=(R,U=!1)=>{a.setUint32(i,R,U),i+=4},d=R=>{a.setBigUint64(i,R),i+=8},f=R=>{let U=new Uint8Array(a.buffer,a.byteOffset+i,R);return i+=R,U};return{write8:c,write32:m,write16:_,write64:d,writeData:R=>f(R.length).set(R),dv:a,next:f}}function Ir(n,t,e){let r=JSON.stringify(t),{writeData:i,dv:a}=Ct(n,r.length+16);switch(i(e.split("").map(c=>c.charCodeAt(0))),i(r.split("").map(c=>c.charCodeAt(0))),n){case 11:case 12:case 7:console.debug("send",se[n],e,t,a.buffer);break;default:n<255&&console.log(et(),"send",se[n],e,t,a.buffer)}return a.buffer}var ai=sr(Mt()),he=class extends ai.EventEmitter{constructor(e){super();this.io=e}get statReportReq(){return this.io.statReportReq.stat}get qualityReport(){return this.io.qualityReportReq.report}get appId(){return this.io.joinReq.sdkAppID}get roomId(){return this.io.joinReq.roomid}get userId(){return this.io.joinRes.openid}get userMap_(){return this.io.userManager.remotePublishedUserMap}send(e,r){return this.io.sendReq(e,r)}post(e,r){return this.io.postReq(e,r)}postMessage(e,r){this.io.postMessage({cmd:e,payload:r})}createResposeOb(e){return Ee(this.io,se[e])}glog(e){self.postMessage({type:"glog",payload:e})}};var Lt=class{constructor(){l(this,"arguments");l(this,"environment");l(this,"preInit");l(this,"preRun");l(this,"postRun");l(this,"onAbort");l(this,"preinitializedWebGLContext");l(this,"noInitialRun");l(this,"noExitRuntime");l(this,"logReadFiles");l(this,"filePackagePrefixURL");l(this,"wasmBinary");l(this,"HEAP");l(this,"IHEAP");l(this,"FHEAP");l(this,"HEAP8");l(this,"HEAP16");l(this,"HEAP32");l(this,"HEAPU8");l(this,"HEAPU16");l(this,"HEAPU32");l(this,"HEAPF32");l(this,"HEAPF64");l(this,"TOTAL_STACK");l(this,"TOTAL_MEMORY");l(this,"FAST_MEMORY");l(this,"preloadedImages");l(this,"preloadedAudios");l(this,"_GetEncodedFrame");l(this,"_ReceivedAudioPacket");l(this,"_CreateUdtPacketizer");l(this,"_PacketizeVideoUdt");l(this,"udtver",3)}onRuntimeInitialized(){}print(t){console.debug(t)}printErr(t){console.debug(t)}},ue=new Lt,k=class{constructor(t,e){this.size=t;l(this,"point");this.point=ue._malloc(t),e&&this.set(e)}set(t){t.length>this.size&&this.grow(t.length),ue.HEAPU8.set(t,this.point)}setUint32(t,e){new DataView(ue.HEAPU8.buffer).setUint32(this.point+t,e)}setBigUint64(t,e){new DataView(ue.HEAPU8.buffer).setBigUint64(this.point+t,e)}getBigUint64(t){return new DataView(ue.HEAPU8.buffer).getBigUint64(this.point+t)}getUint32(t){return ue.HEAPU8[this.point+t]|ue.HEAPU8[this.point+t+1]<<8|ue.HEAPU8[this.point+t+2]<<16|ue.HEAPU8[this.point+t+3]<<24}getInt8(t){return ue.HEAPU8[this.point+t]}uint8Array(t=NaN){return new Uint8Array(ue.HEAPU8.buffer,this.point,t>=0?t:this.size)}uint8Slice(t=NaN){return ue.HEAPU8.slice(this.point,this.point+(t>=0?t:this.size))}fill(t=0,e=this.point,r=this.point+this.size){ue.HEAPU8.fill(t,e,r)}free(){ue._free(this.point)}grow(t){t>this.size&&(this.free(),this.size=t,this.point=ue._malloc(t))}};l(k,"global");var F=ue;var Ar=class{constructor(t){l(this,"lastReceiveTime",-1);l(this,"blocking",!1);l(this,"blockCnt",0);l(this,"blockTime",0);l(this,"received",Qe());let e=We(t);V(this.received,Ys(()=>(this.blockDone(),this.lastReceiveTime=Date.now(),e)),X(()=>{this.blocking=!0},G,()=>{this.blockDone()}))}blockDone(){this.blocking&&(this.blockCnt++,this.blockTime+=Date.now()-this.lastReceiveTime,this.blocking=!1)}clear(){this.blockCnt=0,this.blockTime=0}},Ur=class Ur{constructor(t=2){l(this,"videoStatus",{uint32_video_stream_type:2,uint32_video_codec_fps:0,uint32_video_capture_fps:0,uint32_video_receive_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_codec_type:0,uint32_video_gop:0,uint32_video_rps_open:0,uint32_video_rps_interval:0,uint32_video_codec_bitrate:0,uint32_video_total_bitrate:0,uint32_video_fec_ratio:0,uint32_video_fec_recover:0,uint32_video_arq_request:0,uint32_video_arq_recover:0,uint32_video_arq_packets:0,uint32_video_receive:0,uint32_video_origin_lost:0,uint32_video_final_lost:0,uint32_video_block_cnt:0,uint32_video_cache_ms:0,uint32_video_total_frame:0,uint32_video_decode_frame:0,uint32_video_block_time:0,uint32_video_quality:0,uint32_video_jitter_fps:0});l(this,"videoPort");l(this,"control");l(this,"lastReceiveTime",-1);l(this,"vBlock",new Ar(500));l(this,"ssrc",Ur.g_ssrc++);l(this,"framesFromStartPull",0);this.videoStatus.uint32_video_stream_type=t}getVideoStatus(){let t=en({},this.videoStatus);return t.uint32_video_block_cnt=this.vBlock.blockCnt,t.uint32_video_block_time=this.vBlock.blockTime,t.uint32_video_codec_bitrate>>=1,t.uint32_video_total_bitrate>>=1,t.uint32_video_receive_fps>>=1,t.uint32_video_capture_fps>>=1,t.uint32_video_codec_fps>>=1,this.videoStatus.uint32_video_codec_bitrate=0,this.videoStatus.uint32_video_total_bitrate=0,this.videoStatus.uint32_video_receive_fps=0,this.videoStatus.uint32_video_capture_fps=0,this.videoStatus.uint32_video_codec_fps=0,this.vBlock.clear(),t}demuxPacket(t){let e=t.length,{ssrc:r,videoStatus:i,vBlock:a}=this;i.uint32_video_receive++;let c=Date.now();i.uint32_video_total_bitrate+=e<<3,k.global.set(t);let _=F._ReceivedVideoPacket(k.global.point,e,c/1e3,c%1e3,r);_==0&&(this.lastReceiveTime>0&&c-this.lastReceiveTime>500&&console.debug("demuxPacket",c-this.lastReceiveTime),this.lastReceiveTime=c),a.received.next(_)}gotVideoFrame(t){var r;this.videoStatus.uint32_video_total_frame++,this.videoStatus.uint32_video_codec_bitrate+=t.length<<3,this.videoStatus.uint32_video_receive_fps++,this.videoStatus.uint32_video_capture_fps++;let e=t.slice();(r=this.videoPort)==null||r.postMessage({data:e,packetsReceived:this.videoStatus.uint32_video_receive},[e.buffer])}};l(Ur,"g_ssrc",1);var yr=Ur,Or=class{constructor(t,e){this.writer=t;this.ssrc=e;l(this,"buffer",new k(960));l(this,"timestamp",0);F._AddAudioChannel(e,e)}feed(){}close(){F._DelAudioChannel(this.ssrc),this.buffer.free()}},vr=class{constructor(t,e){this.io=e;l(this,"userId");l(this,"tinyId");l(this,"role");l(this,"terminalType");l(this,"lastCapNtpMs",-1);l(this,"startTimestamp",Date.now());l(this,"alastReceivedTimestamp",-1);l(this,"lengthPoint",new k(4));l(this,"audioPuller");l(this,"mainPuller",new yr(2));l(this,"screenPuller",new yr(7));l(this,"aBlock",new Ar(250));l(this,"events",[]);l(this,"msg_audio_status",{uint32_audio_format:0,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_total_bitrate:0,uint32_audio_aec:0,uint32_audio_fec_ratio:0,uint32_audio_fec_recover:0,uint32_audio_arq_request:0,uint32_audio_arq_recover:0,uint32_audio_arq_packets:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_final_lost:0,uint32_audio_cache_ms:0,uint32_audio_capture_state:0,uint32_audio_filtered_max_cache_ms:0,uint32_audio_filtered_avg_cache_ms:0,uint32_audio_target_max_cache_ms:0,uint32_audio_target_avg_cache_ms:0,uint32_audio_delay_peak_count:0,uint32_audio_speed_percent:0,uint32_audio_quality:0,uint32_audio_block_time:0,uint32_audio_block_cnt:0,uint32_audio_level:0});l(this,"subscribe",0);l(this,"removing",!1);Object.defineProperties(this,Object.getOwnPropertyDescriptors(t))}remove(){var t;this.lengthPoint.free(),(t=this.audioPuller)==null||t.close()}toDownStreamInfo(t,e){let r=[this.mainPuller.getVideoStatus()];r[0].uint32_video_stream_type=this.subscribe&8?3:2,this.screenPuller.videoPort&&r.push(this.screenPuller.getVideoStatus());let i=en({},this.msg_audio_status);return i.uint32_audio_codec_bitrate>>=1,i.uint32_audio_total_bitrate>>=1,i.uint32_audio_block_cnt=this.aBlock.blockCnt,i.uint32_audio_block_time=this.aBlock.blockTime,e&&console.log(new Date().toLocaleString(),t.userId,r.map(a=>({t:a.uint32_video_stream_type,r_fps:a.uint32_video_receive_fps,c_fps:a.uint32_video_codec_fps,c_bps:a.uint32_video_codec_bitrate})),i.uint32_audio_codec_bitrate),this.msg_audio_status.uint32_audio_total_bitrate=0,this.msg_audio_status.uint32_audio_codec_bitrate=0,this.aBlock.clear(),{msg_user_info:{str_identifier:this.userId,uint64_tinyid:Number(this.tinyId)},msg_audio_status:i,msg_video_status:r,msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0,uint32_jitter:0}}}getNextVideoFrame(t){this.lengthPoint.setUint32(0,k.global.size);let e=F._GetEncodedFrame(k.global.point,this.lengthPoint.point,!1,t.ssrc),r=this.lengthPoint.getUint32(0);if(e==-1||r==0)return 10;let i=k.global.uint8Array(r);return t.videoStatus.uint32_video_total_frame||console.timeEnd(`${this.userId}${t==this.mainPuller?"big":"aux"}`),t.gotVideoFrame(i),e}startPullOnlyAudio(t,e,r){this.io.log_.info("start pull only audio",t),F._AddAudioChannel(t.ssrc,t.ssrc)}startPull(t,e,r){this.io.log_.info("start pull",t,r);let i=t===this.mainPuller;if(t.videoPort){t.framesFromStartPull=0,t.videoPort.port=e.port;return}let a=i?[2,1]:[7];t.videoPort=e,console.time(`${this.userId}${r.mediaType&2?"aux":"big"}`),V(e,X(({width:f,height:h})=>{t.videoStatus.uint32_video_width=f,t.videoStatus.uint32_video_height=h,t.videoStatus.uint32_video_decode_frame++,t.videoStatus.uint32_video_codec_fps++}));let c=f=>{delete t.videoPort,f?this.io.log_.error("stop pull",f):this.io.log_.info("stop pull",t),F._DelVideoChannel(t.ssrc),t.vBlock.received.complete(),i&&this.aBlock.received.complete()};F._AddVideoChannel(t.ssrc,t.ssrc);let _=0,m=0,d=()=>{Date.now()-m>2e3&&(m=Date.now(),this.io.sendReq(11,r))};V(this.io.wh.interval10ms,mt(f=>(_<=0&&(_=this.getNextVideoFrame(t),_>500&&(_=20)),_-=10,re.useWt&&(f&1)==0&&!a.every(h=>{let R=F._CheckMissingPacket(k.global.point,k.global.size,h,t.ssrc,this.io.rtt);return R>0&&(k.global.setBigUint64(5,BigInt(this.tinyId)),this.io.send(k.global.uint8Array(R))),R>=0}))),ke(e),X(d,c,c)),d(),V(Oe(5e3),ke(e),X(d))}};var Bu=1e8;function Vu(){let n=new k(500,[0]);return F._GetAudioEnergy(n.point,100),n}var gt=class gt extends he{constructor(){super(...arguments);l(this,"audioReceivedBuff",new k(2048));l(this,"levelsMap",new Map);l(this,"timestampBuff",new k(12))}decodeAudio(e,r){V(this.createResposeOb(4095),ke(r),X(({data:i})=>{let c=new DataView(i.buffer,i.byteOffset,i.byteLength).getBigUint64(9).toString();this.userMap_.has(c)&&(this.statReportReq.msg_net_stat_report.uint32_down_real_pkg++,this.statReportReq.msg_net_stat_report.uint32_down_recv_br+=i.byteLength,this.demuxPacket(i,this.userMap_.get(c),e&&r))})),e&&V(r,X(({timestamp:i,rtpTimestamp:a,seqNum:c,ssrc:_,data:m})=>{this.audioReceivedBuff.set(m),F._ReceivedRawAudioPacket(this.audioReceivedBuff.point,m.byteLength,i,a,c,_)}))}pullAudio({tinyId:e,writable:r}){let i=this.userMap_.get(e);i&&(i.audioPuller=new Or(r.getWriter(),i.mainPuller.ssrc))}getAudioEnergy(e,r){gt.energys||(gt.energys=Vu());let{energys:i}=gt;V(Oe(e),ke(r),X(()=>{let a=i.getInt8(0);for(let c=1;c<5*a;c+=5)this.levelsMap.set(i.getUint32(c),i.getInt8(c+4));if(this.userMap_.size>0){let c=[...this.userMap_.values()];r.postMessage(c.map(_=>{let m=Math.min(100,(this.levelsMap.get(_.mainPuller.ssrc)||0)*2);return _.msg_audio_status.uint32_audio_level=m*Bu/100>>0,{userId:_.userId,volume:m}}))}else r.postMessage([])}))}demuxPacket(e,r,i){let{aBlock:a,msg_audio_status:c}=r;a.received.next(!0),c.uint32_audio_total_bitrate+=e.byteLength<<3,c.uint32_audio_codec_bitrate=c.uint32_audio_total_bitrate-31,this.audioReceivedBuff.set(e);let _=Date.now(),m=_/1e3,d=_%1e3;if(i){let f=F._ParseUdtAudioPacket(this.audioReceivedBuff.point,e.length,this.timestampBuff.point,this.timestampBuff.point+4,this.timestampBuff.point+8,this.audioReceivedBuff.point,r.mainPuller.ssrc);if(f>0){let h=this.audioReceivedBuff.getUint32(0),R=F.HEAPU8.slice(h,h+f);i.postMessage({timestamp:this.timestampBuff.getUint32(0),rtpTimestamp:this.timestampBuff.getUint32(4),seqNum:this.timestampBuff.getUint32(8),data:R,ssrc:r.mainPuller.ssrc},[R.buffer])}}else F._ReceivedAudioUdtPacket(this.audioReceivedBuff.point,e.length,m,d,r.mainPuller.ssrc)}};l(gt,"energys");var kt=gt;var ci=sr(Mt(),1),ui=Symbol("instance"),pd=Symbol("abortCtrl"),Nr=Symbol("cacheResult"),Bt=class{constructor(t,e,r){this.oldState=t,this.newState=e,this.action=r,this.aborted=!1}abort(t){this.aborted=!0,Ft.call(t,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},tt=class extends Error{constructor(t,e,r){super(e),this.state=t,this.message=e,this.cause=r}};function Fu(n){return typeof n=="object"&&n&&"then"in n}var Vt=new Map;function de(n,t,e={}){return(r,i,a)=>{let c=e.action||i;if(!e.context){let m=Vt.get(r)||[];Vt.has(r)||Vt.set(r,m),m.push({from:n,to:t,action:c})}let _=a.value;a.value=function(...m){let d=this;if(e.context&&(d=Z.get(typeof e.context=="function"?e.context.call(this,...m):e.context)),d.state===t)return e.sync?d[Nr]:Promise.resolve(d[Nr]);d.state instanceof Bt&&d.state.action==e.abortAction&&d.state.abort(d);let f=null;Array.isArray(n)?n.length==0?d.state instanceof Bt&&d.state.abort(d):(typeof d.state!="string"||!n.includes(d.state))&&(f=new tt(d._state,`${d.name} ${c} to ${t} failed: current state ${d._state} not from ${n.join("|")}`)):n!==d.state&&(f=new tt(d._state,`${d.name} ${c} to ${t} failed: current state ${d._state} not from ${n}`));let h=y=>{if(e.fail&&e.fail.call(this,y),e.sync){if(e.ignoreError)return y;throw y}else return e.ignoreError?Promise.resolve(y):Promise.reject(y)};if(f)return h(f);let R=d.state,U=new Bt(R,t,c);Ft.call(d,U);let P=y=>{var C;return d[Nr]=y,U.aborted||(Ft.call(d,t),(C=e.success)===null||C===void 0||C.call(this,d[Nr])),y},Y=y=>(Ft.call(d,R,y),h(y));try{let y=_.apply(this,m);return Fu(y)?y.then(P).catch(Y):e.sync?P(y):Promise.resolve(P(y))}catch(y){return Y(new tt(d._state,`${d.name} ${c} from ${n} to ${t} failed: ${y}`,y instanceof Error?y:new Error(String(y))))}}}}var Hu=typeof window!="undefined"&&window.__AFSM__?(e,r)=>{window.dispatchEvent(new CustomEvent(e,{detail:r}))}:typeof importScripts!="undefined"?(e,r)=>{postMessage({type:e,payload:r})}:()=>{};function Ft(n,t){let e=this._state;this._state=n;let r=n.toString();n&&this.emit(r,e),this.emit(Z.STATECHANGED,n,e,t),this.updateDevTools({value:n,old:e,err:t instanceof Error?t.message:String(t)})}var Z=class n extends ci.default{constructor(t,e,r){super(),this.name=t,this.groupName=e,this._state=n.INIT,t||(t=Date.now().toString(36)),r?Object.setPrototypeOf(this,r):r=Object.getPrototypeOf(this),e||(this.groupName=this.constructor.name);let i=r[ui];i?this.name=i.name+"-"+i.count++:r[ui]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let t=Object.getPrototypeOf(this),e=Vt.get(t)||[],r=new Set,i=[],a=[],c=new Set,_=Object.getPrototypeOf(t);Vt.has(_)&&(_.stateDiagram.forEach(d=>r.add(d)),_.allStates.forEach(d=>c.add(d))),e.forEach(({from:d,to:f,action:h})=>{typeof d=="string"?i.push({from:d,to:f,action:h}):d.length?d.forEach(R=>{i.push({from:R,to:f,action:h})}):a.push({to:f,action:h})}),i.forEach(({from:d,to:f,action:h})=>{c.add(d),c.add(f),c.add(h+"ing"),r.add(`${d} --> ${h}ing : ${h}`),r.add(`${h}ing --> ${f} : ${h} \u{1F7E2}`),r.add(`${h}ing --> ${d} : ${h} \u{1F534}`)}),a.forEach(({to:d,action:f})=>{r.add(`${f}ing --> ${d} : ${f} \u{1F7E2}`),c.forEach(h=>{h!==d&&r.add(`${h} --> ${f}ing : ${f}`)})});let m=[...r];return Object.defineProperties(t,{stateDiagram:{value:m},allStates:{value:c}}),m}static get(t){let e;return typeof t=="string"?(e=n.instances.get(t),e||n.instances.set(t,e=new n(t,void 0,Object.create(n.prototype)))):(e=n.instances2.get(t),e||n.instances2.set(t,e=new n(t.constructor.name,void 0,Object.create(n.prototype)))),e}static getState(t){var e;return(e=n.get(t))===null||e===void 0?void 0:e.state}updateDevTools(t={}){Hu(n.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},t))}get state(){return this._state}set state(t){Ft.call(this,t)}};Z.STATECHANGED="stateChanged";Z.UPDATEAFSM="updateAFSM";Z.INIT="[*]";Z.ON="on";Z.OFF="off";Z.instances=new Map;Z.instances2=new WeakMap;var qu=function(n,t,e,r){function i(a){return a instanceof e?a:new e(function(c){c(a)})}return new(e||(e=Promise))(function(a,c){function _(f){try{d(r.next(f))}catch(h){c(h)}}function m(f){try{d(r.throw(f))}catch(h){c(h)}}function d(f){f.done?a(f.value):i(f.value).then(_,m)}d((r=r.apply(n,t||[])).next())})},Yn=Symbol(32),Kn=Symbol(16),Jn=Symbol(8),ve=class{constructor(t){this.g=t,this.consumed=0,t&&(this.need=t.next().value)}setG(t){this.g=t,this.demand(t.next().value,!0)}consume(){this.buffer&&this.consumed&&(this.buffer.copyWithin(0,this.consumed),this.buffer=this.buffer.subarray(0,this.buffer.length-this.consumed),this.consumed=0)}demand(t,e){return e&&this.consume(),this.need=t,this.flush()}read(t){return qu(this,void 0,void 0,function*(){return this.lastReadPromise&&(yield this.lastReadPromise),this.lastReadPromise=new Promise((e,r)=>{var i;this.reject=r,this.resolve=c=>{delete this.lastReadPromise,delete this.resolve,delete this.need,e(c)},this.demand(t,!0)||(i=this.pull)===null||i===void 0||i.call(this,t)})})}readU32(){return this.read(Yn)}readU16(){return this.read(Kn)}readU8(){return this.read(Jn)}close(){var t;this.g&&this.g.return(),this.buffer&&this.buffer.subarray(0,0),(t=this.reject)===null||t===void 0||t.call(this,new Error("EOF")),delete this.lastReadPromise}flush(){if(!this.buffer||!this.need)return;let t=null,e=this.buffer.subarray(this.consumed),r=0,i=a=>e.length<(r=a);if(typeof this.need=="number"){if(i(this.need))return;t=e.subarray(0,r)}else if(this.need===Yn){if(i(4))return;t=e[0]<<24|e[1]<<16|e[2]<<8|e[3]}else if(this.need===Kn){if(i(2))return;t=e[0]<<8|e[1]}else if(this.need===Jn){if(i(1))return;t=e[0]}else if("buffer"in this.need){if("byteOffset"in this.need){if(i(this.need.byteLength-this.need.byteOffset))return;new Uint8Array(this.need.buffer,this.need.byteOffset).set(e.subarray(0,r)),t=this.need}else if(this.g){this.g.throw(new Error("Unsupported type"));return}}else{if(i(this.need.byteLength))return;new Uint8Array(this.need).set(e.subarray(0,r)),t=this.need}return this.consumed+=r,this.g?this.demand(this.g.next(t).value,!0):this.resolve&&this.resolve(t),t}write(t){if(t instanceof Uint8Array?this.malloc(t.length).set(t):"buffer"in t?this.malloc(t.byteLength).set(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)):this.malloc(t.byteLength).set(new Uint8Array(t)),this.g||this.resolve)this.flush();else return new Promise(e=>this.pull=e)}writeU32(t){this.malloc(4).set([t>>24&255,t>>16&255,t>>8&255,t&255]),this.flush()}writeU16(t){this.malloc(2).set([t>>8&255,t&255]),this.flush()}writeU8(t){this.malloc(1)[0]=t,this.flush()}malloc(t){if(this.buffer){let e=this.buffer.length,r=e+t;if(r<=this.buffer.buffer.byteLength-this.buffer.byteOffset)this.buffer=new Uint8Array(this.buffer.buffer,this.buffer.byteOffset,r);else{let i=new Uint8Array(r);i.set(this.buffer),this.buffer=i}return this.buffer.subarray(e,r)}else return this.buffer=new Uint8Array(t),this.buffer}};ve.U32=Yn;ve.U16=Kn;ve.U8=Jn;var je=class extends Z{constructor(e){super(e.params.userId,"WebSocket");this.connectFSM=e;l(this,"ws")}connect(){this.connectFSM.log_.info("connect to",this.connectFSM.wsUrl);let e=new WebSocket(this.connectFSM.wsUrl);return console.time("WebSocket connect"),e.binaryType="arraybuffer",Ge((r,i)=>{e.onerror=a=>{e.onmessage=null,this.connectFSM.log_.error("websocket onerror",a),i(a.type)},e.onclose=a=>{e.onmessage=null,i(a),this.connectFSM.log_.info("websocket onclose",a),this.disconnect(a.reason,a.code)},e.onopen=a=>{console.timeEnd("WebSocket connect"),this.connectFSM.log_.info("websocket onopen")},e.onmessage=a=>{try{let c=JSON.parse(String(a.data));if(this.connectFSM.log_.info("websocket verify",c),c.err!==0)throw c.err;this.connectFSM.verify(c.verify,c.rebuild),this.ws=e,r(e);let _=this.connectFSM.createOputReceiver("w");e.onmessage=m=>_.write(m.data)}catch(c){i(c)}}},this.connectFSM.abortCtrl.signal)}disconnect(e="",r=0){return r===0&&this.ws&&(this.ws.onmessage=null,this.ws.close(1e3,e)),this.connectFSM.log_.warn("websocket disconnected :",r,e),this.connectFSM.disconnect(e)}close(){this.ws&&(this.ws.onmessage=null,this.ws.close(1e3,"close"))}sendReq(e,r,i){this.send(Ir(e,r,i||this.connectFSM.generateUUID()))}send(e){var r;this.state=="CONNECTED"&&((r=this.ws)==null||r.send(e))}};ce([de(["DISCONNECTED",Z.INIT],"CONNECTED")],je.prototype,"connect",1),ce([de("CONNECTED","DISCONNECTED",{sync:!0,ignoreError:!0})],je.prototype,"disconnect",1),ce([de([],Z.INIT,{sync:!0})],je.prototype,"close",1);var Dd=new Uint32Array([Date.now()]),Wu=V(lt(20),ze(()=>performance.now()),qe()),Qn=class{constructor(t){this.wt=t;l(this,"chunk",new Map);l(this,"timestamp",performance.now());l(this,"groupId");l(this,"resentCount",0);this.groupId=t.groupid,t.groupid=t.groupid+1&127,t.sentCache.has(this.groupId)&&t.sentCache.get(this.groupId).chunk.clear(),t.sentCache.set(this.groupId,this),V(Wu,On(()=>this.chunk.size>0&&this.resentCount<20),ye(Ee(t,"DISCONNECTED")),X(e=>{e-this.timestamp>2*t.connectFSM.rtt+10&&(this.chunk.forEach((r,i)=>this.wt.send(r.buffer)),console.debug("resent",this.groupId,this.chunk.size,"after",e-this.timestamp,"ms",++this.resentCount),this.timestamp=e)},console.error,()=>{this.wt.sentCache.delete(this.groupId)}))}ack(t){this.chunk.delete(t)}},$e=class extends Z{constructor(e){super(e.params.userId,"WebTransport");this.connectFSM=e;l(this,"wt");l(this,"writer");l(this,"dw");l(this,"sentCache",new Map);l(this,"groupid",0);l(this,"mtu",1e3)}async connect(){this.connectFSM.log_.info("connect to",this.connectFSM.wtUrl);let e=new WebTransport(this.connectFSM.wtUrl);console.time("WebTransport connect"),e.ready.then(()=>console.timeEnd("WebTransport connect"));let r=this.connectFSM.abortCtrl.signal,{value:i,stream:a}=await Promise.race([(async()=>{await Ge(e.ready,r);let _=await Ge(e.createBidirectionalStream(),r),m=_.readable.getReader();return this.writer=_.writable.getWriter(),this.dw=e.datagrams.writable.getWriter(),Ge(m.read(),r).then(({value:d})=>(m.releaseLock(),{value:d,stream:_}))})(),new Promise((_,m)=>setTimeout(()=>m(new Error("WebTransport connect timeout")),1e3))]),c=JSON.parse(String.fromCharCode(...i));if(this.connectFSM.log_.info("WebTransport connect result:",c),c.err!==0)throw c.err;this.connectFSM.verify(c.verify,c.rebuild),this.wt=e,V(Ee(this.connectFSM,se[4099]),ye(Ee(this,"DISCONNECTED")),X(({data:_})=>{let m=_[0]&127,d=this.sentCache.get(m);d&&d.ack(_[1])})),Promise.race([e.datagrams.readable.pipeTo(new WritableStream(this.connectFSM.createOputReceiver("d"))),a.readable.pipeTo(new WritableStream(this.connectFSM.createOputReceiver("s"))),e.closed]).then(()=>this.disconnect(),this.disconnect.bind(this))}disconnect(e=""){var r;return(r=this.wt)==null||r.close(),this.connectFSM.disconnect(e)}close(){var e;return(e=this.wt)==null?void 0:e.close()}async sendReq(e,r,i){if(i||(i=this.connectFSM.generateUUID()),!this.wt)return new Error("WebTransport not connected");if(!re.unreliable){let U=Ir(e,r,i);return this.writer.write(U).then(()=>!0).catch(this.catchError)}let a=e>=255&&e<4095,c=JSON.stringify(r),_=0,m=c.length+(a?20:16),f=(m>65535?1:0)?7:5,h=Math.ceil(m/this.mtu),R=new Qn(this);console.debug("WebTransport send:",a?"ack":"",se[e],i,"chunks:",h,R.groupId);for(let U=0;U<h;U++){let P=m-U*this.mtu,Y=Math.min(this.mtu,P),y=new Uint8Array(f+4+Y),C=jn(e,y.length-f,new DataView(y.buffer));if(y[0]|=2,y.set([1,2,(U==h-1?128:0)|R.groupId,U],C),C+=4,U==0){a&&(y.set([0,0,0,0],C),C+=4);for(let j=0;j<16;j++)y[C++]=i.charCodeAt(j)}for(let j=0;C<y.length;j++)y[C++]=c.charCodeAt(_++);R.chunk.set(U,y),this.send(y.buffer)}}async send(e){if(!(!this.wt||!this.dw)){if(e instanceof ArrayBuffer){if(!e.byteLength)throw li}else{if(!e.length)throw li;e=e.slice(0)}return this.dw.write(e).catch(this.catchError)}}catchError(e){}};ce([de(["DISCONNECTED",Z.INIT],"CONNECTED")],$e.prototype,"connect",1),ce([de("CONNECTED","DISCONNECTED",{sync:!0,ignoreError:!0})],$e.prototype,"disconnect",1),ce([de([],Z.INIT,{sync:!0})],$e.prototype,"close",1);var li=new Error("WebTransport send empty datagram");var mi=sr(Mt(),1);var Dr=class extends mi.EventEmitter{constructor(e,r,i="userId"){super();this.mySelfId=e;this._log=r;this.key=i;l(this,"userMap",new Map);l(this,"remotePublishedUserMap",new Map)}get hasRobotUser(){return!![...this.remotePublishedUserMap.values()].find(e=>e.isRobot)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let r=e[this.key],{userId:i,tinyId:a,role:c}=e;if(this.userMap.has(r))return;let _={userId:i,tinyId:a,role:c===20?"anchor":"audience"};this.userMap.set(r,_),this.emit("1",_)}deleteUser(e,r){let i=this.userMap.get(e);if(!i)return;let a=`peer leave [${e}]`;Tr(r)||(a+=`:${ri[r]}`),this._log.info(a);let c=this.remotePublishedUserMap.get(e);if(c){let _=c.muteState;c.flag=0,this.emit("5",c.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:_,muteState:c.muteState,flag:0})}this.userMap.delete(e),this.emit("2",i.userId)}setUserList(e){this.userMap.forEach(r=>{e.findIndex(i=>i[this.key]===r[this.key])<0&&this.deleteUser(r[this.key],0)}),e.forEach(r=>{!this.userMap.has(r[this.key])&&r[this.key]!==this.mySelfId&&this.addUser(r)})}addRemotePublishedUser(e){this.remotePublishedUserMap.has(e[this.key])||this.remotePublishedUserMap.set(e[this.key],e)}deleteRemotePublishedUser(e){this.remotePublishedUserMap.has(e)&&this.remotePublishedUserMap.delete(e)}setRemotePublishedUserList(e){this.remotePublishedUserMap.forEach(r=>{let i=r[this.key];if(e.findIndex(a=>a[this.key]===r[this.key])<0){this._log.info(`remote [${i}] unpublish`);let a=r.muteState;r.flag=0,this.emit("5",r.userId),this.deleteRemotePublishedUser(i),this.emit("6",{prevMuteState:a,muteState:r.muteState,flag:0})}}),e.forEach(r=>{var f;let i=r[this.key];if(i===this.mySelfId)return;let{flag:a,userId:c,tinyId:_}=r,m=Wn(a,c),d=(f=this.remotePublishedUserMap.get(i))==null?void 0:f.muteState;if(d){let h=this.remotePublishedUserMap.get(i);h&&h.flag!==a&&(h.flag=a,this._log.info(`remote publish updated: ${JSON.stringify(h.muteState)}`),this.emit("6",{prevMuteState:d,muteState:m,flag:a}))}else this._log.info(`remote publish. state: ${JSON.stringify(m)}`),this.addUser({userId:c,tinyId:_,role:20}),this.emit("3",r),this.emit("6",{prevMuteState:Wn(0,c),muteState:m,flag:a})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};var jd=new Date().getTime(),Gu=0;var zn=function(){return new Date().getTime()+Gu},di=function(){let n=new Date;return n.setTime(zn()),n.toLocaleString()},pi=function(n){let t=String(n.getMilliseconds());return"padStart"in String.prototype&&(t=t.toString().padStart(3,"0")),`${n.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")}:${t}`};function _i({url:n,body:t,method:e="POST",timeout:r,priority:i}){return new Promise((a,c)=>{if("fetch"in window)return fetch(n,{method:e,body:t,priority:i}).then(m=>m.text()).then(m=>{try{a({data:JSON.parse(m)})}catch(d){a({data:m})}},c);let _=new XMLHttpRequest;_.onreadystatechange=()=>{if(_.readyState===4)if(_.status>=200&&_.status<300)try{let m=JSON.parse(_.response);a({data:m})}catch(m){a({data:_.response})}else c({status:_.status,statusText:_.statusText||"request failed!"})},_.timeout=r||5e3,_.open(e,n,!0),_.send(t)})}var ju=Object.prototype.hasOwnProperty;var St=n=>typeof n=="function",fi=n=>typeof n=="undefined";var hi=n=>typeof n=="boolean";var $u=function(n){if(!n||typeof n!="object"||Object.prototype.toString.call(n)!="[object Object]")return!1;let t=Object.getPrototypeOf(n);if(t===null)return!0;let e=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return typeof e=="function"&&e instanceof e&&Function.prototype.toString.call(e)===Function.prototype.toString.call(Object)};function bi(n){if(n==null)return!0;if(typeof n=="boolean")return!1;if(typeof n=="number")return n===0;if(typeof n=="string"||typeof n=="function"||Array.isArray(n))return n.length===0;if(n instanceof Error)return n.message==="";if($u(n))switch(Object.prototype.toString.call(n)){case"[object File]":case"[object Map]":case"[object Set]":return n.size===0;case"[object Object]":{for(let t in n)if(ju.call(n,t))return!1;return!0}}return!1}var Yu=0,Ku=1,gi=2;function Ju({retryFunction:n,settings:t,onError:e,onRetrying:r,onRetryFailed:i,onRetrySuccess:a,context:c}){return function(..._){let{retries:m=5,timeout:d=1e3}=t,f=0,h=-1,R=Yu,U=async(P,Y)=>{let y=c||this;try{let C=await n.apply(y,_);f>0&&a&&a.call(this,f),f=0,P(C)}catch(C){let j=()=>{clearTimeout(h),f=0,R=gi,Y(C)},Te=()=>{R!==gi&&f<(St(m)?m():m)?(f++,R=Ku,St(r)&&r.call(this,f,j),h=window.setTimeout(()=>{h=-1,U(P,Y)},St(d)?d(f):d)):(j(),St(i)&&i.call(this,C))};St(e)?e.call(this,{error:C,retry:Te,reject:Y,retryFuncArgs:_,retriedCount:f}):Te()}};return new Promise(U)}}var Ei=Ju;var Ht=class{constructor(t){l(this,"userId");l(this,"remoteUserId");l(this,"id");l(this,"sdkAppId");l(this,"type");l(this,"isLocal");this.id=t.id,this.userId=t.userId,this.sdkAppId=t.sdkAppId,this.remoteUserId=t.remoteUserId,this.isLocal=hi(t.isLocal)?t.isLocal:!0,this.type=this.isLocal?"":t.type}createChild(t){return Object.setPrototypeOf(t,this)}setUserId(t){this.userId=t}setSdkAppId(t){this.sdkAppId=t}log(t,e){let r=this.isLocal?this.userId:this.remoteUserId;e.unshift(`[${this.isLocal?"\u2191":"\u2193"}${this.type&&this.type!=="main"?"*":""}${this.id}${r?`|${r}`:""}]`),Tt.log(t,e,fi(this.userId)||bi(this.userId),this.userId,this.sdkAppId)}info(...t){this.log(2,t)}debug(...t){this.log(1,t)}warn(...t){this.log(3,t)}error(...t){this.log(4,t)}};var De=typeof navigator=="undefined"?"":navigator.userAgent,M=n=>new RegExp(n,"i").test(De),ne=n=>{if(M(n)){let t=new RegExp(`${n}\\/([\\d.]+)`),e=De.match(t);if(e&&e[1])return e[1]}return""},Zn=n=>{if(M(n)){let t=new RegExp(`${n}\\/(\\d+)`),e=De.match(t);if(e&&e[1])return parseFloat(e[1])}return NaN},Ti=/AppleWebKit\/([\d.]+)/i.exec(De),Xu=Ti?parseFloat(Ti[1]):NaN,Ii=M("iPad"),Ri=typeof navigator!="undefined"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&M("Macintosh"),Ai=M("iPhone")&&!Ii,Qu=M("iPod"),Cr=Ai||Ii||Qu||Ri,It=M("Android"),yi=function(){if(It){let n=De.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(n){let t=n[1]&&parseFloat(n[1]),e=n[2]&&parseFloat(n[2]);if(t&&e)return parseFloat(`${n[1]}.${n[2]}`);if(t)return t}}return NaN}(),ip=It&&M("webkit")&&yi<2.3,op=It&&yi<5&&Xu<537,zu=M("Firefox"),Zu=ne("Firefox"),ap=Zn("Firefox"),Oi=M("Edge"),ec=ne("Edge"),vi=M("Edg"),tc=ne("Edg"),up=Zn("Edg"),Ui=M("SogouMobileBrowser"),rc=ne("SogouMobileBrowser"),xi=M("MetaSr\\s"),nc=ne("MetaSr\\s"),rt=M("TBS"),sc=ne("TBS"),Pi=M("XWEB"),ic=ne("XWEB"),cp=M("MSIE\\s8\\.0"),oc=M("MSIE\\/\\d+"),lp=function(){if(oc){let n=/MSIE\s(\d+)\.\d/.exec(De),t=n&&parseFloat(n[1]);return!t&&/Trident\/7.0/i.test(De)&&/rv:11.0/.test(De)&&(t=11),t}return NaN}(),ac=M("(micromessenger|webbrowser)"),uc=ne("MicroMessenger"),es=!rt&&M("MQQBrowser")&&M("COVC"),ts=!rt&&M("MQQBrowser")&&!M("COVC"),Si=ts||es?ne("MQQBrowser"):"",Ni=!rt&&M(" QQBrowser"),cc=ne(" QQBrowser"),Di=!rt&&M("QQBrowserLite"),lc=ne("QQBrowserLite"),Ci=!rt&&M("MQBHD"),mc=ne("MQBHD"),mp=M("Windows"),dp=!Cr&&M("MAC OS X"),pp=!It&&M("Linux"),_p=M("CrOS"),fp=M("MicroMessenger"),hp=M("UCBrowser"),bp=M("Electron"),wi=M("MiuiBrowser"),dc=ne("MiuiBrowser"),Mi=M("HuaweiBrowser"),gp=M("Huawei")||M("HUAWEI"),Ep=M("Honor")||M("HONOR"),pc=ne("HuaweiBrowser"),Li=M("SamsungBrowser"),_c=ne("SamsungBrowser"),ki=M("HeyTapBrowser"),fc=ne("HeyTapBrowser"),Bi=M("VivoBrowser"),hc=ne("VivoBrowser"),Tp=M("OpenHarmony"),Sp=ne("OpenHarmony"),bc=()=>Zn("Chrome"),Vi=M("Chrome"),gc=!Oi&&!xi&&!Ui&&!rt&&!Pi&&!vi&&!Ni&&!wi&&!Mi&&!Li&&!ki&&!Bi&&Vi,Fi=M("HeadlessChrome"),Ip=bc(),Ec=ne("Chrome"),Tc=!Vi&&!ts&&!es&&!Di&&!Ci&&M("Safari");var Hi=ne("Version"),Rp=/Android.*(wv|.0.0.0)/.test(De),qi=(()=>{if(Ri)return Hi;if(Cr){let n=De.match(/OS (\d+)_(\d+)/i);if(n&&n[1]){let t=n[1];return n[2]&&(t+=`.${n[2]}`),t}}return""})();var Ap=Number(qi.split(".")[0]);var yp=(()=>{let n=Number(qi.split(".")[0]);return n===14||n===13})(),Op=M("CriOS");var vp=typeof location=="undefined"?!1:location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1";var Up=Sc();function Sc(){let n=new Map([[zu,["Firefox",Zu]],[vi,["Edg",tc]],[gc,["Chrome",Ec]],[Tc,["Safari",Hi]],[rt,["TBS",sc]],[Pi,["XWEB",ic]],[ac&&Ai,["WeChat",uc]],[Ni,["QQ(Win)",cc]],[ts,["QQ(Mobile)",Si]],[es,["QQ(Mobile X5)",Si]],[Di,["QQ(Mac)",lc]],[Ci,["QQ(iPad)",mc]],[wi,["MI",dc]],[Mi,["HW",pc]],[Li,["Samsung",_c]],[ki,["OPPO",fc]],[Bi,["VIVO",hc]],[Oi,["EDGE",ec]],[Ui,["SogouMobile",rc]],[xi,["Sogou",nc]]]),t="unknown",e="unknown";return n.has(!0)&&([t,e]=n.get(!0)),{name:t,version:e}}var Wi=sr(Mt(),1),Ic=new Wi.default,Rt=Ic;var rs=(x=>(x.ROOM_DESTROY="1",x.JOIN_START="21",x.JOIN_SCHEDULE_SUCCESS="22",x.JOIN_SIGNAL_CONNECTION_START="23",x.JOIN_SIGNAL_CONNECTION_END="24",x.JOIN_SEND_CMD="25",x.JOIN_RECEIVED_CMD_RES="26",x.JOIN_SUCCESS="27",x.JOIN_FAILED="28",x.LEAVE_START="51",x.LEAVE_SEND_CMD="52",x.LEAVE_SUCCESS="53",x.PUBLISH_START="61",x.SEND_FIRST_VIDEO_FRAME="62",x.PUBLISH_FAILED="63",x.SUBSCRIBE_START="81",x.SUBSCRIBE_SUCCESS="82",x.SUBSCRIBE_FAILED="84",x.UNSUBSCRIBE_SUCCESS="83",x.LOCAL_TRACK_CAPTURE_START="101",x.LOCAL_TRACK_CAPTURE_SUCCESS="102",x.LOCAL_TRACK_CAPTURE_FAILED="103",x.LOCAL_TRACK_PUBLISHED="104",x.LOCAL_TRACK_UNPUBLISHED="105",x.LOCAL_TRACK_REPLACED="106",x.SWITCH_DEVICE_SUCCESS="107",x.TRACK_MUTED="108",x.TRACK_UNMUTED="109",x.REMOTE_TRACK_SUBSCRIBED="110",x.REMOTE_TRACK_UNSUBSCRIBED="111",x.LOCAL_TRACK_RECAPTURE="112",x.LOCAL_AUDIO_STARTED="113",x.LOCAL_AUDIO_STOPPED="114",x.REMOTE_AUDIO_STARTED="115",x.REMOTE_AUDIO_STOPPED="116",x.PLAY_TRACK_START="151",x.PLAYER_STATE_CHANGED="152",x.VIDEO_LOADED_DATA="153",x.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",x.SIGNAL_CONNECTION_STATE_CHANGED="201",x.PEER_CONNECTION_STATE_CHANGED="202",x.SINGLE_CONNECTION_STAT="203",x.SPC_RECONNECTED="204",x.HEARTBEAT_REPORT="251",x.RECEIVED_PUBLISHED_USER_LIST="252",x.REMOTE_PUBLISH_STATE_CHANGED="253",x.AUDIO_LEVEL_INTERVAL="260",x.NETWORK_QUALITY="261",x.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",x.QUALITY_LIMITATION_CHANGED="263",x.LOG="264",x.AUDIO_PROCESSOR_DEBUG="265",x.SWITCH_ROOM_START="401",x.SWITCH_ROOM_SUCCESS="407",x.SWITCH_ROOM_FAILED="408",x))(rs||{});var Ye=rs;var Rc="%cTRTC%c%s",Ac="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",yc="display: inline",wr=class wr{constructor(){l(this,"_isEnableUploadLog",!0);l(this,"_localJoinedUser",new Map);l(this,"_queue",[]);l(this,"_timeoutId",-1);l(this,"_logLevel",1);l(this,"_logLevelToUpload",2);!Js&&!br&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){Rt.on(Ye.JOIN_SCHEDULE_SUCCESS,({schedule:t})=>{var e;(e=t==null?void 0:t.config)!=null&&e.logLevelToUpload&&Le[t.config.logLevelToUpload]&&(this._logLevelToUpload=t.config.logLevelToUpload)}),Rt.on(Ye.JOIN_SUCCESS,({room:t})=>{this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload()}),Rt.once(Ye.JOIN_FAILED,()=>{this.startUpload()}),Rt.on(Ye.LEAVE_SUCCESS,({room:t})=>{this.deleteJoinedUser(t.userId)})}startUpload(){this._timeoutId===-1&&this.uploadInterval()}addJoinedUser(t){this._localJoinedUser.set(t.userId,t),this.startUpload()}deleteJoinedUser(t){this._localJoinedUser.delete(t)}uploadInterval(){this.upload().catch(()=>{}),this._timeoutId=window.setTimeout(()=>this.uploadInterval(),5e3)}getLogsToUpload(){let t={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&this._localJoinedUser.size===0)return t;let e=0;for(;e<this._queue.length&&e!==50;e++){let r=this._queue[e];if(r.forAllJoinedClients)this._localJoinedUser.forEach(({userId:i,sdkAppId:a})=>{t.map.has(i)?t.map.get(i).logs.push(r):t.map.set(i,{userId:i,sdkAppId:a,logs:[r]})});else if(qn(r.userId)&&si(r.sdkAppId)){let{userId:i,sdkAppId:a}=r;t.map.has(i)?t.map.get(i).logs.push(r):t.map.set(i,{userId:i,sdkAppId:a,logs:[r]})}}return t.map.size>0&&(t.splicedQueue=this._queue.splice(0,e)),t}async upload(){if(this._queue.length===0||!this._isEnableUploadLog)return;let{map:t,splicedQueue:e}=this.getLogsToUpload();if(t.size===0)return;try{let i=[...t.values()];for(let a=0;a<i.length;a++){let{userId:c,sdkAppId:_,logs:m}=i[a];await this.uploadLogWithRetry(JSON.stringify({timestamp:di(),sdkAppId:String(_),userId:c,version:Ze,log:m.map(d=>d.log).join(`
|
|
2
|
+
`)}),_),m.forEach(d=>d.uploaded=!0)}}catch(i){}let r=e.filter(i=>!i.uploaded);r.length>0&&(this._queue=r.concat(this._queue))}uploadLogWithRetry(t,e){return Ei({retryFunction:()=>_i({url:ni(e,zs.LOG),body:t,timeout:5e3,priority:"low"}),settings:{retries:3,timeout:2e3},onError:({retry:r})=>{r()}})()}getPrefix(t){let e=new Date;return e.setTime(zn()),`[${pi(e)}] <${Le[t]}>`}getLogLevel(){return this._logLevel}setLogLevel(t){Tr(Le[t])||(this._logLevel!==t&&this.info("setLogLevel",t),this._logLevel=t)}enableUploadLog(){this._isEnableUploadLog=!0}disableUploadLog(){this.warn("disableUploadLog"),this._isEnableUploadLog=!1}logChunkToString(t){if(qn(t))return t;try{return t instanceof Error?t.toString():JSON.stringify(t)}catch(e){return""}}log(t,e,r=!0,i,a){var m;e.unshift(this.getPrefix(t));let c={log:e.reduce((d,f)=>`${d} ${this.logChunkToString(f)}`.trim(),""),level:t,userId:i,sdkAppId:a,forAllJoinedClients:r};if(Rt.emit(Ye.LOG,{log:c}),this._isEnableUploadLog&&t>=this._logLevelToUpload&&this._queue.push(c),t<this._logLevel)return;let _=((m=Le[t])==null?void 0:m.toLowerCase())||"info";wr.PRINT_LOG_TAG?console[_](Rc,Ac,yc,...e):console[_](...e)}debug(...t){this.log(1,t)}info(...t){this.log(2,t)}warn(...t){this.log(3,t)}error(...t){this.log(4,t)}createLogger(t){return new Ht(t)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),r=e?Number(e):-1;Le[r]&&(this._logLevelToUpload=r)}getQueue(){return this._queue}};l(wr,"PRINT_LOG_TAG",!(Cr||It||Fi));var ns=wr,Tt=new ns;function Gi(n,t=1,e=1){return n<=1?e:Gi(n-1,e,t+e)}function xc(n){return n>8?30*1e3:Gi(n)*1e3}function Pc(n,t){return{userId:t,hasAudio:!!(n&ft),hasVideo:!!(n&_t),hasAuxiliary:!!(n&Er),hasSmall:!!(n&gr),audioMuted:!!(n&ht),videoMuted:!!(n&bt),audioAvailable:!!(n&ft)&&!(n&ht),videoAvailable:!!(n&_t)&&!(n&bt)}}var ss=class{constructor(t){this.connect=t;l(this,"publishReq");l(this,"recovering",!1);l(this,"pingCount",0)}async recoverLocal(){return this.recovering=!0,this.publishReq?this.connect._sendReq(2,this.publishReq).then(t=>{this.connect.log_.info("republish",t)}):!1}recoverRemote(t){this.recovering=!1,t.forEach((e,r)=>{this.connect.sendSubscribe(e)})}onSendReq(t,e){switch(t){case 2:this.publishReq?this.publishReq.mediaType|=e.mediaType:this.publishReq=e;break;case 3:this.publishReq=void 0;break;case 8:this.publishReq&&(this.publishReq.mediaType&=~e.mediaType);break;case 9:this.publishReq&&(this.publishReq.mediaType|=e.mediaType);break;case 12:this.connect.updateDevTools({note:`ping${this.pingCount++}`});break}}},be=class be extends Z{constructor(e,r,i){super(i.joinReq.roomid,"Connection");this.id=e;this.port=r;l(this,"signalInfo_");l(this,"reqUser_");l(this,"joinReq");l(this,"frameWorkType");l(this,"userManager");l(this,"joinRes");l(this,"statReportReq");l(this,"qualityReportReq");l(this,"wFSM");l(this,"rtt",50);l(this,"recovery",new ss(this));l(this,"reqPromise",new Map);l(this,"rebuild");l(this,"osName");l(this,"browserInfo");l(this,"tinyId_",new k(32));l(this,"tinyId");l(this,"domains");l(this,"log_");l(this,"params");l(this,"proxy_ws");l(this,"proxy_wt");l(this,"proxy_cloud");l(this,"proxy_unified");l(this,"env");l(this,"wh");l(this,"abortCtrl",new AbortController);l(this,"firstReceiveUserlist");l(this,"connectParams");l(this,"selectDomain",0);l(this,"selectCloudDomain",0);l(this,"abort",this.abortCtrl.abort.bind(this.abortCtrl));l(this,"reconnectedOB",Ee(this,"RECONNECTED"));l(this,"reconnectOB",e=>{this.reconnect().then(()=>{this.postMessage({cmd:"signal-connection-state-changed",payload:{prevState:"RECONNECTING",state:"CONNECTED"}}),this.rejoinRoom()},r=>{e.next(r),this.selectDomain=1-this.selectDomain})});console.log(this),Object.assign(this,i),this.connectParams=new URLSearchParams({sdkAppid:this.params.sdkAppId.toString(),userSig:this.params.userSig,identifier:this.params.userId}),this.tinyId&&this.connectParams.append("tinyId",this.tinyId),this.log_=Tt.createLogger({id:`wc${e}`,userId:this.params.userId,sdkAppId:this.params.sdkAppId}),this.proxy_unified?re.useWt=!1:(this.proxy_ws||this.proxy_wt)&&(re.useWt=!!this.proxy_wt),re.useWt?this.wFSM=new $e(this):this.wFSM=new je(this),this.userManager=new Dr("",this.log_,"tinyId");let a=c=>this.userManager.on(c,_=>this.postMessage({cmd:c,payload:_}));this.userManager.on("3",({flag:c,userId:_,tinyId:m})=>{let d={flag:c,userId:_,tinyId:m,get muteState(){return Pc(this.flag,this.userId)},subscribe:0,removing:!1};this.log_.debug("create user",d),this.postMessage({cmd:"3",payload:d}),this.userManager.addRemotePublishedUser(new vr(d,this))}),a("6"),a("5"),a("1"),a("2"),this.statReportReq={tinyid:"",stat:{msg_audio_stat_report:{msg_audio_enc_stat:{uint32_audio_enc_br:0,uint32_audio_frame_interval:0},msg_audio_send_stat:{uint32_audio_send_br:0,uint32_audio_fec_br:0,uint32_audio_arq_br:0}},rpt_msg_video_stat_report:[{uint32_video_type:2,msg_video_enc_stat:{uint32_video_enc_fps:0,uint32_video_enc_br:0,uint32_video_encrd:1},msg_video_send_stat:{uint32_video_send_br:0,uint32_video_fec_br:0,uint32_video_arq_br:0}}],msg_net_stat_report:{uint32_total_send_br:0,uint32_rtt:0,uint32_down_expect_pkg:0,uint32_down_real_pkg:0,uint32_down_recv_br:0},msg_rtt_info_req:{uint64_last_server_timestamp_ms:0,uint32_delay_since_last_server_timestamp_ms:0,uint64_client_timestamp_ms:0},msg_system_load_report:{uint32_total_cpu_rate:0},msg_down_bandwidth_est:{uint32_bandwidth_br:0,uint32_avg_bandwidth_br:0,uint32_jitter:0,uint32_jitter_in_frm:0},msg_play_report:{uint32_video_jitter_receive_fps_ratio:0}}},this.qualityReportReq={tinyid:"",report:{str_sdk_version:this.joinReq.jsSdkVersion,uint32_groupid:0,uint64_datetime:Date.now(),msg_user_info:{str_identifier:"",uint64_tinyid:0},msg_device_info:{uint32_terminal_type:this.joinReq.AbilityOption.GeneralLimit.uint32_terminal_type,str_device_name:this.browserInfo.browserName,str_os_version:this.osName,uint32_net_type:this.joinReq.AbilityOption.GeneralLimit.uint32_net_type,uint32_app_cpu:0,uint32_system_cpu:0,uint32_app_memory:0,uint32_background:0,uint32_headset:0},msg_up_stream_info:{msg_audio_status:{uint32_audio_format:11,uint32_audio_sample_rate:48e3,uint32_audio_codec_bitrate:0,uint32_audio_receive:0},msg_video_status:[{uint32_video_stream_type:2,uint32_video_decode_frame:0,uint32_video_total_frame:0,uint32_video_capture_fps:0,uint32_video_codec_fps:0,uint32_video_enc_fps:0,uint32_video_codec_bitrate:0,uint32_video_total_bitrate:0}],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0,uint32_jitter:0},msg_qos:[]},msg_down_stream_info:[],msg_event_msg:[],str_acc_ip:"",str_client_ip:"",str_groupid:""}}}get aborted(){return this.abortCtrl.signal.aborted}get wtDomain(){return this.env?`${this.env}.rtc.qq.com:8080`:this.proxy_wt?this.proxy_wt:this.domains.length?`${this.domains[this.selectDomain]}:80`:"wasm.rtc.qq.com:80"}get wsDomain(){return this.env?`${this.env}.rtc.qq.com:8687`:this.proxy_cloud.length?this.proxy_cloud[this.selectCloudDomain].replace("wss://",""):this.proxy_ws?this.proxy_ws:this.domains.length?this.domains[this.selectDomain]:"wasm.rtc.qq.com"}get wtUrl(){return`https://${this.wtDomain}/v1/wt?${this.connectParams}`}get wsUrl(){var r;let e=((r=this.domains)==null?void 0:r[this.selectDomain])||"wasm.rtc.qq.com";return`wss://${this.wsDomain}/v1/ws?${this.connectParams}&realHost=${e}`}async connect(){let e=this.wFSM.connect(),r=(i,a=!1)=>c=>{if(this.aborted||typeof c=="number")throw c;return this.selectDomain=i,this.wFSM=a?new $e(this):new je(this),console.warn(c),console.warn("downgrade to",a?"WebTransport":"WebSocket",this.selectDomain?"\u5907\u7528\u57DF\u540D":"\u4E3B\u57DF\u540D"),this.wFSM.connect()};return re.useWt&&(this.proxy_ws||!this.proxy_wt)&&(e=e.catch(r(0))),!this.proxy_wt&&!this.proxy_ws&&(e=e.catch(r(1,re.useWt)),re.useWt&&(e=e.catch(r(1)))),e}async joinRoom(){let{dataport:e,stunport:r,relayip:i,socketid:a,checkSigSeq:c}=this.signalInfo_,_=await this.sendReq(0,Object.assign(this.joinReq,{dataport:e,stunport:r,relayip:i,socketid:a,checkSigSeq:c}));if(_.err===0)this.setJoinRes(_.data);else throw _.err;return _}async leaveRoom(){return await this.sendReq(1,{}),this.close()}async rejoinRoom(){if(!this.rebuild){let e=await this.sendReq(0,this.joinReq);if(e.err===0)this.setJoinRes(e.data);else return}return this.recovery.recoverLocal()}async reconnect(){return this.postMessage({cmd:"signal-connection-state-changed",payload:{prevState:"DISCONNECTED",state:"RECONNECTING"}}),this.wFSM.connect()}retry(e=0){if(console.log(et(),"retry",e),e>ti){this.close();return}let r=We(xc(e));V(e?Ws(r,this.reconnectOB):r,ur(1),ye(this.reconnectedOB),X(i=>{typeof i!="number"&&this.state==="DISCONNECTED"&&this.retry(e+1)}))}disconnect(e){this.log_.warn("connection lost:",e),this.postMessage({cmd:"signal-connection-state-changed",payload:{prevState:"CONNECTED",state:"DISCONNECTED"}}),this.retry()}close(){this.userManager.clear(),this.port.postMessage(null),this.port.close(),this.wFSM.close()}postMessage(e,r){this.port.postMessage(e,r)}verify(e,r){this.signalInfo_=e,this.rebuild=r,this.reqUser_={openid:e.openid,tinyid:e.tinyid}}async _sendReq(e,r){r.tinyid||(r.reqUser=this.reqUser_);let i=this.generateUUID();return await this.wFSM.sendReq(e,r,i),Ge((a,c)=>this.reqPromise.set(i,{resolve:a,reject:c,startTime:Date.now()}),this.abortCtrl.signal,a=>(console.log("abort",se[e]),{err:a}))}postReq(e,r){return this.wFSM.sendReq(e,r,this.generateUUID())}async sendReq(e,r){return this.recovery.onSendReq(e,r),this._sendReq(e,r)}send(e){return this.wFSM.send(e)}setJoinRes(e){this.joinRes=e,this.userManager.mySelfId=e.tinyid,this.statReportReq.tinyid=e.tinyid,this.qualityReportReq.tinyid=e.tinyid,this.qualityReportReq.report.str_acc_ip=e.relayip,this.qualityReportReq.report.str_client_ip=e.clientip,this.qualityReportReq.report.msg_user_info.str_identifier=e.openid,this.qualityReportReq.report.msg_user_info.uint64_tinyid=Number(e.tinyid),this.tinyId_.set([...e.tinyid].map(r=>r.charCodeAt(0)).concat(0)),[1,2,3,7].forEach(r=>{F._CreateUdtPacketizer(e.roomid,this.tinyId_.point,e.locationid,r,F.udtver,this.id)}),this.wFSM.sendReq(6,{})}onReceive(e,r,i){let a="",c=0,_=new DataView(i.buffer,i.byteOffset);r<255&&(c=_.getUint32(0),i=i.subarray(4)),r<4095&&(a=String.fromCharCode(...i.subarray(0,16)),i=i.subarray(16));let m=i;if(!a)_=new DataView(i.buffer,i.byteOffset,i.byteLength);else{let f="";for(let h=0,R=i.length,U=32768;h<R;h+=U)f+=String.fromCharCode.apply(null,i.subarray(h,Math.min(h+U,R)));if(c)m=f;else try{m=JSON.parse(f)}catch(h){m=f}}let d=se[r];switch(r){case 259:this.joinRes&&this.wFSM.sendReq(r,{tinyid:this.joinRes.tinyid}),console.debug(e,"receive:",d,a,m);break;case 256:m.userlist.forEach(y=>{if(this.userManager.addUser({userId:y.userid,tinyId:y.srctinyid,role:y.role}),this.joinRes&&y.srctinyid!=this.joinRes.tinyid&&this.userManager.userMap.has(y.srctinyid)){let C=this.userManager.userMap.get(y.srctinyid);this.sendSubscribe(C)}}),this.log_.info(e,"receive:",d,a,m),this.wFSM.sendReq(r,{count:this.userManager.userMap.size});break;case 257:this.userManager.deleteUser(m.userlist.srctinyid),this.log_.info(e,"receive:",d,a,m),this.wFSM.sendReq(r,{count:this.userManager.userMap.size});break;case 6:this.userManager.setUserList(m.userlist.map(y=>({userId:y.userid,tinyId:y.srctinyid,role:y.role})));break;case 255:this.wFSM.sendReq(r,{count:this.userManager.userMap.size});{let y=m.userlist.map(C=>({userId:C.userid,tinyId:C.srctinyid,flag:C.flag,terminalType:C.terminaltype}));this.firstReceiveUserlist||(this.firstReceiveUserlist=!0,this.postMessage({cmd:Ye.RECEIVED_PUBLISHED_USER_LIST,payload:{publishedUserList:y}})),this.userManager.setRemotePublishedUserList(y),this.recovery.recovering&&this.recovery.recoverRemote(this.userManager.remotePublishedUserMap)}break;case 4100:this.rtt=_.getUint32(4),console.debug(e,"receive:",d,a,m,this.rtt);let{dv:f,writeData:h}=Ct(4101,8);h(i.subarray(0,4)),this.send(f.buffer);break;case 12:this.reqPromise.forEach(y=>{Date.now()-y.startTime>5e3&&(y.reject(new Error("heartbeat timeout")),this.reqPromise.delete(y.uuid))}),self.postMessage({type:"glog",payload:{heartbeatReceive:1}});case 11:case 260:console.debug(e,"receive:",d,a,m);case 7:case 4095:break;case 4096:case 4097:{let y=i.length;this.statReportReq.stat.msg_net_stat_report.uint32_down_real_pkg++,this.statReportReq.stat.msg_net_stat_report.uint32_down_recv_br+=y<<3;let C=_.getBigUint64(9).toString(),j=this.userManager.getPublishedUser(C);j?r===4096?(j.mainPuller.videoStatus.uint32_video_receive||console.timeLog(`${j.userId}big`,"first video data"),j.mainPuller.demuxPacket(i)):(j.screenPuller.videoStatus.uint32_video_receive||console.timeLog(`${j.userId}aux`,"first video data"),j.screenPuller.demuxPacket(i)):console.warn(e,"receive:",d,a,m,"user not found")}break;case 4102:case 4103:case 4099:break;case 4103:F.HEAPU8.set(i,k.global.point+8);let R=F._ParseUdtMousePacket(k.global.point+8,i.length,k.global.point),U=i.subarray(R),P=k.global.getBigUint64(0).toString(),Y=this.userManager.userMap.get(P);Y&&this.postMessage({cmd:"layerData",payload:{userId:Y.userId,tinyId:P,layerData:U}}),console.debug(e,"receive:",d,R,m,P,U);break;case 4098:{let y=_.getUint8(8);for(let C=9;C<i.length;C+=6){let j=_.getUint32(C),Te=_.getUint16(C+4);for(let Se=0;Se<=16;Se++){if(Se>0&&(Te>>16-Se&1)==0)continue;let Ie=F._GetRetransPacket(y,j+Se,k.global.point,this.id),ie=k.global.getUint32(0),pe=F.HEAPU8.subarray(ie,ie+Ie);Ie>0&&this.send(pe)}}}break;case 1:this.log_.info(e,"receive:",d,a,m),m>0&&m!==3&&(this.postMessage({cmd:"banned",payload:m}),this.close());break;case 258:this.log_.info(e,"receive:",d,a||"",m);break;default:this.log_.info(e,"receive:",d||r,a||"",m)}this.reqPromise.has(a)&&(c&&this.log_.warn(c,m,a),this.reqPromise.get(a).resolve({err:c,data:m,uuid:a}),this.reqPromise.delete(a)),this.emit(d,a?{uuid:a,err:c,data:m}:{data:m})}sendSubscribe(e){let r=e.subscribe;if(r==0)return;let i={mediaType:r,mediaDescription:{audioParam:r&1?{mediaType:1,payloadFmtps:[{payloadType:111,fmtp:"minptime=10;useinbandfec=1"}]}:void 0,videoParam:[4,8,2].filter(a=>r&a).map(a=>({mediaType:a,payloadFmtps:[{payloadType:100,fmtp:"packetization-mode=1;profile-level-id=42e01f"}]}))},userId:e.userId,srctinyid:e.tinyId};this._sendReq(4,i)}createOputReceiver(e){return new ve(this.unMarshal(e))}*unMarshal(e){let r=null,i=new Map;for(;;){let a=0,c=0;try{r=yield 1;let _=r[0]>>4,m=r[0]&2,d=r[0]&1;r=yield 4+d*2;let f=new DataView(r.buffer,r.byteOffset);if(c=f.getUint16(0),a=d==1?f.getUint32(2):f.getUint16(2),r=yield a,m){let h=r[0]&63,R=r[1],U=r.subarray(2,2+R);switch(h){case 1:let P=U[0]>>7,Y=U[0]&127,y=U[1],{dv:C,write8:j}=Ct(4099,2);j(Y),j(y),this.send(C.buffer);let Te=Y%64;for(let Ie=0;Ie<64;Ie++){let ie=Y-Ie;ie<0&&(ie+=64);let pe=Te-Ie;pe<0&&(pe+=64),i.has(pe)&&i.get(pe).groupId!=ie&&i.delete(pe)}let Se=i.get(Te);if(Se||i.set(Te,Se=new is(Y)),r=Se.push(y,r.slice(2+R),P!=0),r)i.delete(Te);else continue}}this.onReceive(e,c,r)}catch(_){this.log_.error(e,_,a,c,r)}}}generateUUID(){return"xxxxxxxxxxxxxxxx".replace(/[xy]/g,e=>{let r=Math.random()*16|0;return(e=="x"?r:r&3|8).toString(16)})}};l(be,"JOINED","joined"),l(be,"CLOSED","closed"),ce([de(Z.INIT,"CONNECTED")],be.prototype,"connect",1),ce([de("CONNECTED",be.JOINED)],be.prototype,"joinRoom",1),ce([de("RECONNECTED",be.JOINED,{fail(){this.close()}})],be.prototype,"rejoinRoom",1),ce([de("DISCONNECTED","RECONNECTED")],be.prototype,"reconnect",1),ce([de([],"DISCONNECTED",{sync:!0})],be.prototype,"disconnect",1),ce([de([],be.CLOSED,{sync:!0})],be.prototype,"close",1);var Ke=be,is=class{constructor(t){this.groupId=t;l(this,"chunks",[]);l(this,"totalLen",0);l(this,"marker",!1)}push(t,e,r){if(this.chunks[t])return null;if(this.chunks[t]=e,this.totalLen+=e.length,r&&(this.chunks.length=t+1,this.marker=!0),this.marker){for(let a=0;a<this.chunks.length;a++)if(!this.chunks[a])return null;let i=new Uint8Array(this.totalLen);for(;this.chunks.length;){let a=this.chunks.pop();i.set(a,this.totalLen-=a.length)}return i}return null}};var qt=class extends he{publishCdn(t,e){return"request_time"in t?(console.info("startPublishTXCDN:",t),this.send(18,t).then(e.postMessage)):(console.info("startPublishCDN:",t),this.send(13,t).then(e.postMessage))}stopPublishCdn(t,e){return"request_time"in t?(console.info("stopPublishTXCDN:",t),this.send(19,t).then(e.postMessage)):(console.info("stopPublishCDN:",t),this.send(14,t).then(e.postMessage))}startMcuMix(t,e){let{inputParam:r,outputParam:i}=t,a={mcuMix:{reqUser:this.io.reqUser_,roomid:t.roomId,sdkAppID:this.appId,socketid:this.io.joinRes.socketid,mcuRequestTime:t.mcuRequestTime,outputSessionId:t.outputSessionId},inputParam:r.map(c=>({userid:c.userId,width:c.width,height:c.height,locationX:c.locationX,locationY:c.locationY,zOrder:c.zOrder,streamType:c.streamType,inputType:c.inputType})),outputParam:{streamId:i.streamId,streamType:i.streamType,videoWidth:i.width,videoHeight:i.height,videoBitrate:i.videoBps,videoFramerate:i.fps,vidoeGOP:i.gop,audioSampleRate:i.audioSampleRate,audioBitrate:i.audioBps,audioChannels:i.audioChannels,backgroundColor:i.backgroundColor,backgroundImage:i.backgroundImg,extraInfo:i.extraInfo,VCodec:i.videoCodec,ACodec:i.audioCodec}};return this.send(15,a).then(e.postMessage)}stopMcuMix(t,e){let r={mcuMix:{reqUser:this.io.reqUser_,roomid:this.roomId,sdkAppID:this.appId,socketid:this.io.joinRes.socketid,mcuRequestTime:t.mcuRequestTime,outputSessionId:t.outputSessionId},userid:this.userId,streamType:t.streamType};return console.info("stop mcuMix:",t),this.send(16,r).then(e.postMessage)}};var Nc=1200;var Dc=31,Cc=6,wc=6;var ji={1:1,audio:1,video:4,2:4,auxVideo:2,7:2,3:8};var v_=Date.now(),U_=Dc+Cc+6+wc+Nc+1;var Wt=class extends he{constructor(){super(...arguments);l(this,"videoEncBuffer_",new k(1920*1080*3>>1));l(this,"videoStats",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0});l(this,"audioStats",{bytesSent:0,packetsSent:0});l(this,"videoTypeIndexMap",new Map([[2,0]]));l(this,"requestTypeMap",new Map([[0,4096]]))}getLocalVideoStats(e){e.postMessage({[this.io.joinRes.openid]:this.videoStats})}getLocalAudioStats(e){e.postMessage({[this.io.joinRes.openid]:this.audioStats})}pushAudio({sampleRate:e,channelCount:r,bitrate:i,index:a},c,_){var U;let m=new k(e*r*2),d=P=>{this.qualityReport.msg_up_stream_info.msg_audio_status.uint32_audio_level=P.volume*1e8/100>>0;let{data:Y}=P,y=Y.length;m.set(Y),this.statReportReq.msg_audio_stat_report.msg_audio_enc_stat.uint32_audio_enc_br+=y<<3,this.statReportReq.msg_audio_stat_report.msg_audio_enc_stat.uint32_audio_frame_interval++,this.audioStats.packetsSent++;let C=F._PacketizeAudioUdt(m.point,y,P.timestamp,e,r,P.energy,k.global.point,k.global.size,this.io.id,!!_);if(C<=0){console.warn("audio pack len is 0");return}this.io.send(k.global.uint8Array(C)),this.audioStats.bytesSent+=C,this.statReportReq.msg_audio_stat_report.msg_audio_send_stat.uint32_audio_send_br+=C<<3,this.qualityReport.msg_up_stream_info.msg_audio_status.uint32_audio_receive++},f=P=>{m.free(),this.send(3,{mediaType:1})},h=new MessageChannel;(U=this.io.wh.playPort)==null||U.postMessage({cmd:"pushAudio",payload:{numberOfChannels:r,bitrate:i},encrypt:!!_,index:a},[h.port2,c.port]);let R=Dt(h.port1);_&&V(R,X()),V(_||R,X(d,f,f))}createSelectAbilityOb(e,r){let i=r.bitrate;return V(this.createResposeOb(259),$s(()=>We(2e3)),ze(a=>{var c;return(c=a.data.ability.rpt_msg_video_control_info)==null?void 0:c.find(_=>_.uint32_video_type===e)}),mt(a=>{if(!a)return!1;let c=a.uint32_video_enc_br,_=c*Math.pow(1-this.qualityReport.msg_up_stream_info.msg_network_status.uint32_lost/100,2),m=Math.min(i,_);a.uint32_video_enc_br=m,this.glog({[`confBr${e}`]:[c,_,m]});let d=!1;return((h,R)=>{a[R]&&a[R]!==r[h]&&(d=!0,r[h]=a[R])})("bitrate","uint32_video_enc_br"),d}),kn(r))}pushVideo({profile:{width:e,height:r,frameRate:i,bitrate:a},type:c,trackType:_,crypto:m},d){this.videoStats.frameWidth=e,this.videoStats.frameHeight=r;let f=0,h=ji[c];this.videoTypeIndexMap.has(c)?f=this.videoTypeIndexMap.get(c):(f=this.statReportReq.rpt_msg_video_stat_report.length,this.requestTypeMap.set(f,c===7?4097:4096),this.videoTypeIndexMap.set(c,f),this.statReportReq.rpt_msg_video_stat_report.push({uint32_video_type:c,msg_video_enc_stat:{uint32_video_enc_fps:0,uint32_video_enc_br:0,uint32_video_encrd:1},msg_video_send_stat:{uint32_video_send_br:0,uint32_video_fec_br:0,uint32_video_arq_br:0}}),this.qualityReport.msg_up_stream_info.msg_video_status.push({uint32_video_codec_bitrate:0,uint32_video_total_bitrate:0,uint32_video_enc_fps:0,uint32_video_capture_fps:0,uint32_video_codec_fps:0,uint32_video_stream_type:c,uint32_video_codec_type:0,uint32_video_decode_frame:0,uint32_video_total_frame:0,uint32_video_width:e,uint32_video_height:r}));let R={width:e,height:r,bitrate:a*1e3,framerate:i};Object.assign(this.qualityReport.msg_up_stream_info.msg_video_status[f],{uint32_video_width:e,uint32_video_height:r});let U=0,P=!1,Y=C=>{this.send(3,{mediaType:h})};V(this.createSelectAbilityOb(c,R),X(()=>{d.postMessage(R)}));let y=d;_!="camera"&&(this.io.log_.info(`push ${_} track`),y=qs(d,V(d,Ks(2e3),Bn(C=>(this.io.log_.warn("start push last video frame"),V(Oe(2e3),kn(C),ye(d),hr({complete:()=>this.io.log_.warn("stop push last video frame")})))),ke(d)))),V(y,X(C=>{let j=this.getVideoStatus(f);j.uint32_video_total_frame++,U++,this.videoStats.framesSent++,j.uint32_video_capture_fps++,U%300==0&&d.postMessage(260),this.handleVideoEncoded(C,c,m)},Y,Y)),V(this.createResposeOb(260),ke(d),X(()=>d.postMessage(260)))}getVideoStatus(e){return this.qualityReport.msg_up_stream_info.msg_video_status[e]}handleVideoEncoded(e,r,i){let{chunk:a,timestamp:c}=e;this.videoStats.framesEncoded++;let _=this.videoTypeIndexMap.get(r),m=this.getVideoStatus(_);m.uint32_video_decode_frame++,m.uint32_video_codec_fps++,m.uint32_video_enc_fps++,this.statReportReq.rpt_msg_video_stat_report[_].msg_video_enc_stat.uint32_video_enc_fps++;let d="byteLength"in a?a.byteLength:a.data.length;if(this.statReportReq.rpt_msg_video_stat_report[_].msg_video_enc_stat.uint32_video_enc_br+=d<<3,d>this.videoEncBuffer_.size){console.log("buffer too small!");return}"byteLength"in a?a.copyTo(this.videoEncBuffer_.uint8Array(d)):this.videoEncBuffer_.set(a.data),k.global.fill();let f=F._PacketizeVideoUdt(this.videoEncBuffer_.point,d,c,a.type=="key"?1:0,r,k.global.point,this.io.id,i);this.sendUdtv3Video(f,_)}sendUdtv3Video(e,r){let i=0,a=k.global.uint8Array();for(let c=0;c<e;c++){let _=k.global.getUint32(i);if(_<=0){this.io.log_.warn("sendUdtv3Video pktSize is ",_);continue}this.io.send(a.subarray(i+=4,i+=_)),this.statReportReq.rpt_msg_video_stat_report[r].msg_video_send_stat.uint32_video_send_br+=_<<3,this.videoStats.bytesSent+=_,this.videoStats.packetsSent++}}mute(e){if(this.send(8,e),e.userId!==this.io.joinRes.openid){let r=this.userMap_.get(e.srctinyid);r&&(r.subscribe&=~e.mediaType)}}unmute(e){if(this.send(9,e),e.userId!==this.io.joinRes.openid){let r=this.userMap_.get(e.srctinyid);r&&(r.subscribe|=e.mediaType)}}waitKeyFrame(e){this.send(11,e)}publish(e,r){this.audioStats.bytesSent=0,this.audioStats.packetsSent=0,this.videoStats.framesSent=0,this.videoStats.bytesSent=0,this.videoStats.packetsSent=0,this.videoStats.framesEncoded=0;let i={mediaType:e,mediaDescription:{audioParam:e&1?{mediaType:1,payloadFmtps:[{payloadType:111,fmtp:"minptime=10;useinbandfec=1"}]}:void 0,videoParam:[4,8,2].filter(a=>e&a).map(a=>({mediaType:a,payloadFmtps:[{payloadType:100,fmtp:"packetization-mode=1;profile-level-id=42e01f"}]}))}};this.send(2,i).then(a=>{r.postMessage(a),r.postMessage(null)})}};var Mc=2,Gt=class extends he{addEventMsgs(t){this.qualityReport.msg_event_msg=t}constructor(t){super(t);let e,r=Ee(t,Ke.JOINED),i=Ee(t,Ke.CLOSED),a={};V(r,Pt(Oe(1e3)),ye(i),X(m=>{let d=Date.now();this.statReportReq.msg_down_bandwidth_est.uint32_avg_bandwidth_br=this.statReportReq.msg_down_bandwidth_est.uint32_bandwidth_br=this.statReportReq.msg_net_stat_report.uint32_down_recv_br,this.statReportReq.msg_rtt_info_req.uint64_client_timestamp_ms=d,this.statReportReq.msg_rtt_info_req.uint32_delay_since_last_server_timestamp_ms=e&&d-e||0,this.statReportReq.msg_net_stat_report.uint32_down_expect_pkg=this.statReportReq.msg_net_stat_report.uint32_down_real_pkg,this.statReportReq.msg_net_stat_report.uint32_total_send_br=this.statReportReq.msg_audio_stat_report.msg_audio_send_stat.uint32_audio_send_br+this.statReportReq.rpt_msg_video_stat_report.reduce((h,R)=>h+R.msg_video_send_stat.uint32_video_send_br,0),a.bandwidth=this.statReportReq.msg_down_bandwidth_est.uint32_avg_bandwidth_br,a.heartbeatSend=1;let f=[this.qualityReport.msg_up_stream_info.msg_audio_status.uint32_audio_codec_bitrate=this.statReportReq.msg_audio_stat_report.msg_audio_enc_stat.uint32_audio_enc_br];this.qualityReport.msg_up_stream_info.msg_video_status.forEach((h,R)=>{let U=this.statReportReq.rpt_msg_video_stat_report[R];h.uint32_video_total_bitrate=U.msg_video_send_stat.uint32_video_send_br,f[U.uint32_video_type==7?3:U.uint32_video_type-1]=h.uint32_video_codec_bitrate=U.msg_video_enc_stat.uint32_video_enc_br}),a.localBr=f,this.qualityReport.msg_up_stream_info.msg_audio_status.uint32_audio_total_bitrate=this.statReportReq.msg_audio_stat_report.msg_audio_send_stat.uint32_audio_send_br,m%2&&this.post(12,this.io.statReportReq),this.statReportReq.msg_audio_stat_report.msg_audio_enc_stat.uint32_audio_frame_interval=0,this.statReportReq.msg_audio_stat_report.msg_audio_send_stat.uint32_audio_send_br=0,this.statReportReq.msg_audio_stat_report.msg_audio_enc_stat.uint32_audio_enc_br=0,this.statReportReq.rpt_msg_video_stat_report.forEach(h=>{h.msg_video_send_stat.uint32_video_send_br=0,h.msg_video_enc_stat.uint32_video_enc_br=0,h.msg_video_enc_stat.uint32_video_enc_fps=0}),this.statReportReq.msg_net_stat_report.uint32_down_recv_br=0}));let c=V(this.createResposeOb(12),hr(m=>{m.err||!m.data||(this.statReportReq.msg_rtt_info_req.uint64_last_server_timestamp_ms=m.data.msg_rtt_info_res.uint64_server_timestamp_ms,e=Date.now(),this.statReportReq.msg_net_stat_report.uint32_rtt=e-m.data.msg_rtt_info_res.uint64_last_client_timestamp_ms-m.data.msg_rtt_info_res.uint32_delay_since_last_client_timestamp_ms,this.statReportReq.msg_net_stat_report.uint32_rtt<0&&(this.statReportReq.msg_net_stat_report.uint32_rtt=30),this.qualityReport.msg_up_stream_info.msg_network_status.uint32_lost=Math.max(0,(m.data.uint32_up_expect_pkg-m.data.uint32_up_real_pkg)*100/m.data.uint32_up_expect_pkg>>0))}));V(r,Pt(c),Pt(We(Zs)),ye(i),X(()=>{this.io.log_.warn("ping timeout,lastrecv:",e,"now:",Date.now()),this.io.state==Ke.JOINED&&this.io.wFSM.disconnect("ping timeout")}));let _=new k(52);V(r,Pt(Oe(Mc*1e3)),ye(i),X(m=>{let d=[...this.userMap_.values()];this.qualityReport.uint64_datetime=Date.now(),this.qualityReport.msg_up_stream_info.msg_network_status.uint32_bitrate=this.statReportReq.msg_net_stat_report.uint32_total_send_br,this.qualityReport.msg_up_stream_info.msg_network_status.uint32_rtt=this.statReportReq.msg_net_stat_report.uint32_rtt,this.qualityReport.msg_down_stream_info=d.map(P=>{var C,j;let Y=P.toDownStreamInfo(P,m%10===0),y=[Y.msg_audio_status.uint32_audio_codec_bitrate];return y[1]=Y.msg_video_status[0].uint32_video_codec_bitrate,y[2]=((C=Y.msg_video_status[1])==null?void 0:C.uint32_video_codec_bitrate)||0,a[`RemoteBr_${P.userId}`]=y,a[`RemoteBlock_${P.userId}`]=[Y.msg_audio_status.uint32_audio_block_cnt,Y.msg_video_status[0].uint32_video_block_cnt,((j=Y.msg_video_status[1])==null?void 0:j.uint32_video_block_cnt)||0],Y}),this.glog(a),a={};let f=this.qualityReport.msg_down_stream_info.map(P=>({userId:P.msg_user_info.str_identifier,rtt:P.msg_network_status.uint32_rtt,loss:P.msg_network_status.uint32_lost})),h=Lc(f),R=this.qualityReport.msg_up_stream_info.msg_network_status.uint32_rtt,U=this.qualityReport.msg_up_stream_info.msg_network_status.uint32_lost;this.postMessage("network-quality",{uplinkNetworkQuality:this.io.state!="DISCONNECTED"?$i(U,R):6,downlinkNetworkQuality:$i(h.loss,h.rtt),uplinkInfo:this.qualityReport.msg_up_stream_info,msg_down_stream_info:this.qualityReport.msg_down_stream_info,downlinkInfo:f,uplinkRTT:R,uplinkLoss:U,downlinkRTT:h.rtt,downlinkLoss:h.loss}),this.qualityReport.msg_up_stream_info.msg_video_status.forEach(P=>{P.uint32_video_capture_fps>>=1,P.uint32_video_codec_fps>>=1,m%10===0&&console.log(et(),"video uplink fps:",P.uint32_video_stream_type,P.uint32_video_capture_fps,P.uint32_video_codec_fps)}),this.post(7,this.io.qualityReportReq),this.qualityReport.msg_event_msg=[],this.qualityReport.msg_up_stream_info.msg_audio_status.uint32_audio_level=0,this.qualityReport.msg_up_stream_info.msg_video_status.forEach(P=>{P.uint32_video_capture_fps=0,P.uint32_video_codec_fps=0,P.uint32_video_enc_fps=0})},m=>{},()=>{this.qualityReport.msg_down_stream_info=[...this.userMap_.values()].map(m=>m.toDownStreamInfo(m,!1)),this.post(7,this.io.qualityReportReq),_.free()}))}};function Lc(n){let t={rtt:0,loss:0};return Array.isArray(n)&&n.length>0&&(n.forEach(e=>{t.rtt+=e.rtt,t.loss+=e.loss}),Object.keys(t).forEach(e=>{t[e]=Math.round(t[e]/n.length)})),t}function $i(n,t){return n>50||t>500?5:n>30||t>350?4:n>20||t>200?3:n>10||t>100?2:n>=0||t>=0?1:0}var jt=class extends he{async subscribe(t,e){let{mediaType:r,srctinyid:i}=t,a=this.userMap_.get(i);if(a){if(a.subscribe|=t.mediaType,t.mediaType=a.subscribe,e)e.postMessage(await this.send(4,t));else return this.send(4,t);r===1&&a.startPullOnlyAudio(a.mainPuller,e,{mediaType:r,srctinyid:i})}}async unSubscribe(t,e){let{mediaType:r,srctinyid:i}=t,a=this.userMap_.get(i);if(a){let c=a.subscribe;a.subscribe&=~r,c!==a.subscribe&&e.postMessage(await(a.subscribe===0?this.send(5,t):this.io.sendSubscribe(a)))}}pullVideo({mediaType:t,tinyId:e},r){let i=this.userMap_.get(e);i&&i.startPull(t===2?i.screenPuller:i.mainPuller,r,{mediaType:t,srctinyid:e})}changetype(t){let{mediaType:e,srctinyid:r}=t,i=this.userMap_.get(r);if(i){let a=i.subscribe;e===8?(i.subscribe|=8,i.subscribe&=-5):e===4&&(i.subscribe|=4,i.subscribe&=-9),a!=i.subscribe&&(t.mediaType=i.subscribe,this.send(4,t))}}};var os=class extends Lt{constructor(e,r,i,a){super();this.seq=e;this.player=r;this.numberOfChannels=i;this.bitrate=a;l(this,"aecPtr");l(this,"encodePrt");l(this,"tenms",sampleRate/100);l(this,"numberOfFrames",this.tenms<<1);l(this,"float32Array");l(this,"pos",0);l(this,"bufferLen",0);l(this,"outputPort");l(this,"mainPort");l(this,"workerPort");l(this,"outPrt");l(this,"audioCaptBuff");l(this,"oput");l(this,"first10ms");l(this,"dumpPort");l(this,"encodeCount",0);this.wasmBinary=r.wasm}reset(){this.encodeCount=0}print(e){console.debug(e)}printErr(e){console.debug(e)}onRuntimeInitialized(){this.aecPtr=this._malloc(1920*10),this.encodePrt=this._malloc(1920*4),this.outPrt=this._malloc(1920*4),this.float32Array=new Float32Array(this.HEAPU8.buffer,this.encodePrt),this._CreateMediaProcessing(0,1,0,!1),this._UseAINS(re.useAINS),this._SetAudioFrameFormat(sampleRate,this.numberOfChannels),this._InitOpusEncoder(sampleRate,this.numberOfChannels,1),this.bitrate&&this._SetOpusEncBitrate(this.bitrate*1e3),console.log(Ze,"audio worklet initialized",sampleRate,this.numberOfChannels,this.seq),this.oput=new ve,this.oput.buffer=new Uint8Array(this.HEAPU8.buffer,this.encodePrt),this.player.encoders[this.seq]=this}aec(e){return this.HEAPU8.set(e,this.aecPtr),this._AudioReverseProcessFloat(this.aecPtr,e.length>>2),this.HEAPU8.subarray(this.aecPtr,this.aecPtr+e.length)}encode(...e){if(!this.bitrate)return;let r=this.encodePrt;for(let i of e){this.float32Array.set(i,this.bufferLen),this.bufferLen+=i.length;let a=0;for(;this.bufferLen-this.pos>=this.tenms;){let c=this.player.delay+(this.bufferLen-this.pos)/(sampleRate/1e3)+20>>0,_=this._AudioProcessFloat(this.encodePrt+this.pos*4,this.tenms,c);if(a<_&&(a=_),this.pos+=this.tenms,this.pos>=this.numberOfFrames){if(this.dumpPort){let h=this.float32Array.slice(0,this.numberOfFrames);this.dumpPort.postMessage({data:h},[h.buffer])}let m=this._OpusEncode(this.encodePrt,this.numberOfFrames,this.outPrt);this.encodeCount++,this.encodeCount<10&&console.log("audio encoded",this.encodeCount,m);let d=this.HEAPU8.slice(this.outPrt,this.outPrt+m),f=a*100/32768;this.mainPort.postMessage(f),this.outputPort.postMessage({data:d,volume:f,energy:a,timestamp:Date.now()},[d.buffer]),a=0,this.float32Array.copyWithin(0,this.numberOfFrames,this.bufferLen),this.bufferLen-=this.numberOfFrames,this.pos-=this.numberOfFrames}}break}}close(){this._free(this.aecPtr),this._free(this.encodePrt)}};function Yi(n){class t extends AudioWorkletProcessor{constructor(i){super();l(this,"oput",new ve);l(this,"wasm");l(this,"encoders",[]);l(this,"useAINS",!0);console.log("worklet created:",sampleRate),this.wasm=i.processorOptions.wasm,Object.assign(re,i.processorOptions.flag),this.port.onmessage=a=>this.pushAudio(a)}get delay(){var i;return(((i=this.oput.buffer)==null?void 0:i.length)||0)/(sampleRate*4/1e3)}process(i,a){return this.oput.demand(a[0][0],!0),this.encoders.forEach((c,_)=>c.encode(...i[_])),!0}pushAudio(i){if(i.data instanceof Uint8Array){let{data:a}=i;this.encoders.forEach(c=>a=c.aec(i.data)),this.oput.malloc(a.length).set(a);return}switch(console.log("worklet receive",i.data.cmd),i.data.cmd){case"dump":switch(i.data.payload){case"mic0":this.encoders[0].dumpPort=i.ports[0];break}break;case"useAINS":re.useAINS=i.data.payload,this.encoders.forEach(a=>a._UseAINS(i.data.payload));break;case"enableAEC":this.encoders.forEach(a=>a._EnableAEC(i.data.payload));break;case"enableDebug":console.debug=i.data.payload?Sr:()=>{};break;case"pushAudio":{let[a,c]=i.ports,{payload:{numberOfChannels:_,bitrate:m},encrypt:d,index:f}=i.data,h=this.encoders[f]||new os(f,this,_,m);this.encoders[f]?(h.bitrate=m,h._SetOpusEncBitrate(m*1e3)):n(h),h.reset(),h.mainPort=c,h.workerPort=a,h.outputPort=d?c:a,c.onmessage=R=>{R.data?h.encode(R.data):(console.log(et(),"encoder",f,"stopped"),a.postMessage(null))}}}}}registerProcessor("global-audio-player",t)}var as=class{constructor(){l(this,"playPort");l(this,"dumpPort");l(this,"downlinkAudioCount",0);l(this,"interval10ms",V(lt(10),qe()));l(this,"ios")}glog(t){self.postMessage({type:"glog",payload:t})}async joinRoom(t){let{data:{id:e,payload:r},ports:i}=t,a=new Ke(e,i[0],r);a.wh=this;let c=[new Wt(a),new jt(a),new kt(a),new Gt(a),new qt(a)],_=(d="leave room")=>{a.leaveRoom().catch(),a.abort(d),this.ios.delete(a)},m=setTimeout(a.abort,5e3,"timeout");V(Dt(a.port,!0),X(({data:{cmd:d,payload:f},ports:h})=>{switch(console.log(self.name,"received message",d),d){case"setAudioWorkletPort":this.playPort=h[0];break;case"switchRole":a.sendReq(20,{role:f,privateMapKey:a.params.privateMapKey}).then(U=>h[0].postMessage(U));break;default:let R=h.map(U=>Dt(U));typeof f!="undefined"&&R.unshift(f),c.forEach(U=>{var P;(P=U[d])==null||P.call(U,...R)})}},_,_));try{await a.connect(),postMessage({id:e,payload:await a.joinRoom()}),clearTimeout(m),this.ios.add(a)}catch(d){d instanceof WebTransportError?d=`Transport initialization failed.
|
|
3
|
+
Reason: ${d.message}.
|
|
4
|
+
Source: ${d.source}.
|
|
5
|
+
Error code: ${d.streamErrorCode}.`:d instanceof tt?d=d.cause:d instanceof Event&&(d=d.type),postMessage({id:e,payload:{err:d}}),a.close()}}};function Bc(n){self.onmessage=async t=>{let e=setTimeout(()=>{self.postMessage({type:"error",payload:"timeout"})},5e3);try{t.data.wasm&&(F.wasmBinary=t.data.wasm),Object.assign(re,t.data.flag),console.time(`Worker[${self.name}${Ze}]`),F.postRun=[()=>{k.global=new k(1920*1080*3>>1),F._CreateMediaProcessing(0,1,0,!1),console.timeEnd(`Worker[${self.name}${Ze}]`),F._UseAINS(re.useAINS),this.ios=new Set,t.ports[0].onmessage=m=>{var h,R,U;let[d,f]=m.data;switch(d){case"dump":switch(f){case"audio":this.dumpPort=m.ports[0];break;case"mic0":(h=this.playPort)==null||h.postMessage({cmd:d,payload:f},m.ports);break}break;case"useAINS":F._UseAINS(f),(R=this.playPort)==null||R.postMessage({cmd:d,payload:f});break;case"enableDebug":console.debug=f?Sr:()=>{},(U=this.playPort)==null||U.postMessage({cmd:d,payload:f});break;case"useV2":F.udtver=f?2:3;break;case"useWt":re.useWt=f;break;case"enableAEC":F._EnableAEC(f);break}};let r=0,i=Date.now(),a=0;V(Oe(1e3),X(()=>{let f=(Date.now()-i)/10-r;console.debug("interval10ms:",f,f-a),a=f,F._UpdateStreamSync()})),F._SetAudioOutStreamFormat(48e3,1);let c=F._malloc(3*4),_=new k(1920);V(this.interval10ms,X(()=>{if(r++,F._GetAudioMixedFloat(_.point,48e3,c)>=0){if(this.playPort){let d=_.uint8Slice();this.playPort.postMessage(d,[d.buffer])}if(this.dumpPort){let d=_.uint8Slice();this.dumpPort.postMessage(d,[d.buffer])}this.ios.forEach(d=>d.userManager.remotePublishedUserMap.forEach(f=>{var h;return(h=f.audioPuller)==null?void 0:h.feed()}))}})),self.onmessage=this.joinRoom.bind(this),clearTimeout(e),self.postMessage({type:"ready"})}],n(F)}catch(r){self.postMessage({type:"error",err:r})}}}var Ki=br?Yi:Bc.bind(new as);var Vc=function(){var n=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return function(e){e=e||{};var e=typeof e!="undefined"?e:{},r,i;e.ready=new Promise(function(s,o){r=s,i=o});var a={},c;for(c in e)e.hasOwnProperty(c)&&(a[c]=e[c]);var _=[],m="./this.program",d=function(s,o){throw o},f=typeof window=="object",h=typeof importScripts=="function",R=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",U=!f&&!R&&!h,P="";function Y(s){return e.locateFile?e.locateFile(s,P):P+s}var y,C,j,Te;function Se(s){if(!(s instanceof fu)){var o=s;ie("exiting due to exception: "+o)}}U?(typeof read!="undefined"&&(y=function(o){return read(o)}),j=function(o){var u;return typeof readbuffer=="function"?new Uint8Array(readbuffer(o)):(u=read(o,"binary"),cs(typeof u=="object"),u)},C=function(o,u,p){setTimeout(function(){u(j(o))},0)},typeof scriptArgs!="undefined"?_=scriptArgs:typeof arguments!="undefined"&&(_=arguments),typeof quit=="function"&&(d=function(s,o){Se(o),quit(s)}),typeof print!="undefined"&&(typeof console=="undefined"&&(console={}),console.log=print,console.warn=console.error=typeof printErr!="undefined"?printErr:print)):(f||h)&&(h?P=self.location.href:typeof document!="undefined"&&document.currentScript&&(P=document.currentScript.src),n&&(P=n),P.indexOf("blob:")!==0?P=P.substr(0,P.replace(/[?#].*/,"").lastIndexOf("/")+1):P="",y=function(s){var o=new XMLHttpRequest;return o.open("GET",s,!1),o.send(null),o.responseText},h&&(j=function(s){var o=new XMLHttpRequest;return o.open("GET",s,!1),o.responseType="arraybuffer",o.send(null),new Uint8Array(o.response)}),C=function(s,o,u){var p=new XMLHttpRequest;p.open("GET",s,!0),p.responseType="arraybuffer",p.onload=function(){if(p.status==200||p.status==0&&p.response){o(p.response);return}u()},p.onerror=u,p.send(null)},Te=function(s){document.title=s});var Ie=e.print||console.log.bind(console),ie=e.printErr||console.warn.bind(console);for(c in a)a.hasOwnProperty(c)&&(e[c]=a[c]);a=null,e.arguments&&(_=e.arguments),e.thisProgram&&(m=e.thisProgram),e.quit&&(d=e.quit);function pe(s){pe.shown||(pe.shown={}),pe.shown[s]||(pe.shown[s]=1,ie(s))}function Xi(s,o){if(typeof WebAssembly.Function=="function"){for(var u={i:"i32",j:"i64",f:"f32",d:"f64"},p={parameters:[],results:o[0]=="v"?[]:[u[o[0]]]},b=1;b<o.length;++b)p.parameters.push(u[o[b]]);return new WebAssembly.Function(p,s)}var E=[1,0,1,96],T=o.slice(0,1),I=o.slice(1),S={i:127,j:126,f:125,d:124};E.push(I.length);for(var b=0;b<I.length;++b)E.push(S[I[b]]);T=="v"?E.push(0):E=E.concat([1,S[T]]),E[1]=E.length-2;var O=new Uint8Array([0,97,115,109,1,0,0,0].concat(E,[2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0])),H=new WebAssembly.Module(O),K=new WebAssembly.Instance(H,{e:{f:s}}),q=K.exports.f;return q}var Mr=[],Je;function Qi(){if(Mr.length)return Mr.pop();try{st.grow(1)}catch(s){throw s instanceof RangeError?"Unable to grow wasm table. Set ALLOW_TABLE_GROWTH.":s}return st.length-1}function zi(s,o){for(var u=s;u<s+o;u++){var p=Kt(u);p&&Je.set(p,u)}}function Zi(s,o){if(Je||(Je=new WeakMap,zi(0,st.length)),Je.has(s))return Je.get(s);var u=Qi();try{As(u,s)}catch(b){if(!(b instanceof TypeError))throw b;var p=Xi(s,o);As(u,p)}return Je.set(s,u),u}function eo(s){Je.delete(Kt(s)),Mr.push(s)}var At;e.wasmBinary&&(At=e.wasmBinary);var Fc=e.noExitRuntime||!1;typeof WebAssembly!="object"&&it("no native wasm support detected");var $t,us=!1,to;function cs(s,o){s||it("Assertion failed: "+o)}function A(s){var o=e["_"+s];return cs(o,"Cannot call unknown function "+s+", make sure it is exported"),o}function ls(s,o,u,p,b){var E={string:function(W){var te=0;if(W!=null&&W!==0){var $=(W.length<<2)+1;te=Xr($),ps(W,te,$)}return te},array:function(W){var te=Xr(W.length);return hs(W,te),te}};function T(W){return o==="string"?yt(W):o==="boolean"?!!W:W}var I=A(s),S=[],O=0;if(p)for(var H=0;H<p.length;H++){var K=E[u[H]];K?(O===0&&(O=Ms()),S[H]=K(p[H])):S[H]=p[H]}var q=I.apply(null,S);function Q(W){return O!==0&&Ls(O),T(W)}return q=Q(q),q}function ro(s,o,u,p){u=u||[];var b=u.every(function(T){return T==="number"}),E=o!=="string";return E&&b&&!p?A(s):function(){return ls(s,o,u,arguments,p)}}var ms=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):void 0;function Lr(s,o,u){for(var p=o+u,b=o;s[b]&&!(b>=p);)++b;if(b-o>16&&s.subarray&&ms)return ms.decode(s.subarray(o,b));for(var E="";o<b;){var T=s[o++];if(!(T&128)){E+=String.fromCharCode(T);continue}var I=s[o++]&63;if((T&224)==192){E+=String.fromCharCode((T&31)<<6|I);continue}var S=s[o++]&63;if((T&240)==224?T=(T&15)<<12|I<<6|S:T=(T&7)<<18|I<<12|S<<6|s[o++]&63,T<65536)E+=String.fromCharCode(T);else{var O=T-65536;E+=String.fromCharCode(55296|O>>10,56320|O&1023)}}return E}function yt(s,o){return s?Lr(oe,s,o):""}function ds(s,o,u,p){if(!(p>0))return 0;for(var b=u,E=u+p-1,T=0;T<s.length;++T){var I=s.charCodeAt(T);if(I>=55296&&I<=57343){var S=s.charCodeAt(++T);I=65536+((I&1023)<<10)|S&1023}if(I<=127){if(u>=E)break;o[u++]=I}else if(I<=2047){if(u+1>=E)break;o[u++]=192|I>>6,o[u++]=128|I&63}else if(I<=65535){if(u+2>=E)break;o[u++]=224|I>>12,o[u++]=128|I>>6&63,o[u++]=128|I&63}else{if(u+3>=E)break;o[u++]=240|I>>18,o[u++]=128|I>>12&63,o[u++]=128|I>>6&63,o[u++]=128|I&63}}return o[u]=0,u-b}function ps(s,o,u){return ds(s,oe,o,u)}function _s(s){for(var o=0,u=0;u<s.length;++u){var p=s.charCodeAt(u);p>=55296&&p<=57343&&(p=65536+((p&1023)<<10)|s.charCodeAt(++u)&1023),p<=127?++o:p<=2047?o+=2:p<=65535?o+=3:o+=4}return o}var fs=typeof TextDecoder!="undefined"?new TextDecoder("utf-16le"):void 0;function no(s,o){for(var u=s,p=u>>1,b=p+o/2;!(p>=b)&&Yt[p];)++p;if(u=p<<1,u-s>32&&fs)return fs.decode(oe.subarray(s,u));for(var E="",T=0;!(T>=o/2);++T){var I=nt[s+T*2>>1];if(I==0)break;E+=String.fromCharCode(I)}return E}function so(s,o,u){if(u===void 0&&(u=2147483647),u<2)return 0;u-=2;for(var p=o,b=u<s.length*2?u/2:s.length,E=0;E<b;++E){var T=s.charCodeAt(E);nt[o>>1]=T,o+=2}return nt[o>>1]=0,o-p}function io(s){return s.length*2}function oo(s,o){for(var u=0,p="";!(u>=o/4);){var b=L[s+u*4>>2];if(b==0)break;if(++u,b>=65536){var E=b-65536;p+=String.fromCharCode(55296|E>>10,56320|E&1023)}else p+=String.fromCharCode(b)}return p}function ao(s,o,u){if(u===void 0&&(u=2147483647),u<4)return 0;for(var p=o,b=p+u-4,E=0;E<s.length;++E){var T=s.charCodeAt(E);if(T>=55296&&T<=57343){var I=s.charCodeAt(++E);T=65536+((T&1023)<<10)|I&1023}if(L[o>>2]=T,o+=4,o+4>b)break}return L[o>>2]=0,o-p}function uo(s){for(var o=0,u=0;u<s.length;++u){var p=s.charCodeAt(u);p>=55296&&p<=57343&&++u,o+=4}return o}function hs(s,o){z.set(s,o)}function co(s,o,u){for(var p=0;p<s.length;++p)z[o++>>0]=s.charCodeAt(p);u||(z[o>>0]=0)}function x(s,o){return s%o>0&&(s+=o-s%o),s}var kr,z,oe,nt,Yt,L,Ce,bs,Br;function gs(s){kr=s,e.HEAP8=z=new Int8Array(s),e.HEAP16=nt=new Int16Array(s),e.HEAP32=L=new Int32Array(s),e.HEAPU8=oe=new Uint8Array(s),e.HEAPU16=Yt=new Uint16Array(s),e.HEAPU32=Ce=new Uint32Array(s),e.HEAPF32=bs=new Float32Array(s),e.HEAPF64=Br=new Float64Array(s)}var Hc=e.INITIAL_MEMORY||134217728,st,Es=[],Ts=[],lo=[],Ss=[],mo=!1;function po(){if(e.preRun)for(typeof e.preRun=="function"&&(e.preRun=[e.preRun]);e.preRun.length;)ho(e.preRun.shift());Fr(Es)}function _o(){mo=!0,Fr(Ts)}function fo(){if(e.postRun)for(typeof e.postRun=="function"&&(e.postRun=[e.postRun]);e.postRun.length;)go(e.postRun.shift());Fr(Ss)}function ho(s){Es.unshift(s)}function bo(s){Ts.unshift(s)}function go(s){Ss.unshift(s)}var Xe=0,Vr=null,Ot=null;function Eo(s){Xe++,e.monitorRunDependencies&&e.monitorRunDependencies(Xe)}function To(s){if(Xe--,e.monitorRunDependencies&&e.monitorRunDependencies(Xe),Xe==0&&(Vr!==null&&(clearInterval(Vr),Vr=null),Ot)){var o=Ot;Ot=null,o()}}e.preloadedImages={},e.preloadedAudios={};function it(s){e.onAbort&&e.onAbort(s),s="Aborted("+s+")",ie(s),us=!0,to=1,s+=". Build with -s ASSERTIONS=1 for more info.";var o=new WebAssembly.RuntimeError(s);throw i(o),o}var So="data:application/octet-stream;base64,";function Is(s){return s.startsWith(So)}var Re;Re="av_processing.wasm",Is(Re)||(Re=Y(Re));function Rs(s){try{if(s==Re&&At)return new Uint8Array(At);if(j)return j(s);throw"both async and sync fetching of the wasm failed"}catch(o){it(o)}}function Io(){return!At&&(f||h)&&typeof fetch=="function"?fetch(Re,{credentials:"same-origin"}).then(function(s){if(!s.ok)throw"failed to load wasm binary file at '"+Re+"'";return s.arrayBuffer()}).catch(function(){return Rs(Re)}):Promise.resolve().then(function(){return Rs(Re)})}function Ro(){var s={a:Oa};function o(T,I){var S=T.exports;e.asm=S,$t=e.asm.B,gs($t.buffer),st=e.asm.na,bo(e.asm.C),To("wasm-instantiate")}Eo("wasm-instantiate");function u(T){o(T.instance)}function p(T){return Io().then(function(I){return WebAssembly.instantiate(I,s)}).then(function(I){return I}).then(T,function(I){ie("failed to asynchronously prepare wasm: "+I),it(I)})}function b(){return!At&&typeof WebAssembly.instantiateStreaming=="function"&&!Is(Re)&&typeof fetch=="function"?fetch(Re,{credentials:"same-origin"}).then(function(T){var I=WebAssembly.instantiateStreaming(T,s);return I.then(u,function(S){return ie("wasm streaming compile failed: "+S),ie("falling back to ArrayBuffer instantiation"),p(u)})}):p(u)}if(e.instantiateWasm)try{var E=e.instantiateWasm(s,o);return E}catch(T){return ie("Module.instantiateWasm callback failed with error: "+T),!1}return b().catch(i),{}}function Fr(s){for(;s.length>0;){var o=s.shift();if(typeof o=="function"){o(e);continue}var u=o.func;typeof u=="number"?o.arg===void 0?Kt(u)():Kt(u)(o.arg):u(o.arg===void 0?null:o.arg)}}function Kt(s){return st.get(s)}function Ao(){var s=new Error;if(!s.stack){try{throw new Error}catch(o){s=o}if(!s.stack)return"(no stack trace available)"}return s.stack.toString()}function As(s,o){st.set(s,o)}function yo(s){return er(s+16)+16}function Oo(s,o){lo.unshift({func:s,arg:o})}function vo(s,o){return Oo(s,o)}function Uo(s){this.excPtr=s,this.ptr=s-16,this.set_type=function(o){L[this.ptr+4>>2]=o},this.get_type=function(){return L[this.ptr+4>>2]},this.set_destructor=function(o){L[this.ptr+8>>2]=o},this.get_destructor=function(){return L[this.ptr+8>>2]},this.set_refcount=function(o){L[this.ptr>>2]=o},this.set_caught=function(o){o=o?1:0,z[this.ptr+12>>0]=o},this.get_caught=function(){return z[this.ptr+12>>0]!=0},this.set_rethrown=function(o){o=o?1:0,z[this.ptr+13>>0]=o},this.get_rethrown=function(){return z[this.ptr+13>>0]!=0},this.init=function(o,u){this.set_type(o),this.set_destructor(u),this.set_refcount(0),this.set_caught(!1),this.set_rethrown(!1)},this.add_ref=function(){var o=L[this.ptr>>2];L[this.ptr>>2]=o+1},this.release_ref=function(){var o=L[this.ptr>>2];return L[this.ptr>>2]=o-1,o===1}}var xo=0,Po=0;function No(s,o,u){var p=new Uo(s);throw p.init(o,u),xo=s,Po++,s}function Do(s,o,u,p,b){}function Hr(s){switch(s){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError("Unknown type size: "+s)}}function Co(){for(var s=new Array(256),o=0;o<256;++o)s[o]=String.fromCharCode(o);ys=s}var ys=void 0;function Be(s){for(var o="",u=s;oe[u];)o+=ys[oe[u++]];return o}var qr={},Os={},wo={},Mo=48,Lo=57;function ko(s){if(s===void 0)return"_unknown";s=s.replace(/[^a-zA-Z0-9_]/g,"$");var o=s.charCodeAt(0);return o>=Mo&&o<=Lo?"_"+s:s}function Bo(s,o){return s=ko(s),new Function("body","return function "+s+`() {
|
|
6
|
+
"use strict"; return body.apply(this, arguments);
|
|
7
|
+
};
|
|
8
|
+
`)(o)}function vs(s,o){var u=Bo(o,function(p){this.name=o,this.message=p;var b=new Error(p).stack;b!==void 0&&(this.stack=this.toString()+`
|
|
9
|
+
`+b.replace(/^Error(:[^\n]*)?\n/,""))});return u.prototype=Object.create(s.prototype),u.prototype.constructor=u,u.prototype.toString=function(){return this.message===void 0?this.name:this.name+": "+this.message},u}var Us=void 0;function ot(s){throw new Us(s)}var Vo=void 0;function Ve(s,o,u){if(u=u||{},!("argPackAdvance"in o))throw new TypeError("registerType registeredInstance requires argPackAdvance");var p=o.name;if(s||ot('type "'+p+'" must have a positive integer typeid pointer'),Os.hasOwnProperty(s)){if(u.ignoreDuplicateRegistrations)return;ot("Cannot register type '"+p+"' twice")}if(Os[s]=o,delete wo[s],qr.hasOwnProperty(s)){var b=qr[s];delete qr[s],b.forEach(function(E){E()})}}function Fo(s,o,u,p,b){var E=Hr(u);o=Be(o),Ve(s,{name:o,fromWireType:function(T){return!!T},toWireType:function(T,I){return I?p:b},argPackAdvance:8,readValueFromPointer:function(T){var I;if(u===1)I=z;else if(u===2)I=nt;else if(u===4)I=L;else throw new TypeError("Unknown boolean type size: "+o);return this.fromWireType(I[T>>E])},destructorFunction:null})}var Wr=[],Ue=[{},{value:void 0},{value:null},{value:!0},{value:!1}];function Ho(s){s>4&&--Ue[s].refcount===0&&(Ue[s]=void 0,Wr.push(s))}function qo(){for(var s=0,o=5;o<Ue.length;++o)Ue[o]!==void 0&&++s;return s}function Wo(){for(var s=5;s<Ue.length;++s)if(Ue[s]!==void 0)return Ue[s];return null}function Go(){e.count_emval_handles=qo,e.get_first_emval=Wo}var xs={toValue:function(s){return s||ot("Cannot use deleted val. handle = "+s),Ue[s].value},toHandle:function(s){switch(s){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:{var o=Wr.length?Wr.pop():Ue.length;return Ue[o]={refcount:1,value:s},o}}}};function Gr(s){return this.fromWireType(Ce[s>>2])}function jo(s,o){o=Be(o),Ve(s,{name:o,fromWireType:function(u){var p=xs.toValue(u);return Ho(u),p},toWireType:function(u,p){return xs.toHandle(p)},argPackAdvance:8,readValueFromPointer:Gr,destructorFunction:null})}function jr(s){if(s===null)return"null";var o=typeof s;return o==="object"||o==="array"||o==="function"?s.toString():""+s}function $o(s,o){switch(o){case 2:return function(u){return this.fromWireType(bs[u>>2])};case 3:return function(u){return this.fromWireType(Br[u>>3])};default:throw new TypeError("Unknown float type: "+s)}}function Yo(s,o,u){var p=Hr(u);o=Be(o),Ve(s,{name:o,fromWireType:function(b){return b},toWireType:function(b,E){if(typeof E!="number"&&typeof E!="boolean")throw new TypeError('Cannot convert "'+jr(E)+'" to '+this.name);return E},argPackAdvance:8,readValueFromPointer:$o(o,p),destructorFunction:null})}function Ko(s,o,u){switch(o){case 0:return u?function(b){return z[b]}:function(b){return oe[b]};case 1:return u?function(b){return nt[b>>1]}:function(b){return Yt[b>>1]};case 2:return u?function(b){return L[b>>2]}:function(b){return Ce[b>>2]};default:throw new TypeError("Unknown integer type: "+s)}}function Jo(s,o,u,p,b){o=Be(o),b===-1&&(b=4294967295);var E=Hr(u),T=function(O){return O};if(p===0){var I=32-8*u;T=function(O){return O<<I>>>I}}var S=o.includes("unsigned");Ve(s,{name:o,fromWireType:T,toWireType:function(O,H){if(typeof H!="number"&&typeof H!="boolean")throw new TypeError('Cannot convert "'+jr(H)+'" to '+this.name);if(H<p||H>b)throw new TypeError('Passing a number "'+jr(H)+'" from JS side to C/C++ side to an argument of type "'+o+'", which is outside the valid range ['+p+", "+b+"]!");return S?H>>>0:H|0},argPackAdvance:8,readValueFromPointer:Ko(o,E,p!==0),destructorFunction:null})}function Xo(s,o,u){var p=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],b=p[o];function E(T){T=T>>2;var I=Ce,S=I[T],O=I[T+1];return new b(kr,O,S)}u=Be(u),Ve(s,{name:u,fromWireType:E,argPackAdvance:8,readValueFromPointer:E},{ignoreDuplicateRegistrations:!0})}function Qo(s,o){o=Be(o);var u=o==="std::string";Ve(s,{name:o,fromWireType:function(p){var b=Ce[p>>2],E;if(u)for(var T=p+4,I=0;I<=b;++I){var S=p+4+I;if(I==b||oe[S]==0){var O=S-T,H=yt(T,O);E===void 0?E=H:(E+="\0",E+=H),T=S+1}}else{for(var K=new Array(b),I=0;I<b;++I)K[I]=String.fromCharCode(oe[p+4+I]);E=K.join("")}return Fe(p),E},toWireType:function(p,b){b instanceof ArrayBuffer&&(b=new Uint8Array(b));var E,T=typeof b=="string";T||b instanceof Uint8Array||b instanceof Uint8ClampedArray||b instanceof Int8Array||ot("Cannot pass non-string to std::string"),u&&T?E=function(){return _s(b)}:E=function(){return b.length};var I=E(),S=er(4+I+1);if(Ce[S>>2]=I,u&&T)ps(b,S+4,I+1);else if(T)for(var O=0;O<I;++O){var H=b.charCodeAt(O);H>255&&(Fe(S),ot("String has UTF-16 code units that do not fit in 8 bits")),oe[S+4+O]=H}else for(var O=0;O<I;++O)oe[S+4+O]=b[O];return p!==null&&p.push(Fe,S),S},argPackAdvance:8,readValueFromPointer:Gr,destructorFunction:function(p){Fe(p)}})}function zo(s,o,u){u=Be(u);var p,b,E,T,I;o===2?(p=no,b=so,T=io,E=function(){return Yt},I=1):o===4&&(p=oo,b=ao,T=uo,E=function(){return Ce},I=2),Ve(s,{name:u,fromWireType:function(S){for(var O=Ce[S>>2],H=E(),K,q=S+4,Q=0;Q<=O;++Q){var W=S+4+Q*o;if(Q==O||H[W>>I]==0){var te=W-q,$=p(q,te);K===void 0?K=$:(K+="\0",K+=$),q=W+o}}return Fe(S),K},toWireType:function(S,O){typeof O!="string"&&ot("Cannot pass non-string to C++ string type "+u);var H=T(O),K=er(4+H+o);return Ce[K>>2]=H>>I,b(O,K+4,H+o),S!==null&&S.push(Fe,K),K},argPackAdvance:8,readValueFromPointer:Gr,destructorFunction:function(S){Fe(S)}})}function Zo(s,o){o=Be(o),Ve(s,{isVoid:!0,name:o,argPackAdvance:0,fromWireType:function(){},toWireType:function(u,p){}})}function ea(){it("")}var $r;typeof dateNow!="undefined"?$r=dateNow:$r=function(){return performance.now()};var ta=!0;function ra(s){return L[ws()>>2]=s,s}function na(s,o){var u;if(s===0)u=Date.now();else if((s===1||s===4)&&ta)u=$r();else return ra(28),-1;return L[o>>2]=u/1e3|0,L[o+4>>2]=u%1e3*1e3*1e3|0,0}function sa(s){return s<0||s===0&&1/s===-1/0}function ia(s,o){return(s>>>0)+o*4294967296}function oa(s,o){return(s>>>0)+(o>>>0)*4294967296}function Ps(s,o){if(s<=0)return s;var u=o<=32?Math.abs(1<<o-1):Math.pow(2,o-1);return s>=u&&(o<=32||s>u)&&(s=-2*u+s),s}function Ns(s,o){return s>=0?s:o<=32?2*Math.abs(1<<o-1)+s:Math.pow(2,o)+s}function Ds(s){for(var o=s;oe[o];)++o;return o-s}e._strlen=Ds;function aa(s,o){var u=s,p=o;function b(Pe,Me){return(Me==="double"||Me==="i64")&&Pe&7&&(Pe+=4),Pe}function E(Pe){var Me;return p=b(p,Pe),Pe==="double"?(Me=Number(Br[p>>3]),p+=8):Pe=="i64"?(Me=[L[p>>2],L[p+4>>2]],p+=8):(Pe="i32",Me=L[p>>2],p+=4),Me}for(var T=[],I,S,O;;){var H=u;if(I=z[u>>0],I===0)break;if(S=z[u+1>>0],I==37){var K=!1,q=!1,Q=!1,W=!1,te=!1;e:for(;;){switch(S){case 43:K=!0;break;case 45:q=!0;break;case 35:Q=!0;break;case 48:if(W)break e;W=!0;break;case 32:te=!0;break;default:break e}u++,S=z[u+1>>0]}var $=0;if(S==42)$=E("i32"),u++,S=z[u+1>>0];else for(;S>=48&&S<=57;)$=$*10+(S-48),u++,S=z[u+1>>0];var fe=!1,g=-1;if(S==46){if(g=0,fe=!0,u++,S=z[u+1>>0],S==42)g=E("i32"),u++;else for(;;){var D=z[u+1>>0];if(D<48||D>57)break;g=g*10+(D-48),u++}S=z[u+1>>0]}g<0&&(g=6,fe=!1);var B;switch(String.fromCharCode(S)){case"h":var J=z[u+2>>0];J==104?(u++,B=1):B=2;break;case"l":var J=z[u+2>>0];J==108?(u++,B=8):B=4;break;case"L":case"q":case"j":B=8;break;case"z":case"t":case"I":B=4;break;default:B=null}switch(B&&u++,S=z[u+1>>0],String.fromCharCode(S)){case"d":case"i":case"u":case"o":case"x":case"X":case"p":{var ge=S==100||S==105;B=B||4,O=E("i"+B*8);var v;if(B==8&&(O=S==117?oa(O[0],O[1]):ia(O[0],O[1])),B<=4){var we=Math.pow(256,B)-1;O=(ge?Ps:Ns)(O&we,B*8)}var Ut=Math.abs(O),_e="";if(S==100||S==105)v=Ps(O,8*B,1).toString(10);else if(S==117)v=Ns(O,8*B,1).toString(10),O=Math.abs(O);else if(S==111)v=(Q?"0":"")+Ut.toString(8);else if(S==120||S==88){if(_e=Q&&O!=0?"0x":"",O<0){O=-O,v=(Ut-1).toString(16);for(var ks=[],xe=0;xe<v.length;xe++)ks.push((15-parseInt(v[xe],16)).toString(16));for(v=ks.join("");v.length<B*2;)v="f"+v}else v=Ut.toString(16);S==88&&(_e=_e.toUpperCase(),v=v.toUpperCase())}else S==112&&(Ut===0?v="(nil)":(_e="0x",v=Ut.toString(16)));if(fe)for(;v.length<g;)v="0"+v;for(O>=0&&(K?_e="+"+_e:te&&(_e=" "+_e)),v.charAt(0)=="-"&&(_e="-"+_e,v=v.substr(1));_e.length+v.length<$;)q?v+=" ":W?v="0"+v:_e=" "+_e;v=_e+v,v.split("").forEach(function(Pe){T.push(Pe.charCodeAt(0))});break}case"f":case"F":case"e":case"E":case"g":case"G":{O=E("double");var v;if(isNaN(O))v="nan",W=!1;else if(!isFinite(O))v=(O<0?"-":"")+"inf",W=!1;else{var Bs=!1,xt=Math.min(g,20);if(S==103||S==71){Bs=!0,g=g||1;var zr=parseInt(O.toExponential(xt).split("e")[1],10);g>zr&&zr>=-4?(S=(S==103?"f":"F").charCodeAt(0),g-=zr+1):(S=(S==103?"e":"E").charCodeAt(0),g--),xt=Math.min(g,20)}S==101||S==69?(v=O.toExponential(xt),/[eE][-+]\d$/.test(v)&&(v=v.slice(0,-1)+"0"+v.slice(-1))):(S==102||S==70)&&(v=O.toFixed(xt),O===0&&sa(O)&&(v="-"+v));var Ae=v.split("e");if(Bs&&!Q)for(;Ae[0].length>1&&Ae[0].includes(".")&&(Ae[0].slice(-1)=="0"||Ae[0].slice(-1)==".");)Ae[0]=Ae[0].slice(0,-1);else for(Q&&v.indexOf(".")==-1&&(Ae[0]+=".");g>xt++;)Ae[0]+="0";v=Ae[0]+(Ae.length>1?"e"+Ae[1]:""),S==69&&(v=v.toUpperCase()),O>=0&&(K?v="+"+v:te&&(v=" "+v))}for(;v.length<$;)q?v+=" ":W&&(v[0]=="-"||v[0]=="+")?v=v[0]+"0"+v.slice(1):v=(W?"0":" ")+v;S<97&&(v=v.toUpperCase()),v.split("").forEach(function(Me){T.push(Me.charCodeAt(0))});break}case"s":{var rr=E("i8*"),ut=rr?Ds(rr):6;if(fe&&(ut=Math.min(ut,g)),!q)for(;ut<$--;)T.push(32);if(rr)for(var xe=0;xe<ut;xe++)T.push(oe[rr++>>0]);else T=T.concat(Cs("(null)".substr(0,ut),!0));if(q)for(;ut<$--;)T.push(32);break}case"c":{for(q&&T.push(E("i8"));--$>0;)T.push(32);q||T.push(E("i8"));break}case"n":{var hu=E("i32*");L[hu>>2]=T.length;break}case"%":{T.push(I);break}default:for(var xe=H;xe<u+2;xe++)T.push(z[xe>>0])}u+=2}else T.push(I),u+=1}return T}function Yr(s){if(!s||!s.callee||!s.callee.name)return[null,"",""];var o=s.callee.toString(),u=s.callee.name,p="(",b=!0;for(var E in s){var T=s[E];b||(p+=", "),b=!1,typeof T=="number"||typeof T=="string"?p+=T:p+="("+typeof T+")"}p+=")";var I=s.callee.caller;return s=I?I.arguments:[],b&&(p=""),[s,u,p]}function ua(s){var o=Ao(),u=o.lastIndexOf("_emscripten_log"),p=o.lastIndexOf("_emscripten_get_callstack"),b=o.indexOf(`
|
|
10
|
+
`,Math.max(u,p))+1;o=o.slice(b),s&32&&pe("EM_LOG_DEMANGLE is deprecated; ignoring"),s&8&&typeof emscripten_source_map=="undefined"&&(pe('Source map information is not available, emscripten_log with EM_LOG_C_STACK will be ignored. Build with "--pre-js $EMSCRIPTEN/src/emscripten-source-map.min.js" linker flag to add source map loading to code.'),s^=8,s|=16);var E=null;if(s&128)for(E=Yr(arguments);E[1].includes("_emscripten_");)E=Yr(E[0]);var T=o.split(`
|
|
11
|
+
`);o="";var I=new RegExp("\\s*(.*?)@(.*?):([0-9]+):([0-9]+)"),S=new RegExp("\\s*(.*?)@(.*):(.*)(:(.*))?"),O=new RegExp("\\s*at (.*?) \\((.*):(.*):(.*)\\)");for(var H in T){var K=T[H],q="",Q="",W=0,te=0,$=O.exec(K);if($&&$.length==5)q=$[1],Q=$[2],W=$[3],te=$[4];else if($=I.exec(K),$||($=S.exec(K)),$&&$.length>=4)q=$[1],Q=$[2],W=$[3],te=$[4]|0;else{o+=K+`
|
|
12
|
+
`;continue}var fe=!1;if(s&8){var g=emscripten_source_map.originalPositionFor({line:W,column:te});fe=g&&g.source,fe&&(s&64&&(g.source=g.source.substring(g.source.replace(/\\/g,"/").lastIndexOf("/")+1)),o+=" at "+q+" ("+g.source+":"+g.line+":"+g.column+`)
|
|
13
|
+
`)}(s&16||!fe)&&(s&64&&(Q=Q.substring(Q.replace(/\\/g,"/").lastIndexOf("/")+1)),o+=(fe?" = "+q:" at "+q)+" ("+Q+":"+W+":"+te+`)
|
|
14
|
+
`),s&128&&E[0]&&(E[1]==q&&E[2].length>0&&(o=o.replace(/\s+$/,""),o+=" with values: "+E[1]+E[2]+`
|
|
15
|
+
`),E=Yr(E[0]))}return o=o.replace(/\s+$/,""),o}function ca(s,o){s&24&&(o=o.replace(/\s+$/,""),o+=(o.length>0?`
|
|
16
|
+
`:"")+ua(s)),s&1?s&4?ie(o):s&2?console.warn(o):s&512?console.info(o):s&256?console.debug(o):Ie(o):s&6?ie(o):Ie(o)}function la(s,o,u){var p=aa(o,u),b=Lr(p,0);ca(s,b)}function ma(s,o,u){oe.copyWithin(s,o,o+u)}function da(s){try{return $t.grow(s-kr.byteLength+65535>>>16),gs($t.buffer),1}catch(o){}}function pa(s){var o=oe.length;s=s>>>0;var u=1073741824;if(s>u)return!1;for(var p=1;p<=4;p*=2){var b=o*(1+.2/p);b=Math.min(b,s+100663296);var E=Math.min(u,x(Math.max(s,b),65536)),T=da(E);if(T)return!0}return!1}var Kr={};function _a(){return m||"./this.program"}function vt(){if(!vt.strings){var s=(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",o={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:s,_:_a()};for(var u in Kr)Kr[u]===void 0?delete o[u]:o[u]=Kr[u];var p=[];for(var u in o)p.push(u+"="+o[u]);vt.strings=p}return vt.strings}var at={mappings:{},buffers:[null,[],[]],printChar:function(s,o){var u=at.buffers[s];o===0||o===10?((s===1?Ie:ie)(Lr(u,0)),u.length=0):u.push(o)},varargs:void 0,get:function(){at.varargs+=4;var s=L[at.varargs-4>>2];return s},getStr:function(s){var o=yt(s);return o},get64:function(s,o){return s}};function fa(s,o){var u=0;return vt().forEach(function(p,b){var E=o+u;L[s+b*4>>2]=E,co(p,E),u+=p.length+1}),0}function ha(s,o){var u=vt();L[s>>2]=u.length;var p=0;return u.forEach(function(b){p+=b.length+1}),L[o>>2]=p,0}function ba(s){return 0}function ga(s,o,u,p){var b=at.getStreamFromFD(s),E=at.doReadv(b,o,u);return L[p>>2]=E,0}function Ea(s,o,u,p,b){}function Ta(s,o,u,p){for(var b=0,E=0;E<u;E++){var T=L[o>>2],I=L[o+4>>2];o+=8;for(var S=0;S<I;S++)at.printChar(s,oe[T+S]);b+=I}return L[p>>2]=b,0}function Sa(){if(typeof crypto=="object"&&typeof crypto.getRandomValues=="function"){var s=new Uint8Array(1);return function(){return crypto.getRandomValues(s),s[0]}}else return function(){it("randomDevice")}}function Jt(s,o){Jt.randomDevice||(Jt.randomDevice=Sa());for(var u=0;u<o;u++)z[s+u>>0]=Jt.randomDevice();return 0}function Ia(s){var o=Date.now();return L[s>>2]=o/1e3|0,L[s+4>>2]=o%1e3*1e3|0,0}function Xt(s){return s%4===0&&(s%100!==0||s%400===0)}function Jr(s,o){for(var u=0,p=0;p<=o;u+=s[p++]);return u}var Qt=[31,29,31,30,31,30,31,31,30,31,30,31],zt=[31,28,31,30,31,30,31,31,30,31,30,31];function Zt(s,o){for(var u=new Date(s.getTime());o>0;){var p=Xt(u.getFullYear()),b=u.getMonth(),E=(p?Qt:zt)[b];if(o>E-u.getDate())o-=E-u.getDate()+1,u.setDate(1),b<11?u.setMonth(b+1):(u.setMonth(0),u.setFullYear(u.getFullYear()+1));else return u.setDate(u.getDate()+o),u}return u}function Ra(s,o,u,p){var b=L[p+40>>2],E={tm_sec:L[p>>2],tm_min:L[p+4>>2],tm_hour:L[p+8>>2],tm_mday:L[p+12>>2],tm_mon:L[p+16>>2],tm_year:L[p+20>>2],tm_wday:L[p+24>>2],tm_yday:L[p+28>>2],tm_isdst:L[p+32>>2],tm_gmtoff:L[p+36>>2],tm_zone:b?yt(b):""},T=yt(u),I={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var S in I)T=T.replace(new RegExp(S,"g"),I[S]);var O=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],H=["January","February","March","April","May","June","July","August","September","October","November","December"];function K(g,D,B){for(var J=typeof g=="number"?g.toString():g||"";J.length<D;)J=B[0]+J;return J}function q(g,D){return K(g,D,"0")}function Q(g,D){function B(ge){return ge<0?-1:ge>0?1:0}var J;return(J=B(g.getFullYear()-D.getFullYear()))===0&&(J=B(g.getMonth()-D.getMonth()))===0&&(J=B(g.getDate()-D.getDate())),J}function W(g){switch(g.getDay()){case 0:return new Date(g.getFullYear()-1,11,29);case 1:return g;case 2:return new Date(g.getFullYear(),0,3);case 3:return new Date(g.getFullYear(),0,2);case 4:return new Date(g.getFullYear(),0,1);case 5:return new Date(g.getFullYear()-1,11,31);case 6:return new Date(g.getFullYear()-1,11,30)}}function te(g){var D=Zt(new Date(g.tm_year+1900,0,1),g.tm_yday),B=new Date(D.getFullYear(),0,4),J=new Date(D.getFullYear()+1,0,4),ge=W(B),v=W(J);return Q(ge,D)<=0?Q(v,D)<=0?D.getFullYear()+1:D.getFullYear():D.getFullYear()-1}var $={"%a":function(g){return O[g.tm_wday].substring(0,3)},"%A":function(g){return O[g.tm_wday]},"%b":function(g){return H[g.tm_mon].substring(0,3)},"%B":function(g){return H[g.tm_mon]},"%C":function(g){var D=g.tm_year+1900;return q(D/100|0,2)},"%d":function(g){return q(g.tm_mday,2)},"%e":function(g){return K(g.tm_mday,2," ")},"%g":function(g){return te(g).toString().substring(2)},"%G":function(g){return te(g)},"%H":function(g){return q(g.tm_hour,2)},"%I":function(g){var D=g.tm_hour;return D==0?D=12:D>12&&(D-=12),q(D,2)},"%j":function(g){return q(g.tm_mday+Jr(Xt(g.tm_year+1900)?Qt:zt,g.tm_mon-1),3)},"%m":function(g){return q(g.tm_mon+1,2)},"%M":function(g){return q(g.tm_min,2)},"%n":function(){return`
|
|
17
|
+
`},"%p":function(g){return g.tm_hour>=0&&g.tm_hour<12?"AM":"PM"},"%S":function(g){return q(g.tm_sec,2)},"%t":function(){return" "},"%u":function(g){return g.tm_wday||7},"%U":function(g){var D=new Date(g.tm_year+1900,0,1),B=D.getDay()===0?D:Zt(D,7-D.getDay()),J=new Date(g.tm_year+1900,g.tm_mon,g.tm_mday);if(Q(B,J)<0){var ge=Jr(Xt(J.getFullYear())?Qt:zt,J.getMonth()-1)-31,v=31-B.getDate(),we=v+ge+J.getDate();return q(Math.ceil(we/7),2)}return Q(B,D)===0?"01":"00"},"%V":function(g){var D=new Date(g.tm_year+1900,0,4),B=new Date(g.tm_year+1901,0,4),J=W(D),ge=W(B),v=Zt(new Date(g.tm_year+1900,0,1),g.tm_yday);if(Q(v,J)<0)return"53";if(Q(ge,v)<=0)return"01";var we;return J.getFullYear()<g.tm_year+1900?we=g.tm_yday+32-J.getDate():we=g.tm_yday+1-J.getDate(),q(Math.ceil(we/7),2)},"%w":function(g){return g.tm_wday},"%W":function(g){var D=new Date(g.tm_year,0,1),B=D.getDay()===1?D:Zt(D,D.getDay()===0?1:7-D.getDay()+1),J=new Date(g.tm_year+1900,g.tm_mon,g.tm_mday);if(Q(B,J)<0){var ge=Jr(Xt(J.getFullYear())?Qt:zt,J.getMonth()-1)-31,v=31-B.getDate(),we=v+ge+J.getDate();return q(Math.ceil(we/7),2)}return Q(B,D)===0?"01":"00"},"%y":function(g){return(g.tm_year+1900).toString().substring(2)},"%Y":function(g){return g.tm_year+1900},"%z":function(g){var D=g.tm_gmtoff,B=D>=0;return D=Math.abs(D)/60,D=D/60*100+D%60,(B?"+":"-")+("0000"+D).slice(-4)},"%Z":function(g){return g.tm_zone},"%%":function(){return"%"}};for(var S in $)T.includes(S)&&(T=T.replace(new RegExp(S,"g"),$[S](E)));var fe=Cs(T,!1);return fe.length>o?0:(hs(fe,s),fe.length-1)}function Aa(s,o,u,p){return Ra(s,o,u,p)}function ya(s){var o=Date.now()/1e3|0;return s&&(L[s>>2]=o),o}Co(),Us=e.BindingError=vs(Error,"BindingError"),Vo=e.InternalError=vs(Error,"InternalError"),Go();function Cs(s,o,u){var p=u>0?u:_s(s)+1,b=new Array(p),E=ds(s,b,0,b.length);return o&&(b.length=E),b}var Oa={g:yo,a:vo,f:No,r:Do,n:Fo,A:jo,l:Yo,d:Jo,c:Xo,m:Qo,i:zo,o:Zo,e:ea,j:na,b:la,s:ma,t:pa,x:fa,y:ha,z:ba,u:ga,q:Ea,k:Ta,v:Jt,h:Ia,w:Aa,p:ya},qc=Ro(),va=e.___wasm_call_ctors=function(){return(va=e.___wasm_call_ctors=e.asm.C).apply(null,arguments)},Ua=e._CreateMediaProcessing=function(){return(Ua=e._CreateMediaProcessing=e.asm.D).apply(null,arguments)},xa=e._ReleaseMediaProcessing=function(){return(xa=e._ReleaseMediaProcessing=e.asm.E).apply(null,arguments)},Pa=e._AddAudioChannel=function(){return(Pa=e._AddAudioChannel=e.asm.F).apply(null,arguments)},Na=e._DelAudioChannel=function(){return(Na=e._DelAudioChannel=e.asm.G).apply(null,arguments)},Da=e._AddVideoChannel=function(){return(Da=e._AddVideoChannel=e.asm.H).apply(null,arguments)},Ca=e._DelVideoChannel=function(){return(Ca=e._DelVideoChannel=e.asm.I).apply(null,arguments)},wa=e._ReceivedRawAudioPacket=function(){return(wa=e._ReceivedRawAudioPacket=e.asm.J).apply(null,arguments)},Ma=e._ParseUdtMousePacket=function(){return(Ma=e._ParseUdtMousePacket=e.asm.K).apply(null,arguments)},La=e._ReceivedAudioUdtPacket=function(){return(La=e._ReceivedAudioUdtPacket=e.asm.L).apply(null,arguments)},ka=e._ParseUdtAudioPacket=function(){return(ka=e._ParseUdtAudioPacket=e.asm.M).apply(null,arguments)},Ba=e._ReceivedVideoPacket=function(){return(Ba=e._ReceivedVideoPacket=e.asm.N).apply(null,arguments)},Va=e._SetAudioBuffer10Ms=function(){return(Va=e._SetAudioBuffer10Ms=e.asm.O).apply(null,arguments)},Fa=e._SetAudioVolume=function(){return(Fa=e._SetAudioVolume=e.asm.P).apply(null,arguments)},Ha=e._GetAudioFrame=function(){return(Ha=e._GetAudioFrame=e.asm.Q).apply(null,arguments)},qa=e._GetAudioFrameFloat=function(){return(qa=e._GetAudioFrameFloat=e.asm.R).apply(null,arguments)},Wa=e._GetAudioMixed=function(){return(Wa=e._GetAudioMixed=e.asm.S).apply(null,arguments)},Ga=e._GetAudioMixedFloat=function(){return(Ga=e._GetAudioMixedFloat=e.asm.T).apply(null,arguments)},ja=e._GetAudioEnergy=function(){return(ja=e._GetAudioEnergy=e.asm.U).apply(null,arguments)},$a=e._SetAudioFrameFormat=function(){return($a=e._SetAudioFrameFormat=e.asm.V).apply(null,arguments)},Ya=e._SetAudioOutStreamFormat=function(){return(Ya=e._SetAudioOutStreamFormat=e.asm.W).apply(null,arguments)},Ka=e._AudioProcess=function(){return(Ka=e._AudioProcess=e.asm.X).apply(null,arguments)},Ja=e._AudioProcessFloat=function(){return(Ja=e._AudioProcessFloat=e.asm.Y).apply(null,arguments)},Xa=e._AudioReverseProcess=function(){return(Xa=e._AudioReverseProcess=e.asm.Z).apply(null,arguments)},Qa=e._AudioReverseProcessFloat=function(){return(Qa=e._AudioReverseProcessFloat=e.asm._).apply(null,arguments)},za=e._InitOpusEncoder=function(){return(za=e._InitOpusEncoder=e.asm.$).apply(null,arguments)},Za=e._SetOpusEncBitrate=function(){return(Za=e._SetOpusEncBitrate=e.asm.aa).apply(null,arguments)},eu=e._OpusEncode=function(){return(eu=e._OpusEncode=e.asm.ba).apply(null,arguments)},tu=e._UpdateStreamSync=function(){return(tu=e._UpdateStreamSync=e.asm.ca).apply(null,arguments)},ru=e._GetEncodedFrame=function(){return(ru=e._GetEncodedFrame=e.asm.da).apply(null,arguments)},nu=e._GetReceivedVideoStat=function(){return(nu=e._GetReceivedVideoStat=e.asm.ea).apply(null,arguments)},su=e._CreateUdtPacketizer=function(){return(su=e._CreateUdtPacketizer=e.asm.fa).apply(null,arguments)},iu=e._PacketizeVideoUdt=function(){return(iu=e._PacketizeVideoUdt=e.asm.ga).apply(null,arguments)},ou=e._PacketizeAudioUdt=function(){return(ou=e._PacketizeAudioUdt=e.asm.ha).apply(null,arguments)},au=e._GetRetransPacket=function(){return(au=e._GetRetransPacket=e.asm.ia).apply(null,arguments)},uu=e._CheckMissingPacket=function(){return(uu=e._CheckMissingPacket=e.asm.ja).apply(null,arguments)},cu=e._UseAINS=function(){return(cu=e._UseAINS=e.asm.ka).apply(null,arguments)},lu=e._EnableAEC=function(){return(lu=e._EnableAEC=e.asm.la).apply(null,arguments)},mu=e._SetCrypto=function(){return(mu=e._SetCrypto=e.asm.ma).apply(null,arguments)},er=e._malloc=function(){return(er=e._malloc=e.asm.oa).apply(null,arguments)},Fe=e._free=function(){return(Fe=e._free=e.asm.pa).apply(null,arguments)},ws=e.___errno_location=function(){return(ws=e.___errno_location=e.asm.qa).apply(null,arguments)},du=e.___getTypeName=function(){return(du=e.___getTypeName=e.asm.ra).apply(null,arguments)},pu=e.___embind_register_native_and_builtin_types=function(){return(pu=e.___embind_register_native_and_builtin_types=e.asm.sa).apply(null,arguments)},Ms=e.stackSave=function(){return(Ms=e.stackSave=e.asm.ta).apply(null,arguments)},Ls=e.stackRestore=function(){return(Ls=e.stackRestore=e.asm.ua).apply(null,arguments)},Xr=e.stackAlloc=function(){return(Xr=e.stackAlloc=e.asm.va).apply(null,arguments)},_u=e._emscripten_stack_init=function(){return(_u=e._emscripten_stack_init=e.asm.wa).apply(null,arguments)};e.ccall=ls,e.cwrap=ro,e.addFunction=Zi,e.removeFunction=eo;var tr;function fu(s){this.name="ExitStatus",this.message="Program terminated with exit("+s+")",this.status=s}Ot=function s(){tr||Qr(),tr||(Ot=s)};function Qr(s){if(s=s||_,Xe>0||(po(),Xe>0))return;function o(){tr||(tr=!0,e.calledRun=!0,!us&&(_o(),r(e),e.onRuntimeInitialized&&e.onRuntimeInitialized(),fo()))}e.setStatus?(e.setStatus("Running..."),setTimeout(function(){setTimeout(function(){e.setStatus("")},1),o()},1)):o()}if(e.run=Qr,e.preInit)for(typeof e.preInit=="function"&&(e.preInit=[e.preInit]);e.preInit.length>0;)e.preInit.pop()();return Qr(),e.ready}}(),Ji=Vc;Ki(Ji);
|
package/package.json
CHANGED
|
@@ -1,12 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "trtc-sdk-v5",
|
|
3
|
-
"version": "5.11.2-
|
|
3
|
+
"version": "5.11.2-wasm.2",
|
|
4
4
|
"description": "Tencent Cloud RTC SDK for Web",
|
|
5
|
-
"
|
|
5
|
+
"module": "trtc.esm.js",
|
|
6
|
+
"type": "module",
|
|
6
7
|
"types": "index.d.ts",
|
|
7
|
-
"dependencies": {
|
|
8
|
-
"webrtc-adapter": "^8.2.3"
|
|
9
|
-
},
|
|
10
8
|
"keywords": [
|
|
11
9
|
"webrtc",
|
|
12
10
|
"TRTC",
|
|
@@ -29,4 +27,4 @@
|
|
|
29
27
|
},
|
|
30
28
|
"author": "Tencent Cloud Client R&D Center",
|
|
31
29
|
"license": "ISC"
|
|
32
|
-
}
|
|
30
|
+
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var errorModule,__create=Object.create,__defProp=Object.defineProperty,__defProps=Object.defineProperties,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropDescs=Object.getOwnPropertyDescriptors,__getOwnPropNames=Object.getOwnPropertyNames,__getOwnPropSymbols=Object.getOwnPropertySymbols,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__propIsEnum=Object.prototype.propertyIsEnumerable,__defNormalProp=(e,t,r)=>t in e?__defProp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,__spreadValues=(e,t)=>{for(var r in t||(t={}))__hasOwnProp.call(t,r)&&__defNormalProp(e,r,t[r]);if(__getOwnPropSymbols)for(var r of __getOwnPropSymbols(t))__propIsEnum.call(t,r)&&__defNormalProp(e,r,t[r]);return e},__spreadProps=(e,t)=>__defProps(e,__getOwnPropDescs(t)),__commonJS=(e,t)=>function(){return t||(0,e[__getOwnPropNames(e)[0]])((t={exports:{}}).exports,t),t.exports},__copyProps=(e,t,r,o)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let i of __getOwnPropNames(t))__hasOwnProp.call(e,i)||i===r||__defProp(e,i,{get:()=>t[i],enumerable:!(o=__getOwnPropDesc(t,i))||o.enumerable});return e},__toESM=(e,t,r)=>(r=null!=e?__create(__getProtoOf(e)):{},__copyProps(!t&&e&&e.__esModule?r:__defProp(r,"default",{value:e,enumerable:!0}),e)),__publicField=(e,t,r)=>__defNormalProp(e,"symbol"!=typeof t?t+"":t,r),require_md5=__commonJS({"../node_modules/.pnpm/blueimp-md5@2.19.0/node_modules/blueimp-md5/js/md5.js"(e,t){"use strict";!function(e){function r(e,t){var r=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(r>>16)<<16|65535&r}function o(e,t,o,i,s,a){return r((n=r(r(t,e),r(i,a)))<<(d=s)|n>>>32-d,o);var n,d}function i(e,t,r,i,s,a,n){return o(t&r|~t&i,e,t,s,a,n)}function s(e,t,r,i,s,a,n){return o(t&i|r&~i,e,t,s,a,n)}function a(e,t,r,i,s,a,n){return o(t^r^i,e,t,s,a,n)}function n(e,t,r,i,s,a,n){return o(r^(t|~i),e,t,s,a,n)}function d(e,t){var o,d,u,l,h;e[t>>5]|=128<<t%32,e[14+(t+64>>>9<<4)]=t;var m=1732584193,_=-271733879,p=-1732584194,c=271733878;for(o=0;o<e.length;o+=16)d=m,u=_,l=p,h=c,m=i(m,_,p,c,e[o],7,-680876936),c=i(c,m,_,p,e[o+1],12,-389564586),p=i(p,c,m,_,e[o+2],17,606105819),_=i(_,p,c,m,e[o+3],22,-1044525330),m=i(m,_,p,c,e[o+4],7,-176418897),c=i(c,m,_,p,e[o+5],12,1200080426),p=i(p,c,m,_,e[o+6],17,-1473231341),_=i(_,p,c,m,e[o+7],22,-45705983),m=i(m,_,p,c,e[o+8],7,1770035416),c=i(c,m,_,p,e[o+9],12,-1958414417),p=i(p,c,m,_,e[o+10],17,-42063),_=i(_,p,c,m,e[o+11],22,-1990404162),m=i(m,_,p,c,e[o+12],7,1804603682),c=i(c,m,_,p,e[o+13],12,-40341101),p=i(p,c,m,_,e[o+14],17,-1502002290),m=s(m,_=i(_,p,c,m,e[o+15],22,1236535329),p,c,e[o+1],5,-165796510),c=s(c,m,_,p,e[o+6],9,-1069501632),p=s(p,c,m,_,e[o+11],14,643717713),_=s(_,p,c,m,e[o],20,-373897302),m=s(m,_,p,c,e[o+5],5,-701558691),c=s(c,m,_,p,e[o+10],9,38016083),p=s(p,c,m,_,e[o+15],14,-660478335),_=s(_,p,c,m,e[o+4],20,-405537848),m=s(m,_,p,c,e[o+9],5,568446438),c=s(c,m,_,p,e[o+14],9,-1019803690),p=s(p,c,m,_,e[o+3],14,-187363961),_=s(_,p,c,m,e[o+8],20,1163531501),m=s(m,_,p,c,e[o+13],5,-1444681467),c=s(c,m,_,p,e[o+2],9,-51403784),p=s(p,c,m,_,e[o+7],14,1735328473),m=a(m,_=s(_,p,c,m,e[o+12],20,-1926607734),p,c,e[o+5],4,-378558),c=a(c,m,_,p,e[o+8],11,-2022574463),p=a(p,c,m,_,e[o+11],16,1839030562),_=a(_,p,c,m,e[o+14],23,-35309556),m=a(m,_,p,c,e[o+1],4,-1530992060),c=a(c,m,_,p,e[o+4],11,1272893353),p=a(p,c,m,_,e[o+7],16,-155497632),_=a(_,p,c,m,e[o+10],23,-1094730640),m=a(m,_,p,c,e[o+13],4,681279174),c=a(c,m,_,p,e[o],11,-358537222),p=a(p,c,m,_,e[o+3],16,-722521979),_=a(_,p,c,m,e[o+6],23,76029189),m=a(m,_,p,c,e[o+9],4,-640364487),c=a(c,m,_,p,e[o+12],11,-421815835),p=a(p,c,m,_,e[o+15],16,530742520),m=n(m,_=a(_,p,c,m,e[o+2],23,-995338651),p,c,e[o],6,-198630844),c=n(c,m,_,p,e[o+7],10,1126891415),p=n(p,c,m,_,e[o+14],15,-1416354905),_=n(_,p,c,m,e[o+5],21,-57434055),m=n(m,_,p,c,e[o+12],6,1700485571),c=n(c,m,_,p,e[o+3],10,-1894986606),p=n(p,c,m,_,e[o+10],15,-1051523),_=n(_,p,c,m,e[o+1],21,-2054922799),m=n(m,_,p,c,e[o+8],6,1873313359),c=n(c,m,_,p,e[o+15],10,-30611744),p=n(p,c,m,_,e[o+6],15,-1560198380),_=n(_,p,c,m,e[o+13],21,1309151649),m=n(m,_,p,c,e[o+4],6,-145523070),c=n(c,m,_,p,e[o+11],10,-1120210379),p=n(p,c,m,_,e[o+2],15,718787259),_=n(_,p,c,m,e[o+9],21,-343485551),m=r(m,d),_=r(_,u),p=r(p,l),c=r(c,h);return[m,_,p,c]}function u(e){var t,r="",o=32*e.length;for(t=0;t<o;t+=8)r+=String.fromCharCode(e[t>>5]>>>t%32&255);return r}function l(e){var t,r=[];for(r[(e.length>>2)-1]=void 0,t=0;t<r.length;t+=1)r[t]=0;var o=8*e.length;for(t=0;t<o;t+=8)r[t>>5]|=(255&e.charCodeAt(t/8))<<t%32;return r}function h(e){var t,r,o="0123456789abcdef",i="";for(r=0;r<e.length;r+=1)t=e.charCodeAt(r),i+=o.charAt(t>>>4&15)+o.charAt(15&t);return i}function m(e){return unescape(encodeURIComponent(e))}function _(e){return function(e){return u(d(l(e),8*e.length))}(m(e))}function p(e,t){return function(e,t){var r,o,i=l(e),s=[],a=[];for(s[15]=a[15]=void 0,i.length>16&&(i=d(i,8*e.length)),r=0;r<16;r+=1)s[r]=909522486^i[r],a[r]=1549556828^i[r];return o=d(s.concat(l(t)),512+8*t.length),u(d(a.concat(o),640))}(m(e),m(t))}function c(e,t,r){return t?r?p(t,e):h(p(t,e)):r?_(e):h(_(e))}"function"==typeof define&&define.amd?define((function(){return c})):"object"==typeof t&&t.exports?t.exports=c:e.md5=c}(e)}}),import_blueimp_md5=__toESM(require_md5(),1),MIX_INPUT_TYPE={IT_AUDIO_VIDEO:0,IT_PICTURE:2,IT_CANVAS:3,IT_PURE_AUDIO:4,IT_PURE_VIDEO:5},GivenCDNManager=class{constructor(e,t){__publicField(this,"_core"),__publicField(this,"_room"),__publicField(this,"_log"),__publicField(this,"_params"),__publicField(this,"_publishGivenCDNData",null),this._core=e,this._room=e.room,this._log=t}get isPublishingGivenCDN(){return!!this._params}async startPublishGivenCDN(e){if(this._log.info(`[CDNStreaming] startPublishGivenCDN() current: ${JSON.stringify(this._params)}, params: ${JSON.stringify(e)}`),this.isPublishingGivenCDN){const{appId:t,bizId:r,url:o}=this._params||{};if(t===e.appId&&r===e.bizId&&o===e.url)return;await this.stopPublishGivenCDN()}this._params=e,this._publishGivenCDNData={pushRequestTime:Date.now(),pushAppId:e.appId,pushBizId:e.bizId,pushCdnUrl:e.url,pushStreamType:this.convertStreamType(null==e?void 0:e.publishMode),pushStreamId:e.streamId};try{const t=await this._room.sendStartPublishCDN(this._publishGivenCDNData,!1),{code:r,message:o}=t.data;if(0!==r)throw this.resetGivenCDN(),this._log.error(`[CDNStreaming] server failed: start given cdn errCode: ${r} errMsg: ${o} options: ${JSON.stringify(e)}`),new Error(`[CDNStreaming] server failed: start given cdn errCode: ${r} errMsg: ${o}`);this._log.info("[CDNStreaming] server success: start given cdn.")}catch(e){throw this.resetGivenCDN(),e}}async stopPublishGivenCDN(){if(this._log.info("[CDNStreaming] stopPublishGivenCDN"),!this.isPublishingGivenCDN||!this._publishGivenCDNData)return void this.resetGivenCDN();const{pushAppId:e,pushBizId:t,pushCdnUrl:r,pushStreamType:o,pushStreamId:i}=this._publishGivenCDNData,s={pushRequestTime:Date.now(),pushAppId:e,pushBizId:t,pushCdnUrl:r,pushStreamType:o,pushStreamId:i},a=await this._room.sendStopPublishCDN(s,!1),{code:n,message:d}=a.data;if(0!==n)throw this._log.error(`[CDNStreaming] server failed: stop given cdn errCode: ${n} errMsg: ${d} data: ${JSON.stringify(s)}`),new Error(`[CDNStreaming] server failed: stop given cdn errCode: ${n} errMsg: ${d}`);this._log.info("[CDNStreaming] server success: stop given cdn."),this.resetGivenCDN()}resetGivenCDN(){this._publishGivenCDNData=null,this._params=void 0}convertStreamType(e){return"publish-sub-stream-to-cdn"===e?"aux":"main"}},MixTranscodeManager=class{constructor(e,t){__publicField(this,"_core"),__publicField(this,"_room"),__publicField(this,"_log"),__publicField(this,"_config",null),__publicField(this,"_data",null),__publicField(this,"_givenCDNManager"),this._core=e,this._room=e.room,this._log=t,this.reset()}get isMixing(){return!!this._data}get isStarted(){return!!this._config}get hasCustomCDN(){var e,t,r;return(null==(e=this._config)?void 0:e.target.appId)&&(null==(t=this._config)?void 0:t.target.bizId)&&(null==(r=this._config)?void 0:r.target.url)}async startMixTranscode(e){if(this._log.info(`startMixTranscode: ${JSON.stringify(e)}`),this._config=e,this.installEvents(),this._core.room.isJoined)try{const t=this.getInputParam(e),r=this.getOutputParam(e),o=this.getOutputSessionId({config:e,roomId:this._room.roomId,userId:this._room.userId});this.isMixing&&this._data&&o!==this._data.outputSessionId&&(this._log.info("[CDNStreaming] streamId changed, auto stop mixing before start"),await this.doStopMixTranscode()),await this.doStartMixTranscode({outputSessionId:o,inputParam:t,outputParam:r});const{appId:i,bizId:s,url:a,streamId:n=""}=e.target;i&&s&&a&&(this._givenCDNManager||(this._givenCDNManager=new GivenCDNManager(this._core,this._log)),await this._givenCDNManager.startPublishGivenCDN({publishMode:e.target.publishMode,appId:i,bizId:s,url:a,streamId:n}))}catch(e){throw this.reset(),e}}async doStartMixTranscode({outputSessionId:e,inputParam:t,outputParam:r}){const o={roomId:String(this._room.roomId),mcuRequestTime:Date.now(),outputSessionId:e,inputParam:t,outputParam:r};this._log.info(`[CDNStreaming] doStartMixTranscode: ${JSON.stringify(o)}`);const i=await this._room.sendStartMixTranscode(o),{code:s}=i.data;let{message:a}=i.data;if(0!==s)throw-102083===s&&(a=`Please enable relayed-push in ${this._core.constants.CLOUD_CONSOLE_URL} and try later, refer to ${this._core.constants.DOC_URL}tutorial-26-advanced-publish-cdn-stream.html`),this._log.error(`[CDNStreaming] server failed: start mix errCode: ${s} errMsg: ${a}`),new Error(`[CDNStreaming] server failed: start mix errCode: ${s} errMsg: ${a}`);this._log.info("[CDNStreaming] server success: start mix"),this._data=o}async stopMixTranscode(){this._log.info("[CDNStreaming] stopMixTranscode");try{this.isStarted&&this.isMixing&&(await this.doStopMixTranscode(),this._config&&this.hasCustomCDN&&this._givenCDNManager&&await this._givenCDNManager.stopPublishGivenCDN())}catch(e){throw e}this.reset()}async doStopMixTranscode(){const e={mcuRequestTime:Date.now(),outputSessionId:this._data.outputSessionId,streamType:this._data.outputParam.streamType};this._log.info(`[CDNStreaming] doStopMixTranscode: ${JSON.stringify(e)}`);const t=await this._room.sendStopMixTranscode(e),{code:r,message:o}=t.data;if(0!==r)throw this._log.error(`[CDNStreaming] server failed: stop mix errCode: ${r} errMsg: ${o}`),new Error(`[CDNStreaming] server failed: stop mix errCode: ${r} errMsg: ${o}`);this._log.info("[CDNStreaming] server success: stop mix"),this.reset()}reset(){this._config=null,this._data=null,this.uninstallEvents()}installEvents(){this._core.room.on("joined",this.handleRoomJoined,this),this._core.room.on("left",this.handleRoomLeft,this)}uninstallEvents(){this._core.room.off("joined",this.handleRoomJoined,this),this._core.room.off("left",this.handleRoomLeft,this)}async handleRoomJoined(){this._log.info(`[CDNStreaming] handleJoined: ${JSON.stringify(this._config)}`),this.isStarted&&this._config&&await this.startMixTranscode(this._config)}async handleRoomLeft(){this._log.info(`[CDNStreaming] handleRoomLeft: ${JSON.stringify(this._config)}`),this._data=null}getOutputSessionId({config:e,userId:t,roomId:r}){return this._core.utils.isString(e.target.streamId)&&e.target.streamId.length>0?e.target.streamId:(0,import_blueimp_md5.default)(`${r}_${t}_main`)}getStringRoomId(e,t){return e?String(e):t}getInputParam(e){const{mix:t={}}=e,{audioMixUserList:r=[],videoLayoutList:o=[]}=t,i=o.map((e=>({userId:e.fixedVideoUser.userId,roomId:this.getStringRoomId(e.fixedVideoUser.roomId,e.fixedVideoUser.strRoomId)||this._core.room.roomId,width:e.width||0,height:e.height||0,locationX:e.locationX||0,locationY:e.locationY||0,zOrder:e.zOrder||1,streamType:"sub"===e.fixedVideoStreamType?1:0,inputType:MIX_INPUT_TYPE.IT_PURE_VIDEO,renderMode:e.fillMode||0})));return r.forEach((e=>{let t=this._core.room.roomId;(e.roomId||e.strRoomId)&&(t=this.getStringRoomId(e.roomId,e.strRoomId));const r=i.findIndex((r=>r.userId===e.userId&&r.roomId===t));-1!==r?i[r].inputType=MIX_INPUT_TYPE.IT_AUDIO_VIDEO:i.push({userId:e.userId,roomId:e.roomId||e.strRoomId||this._core.room.roomId,inputType:MIX_INPUT_TYPE.IT_PURE_AUDIO})})),i}getOutputParam(e){const t=e.target.streamId||"",{encoding:r={},mix:o={}}=e;return{streamId:t,streamType:t.length>0?1:0,width:this._core.utils.isUndefined(r.videoWidth)?640:r.videoWidth,height:this._core.utils.isUndefined(r.videoHeight)?480:r.videoHeight,videoBps:r.videoBitrate||0,fps:r.videoFramerate||15,gop:r.videoGOP||2,audioSampleRate:r.audioSampleRate||48e3,audioBps:r.audioBitrate||64,audioChannels:r.audioChannels||1,backgroundColor:o.backgroundColor||0,backgroundImg:o.backgroundImage||"",extraInfo:"",videoCodec:2,audioCodec:0}}},import_blueimp_md52=__toESM(require_md5(),1),PublishCDNManager=class{constructor(e,t){__publicField(this,"_room"),__publicField(this,"_core"),__publicField(this,"_log"),__publicField(this,"_paramsForTencentCDN"),__publicField(this,"_initParamsForTencentCDN",{isPublished:!1,isStarted:!1}),this._core=e,this._room=e.room,this._log=t,this._paramsForTencentCDN=new Map([["publish-main-stream-to-cdn",this._initParamsForTencentCDN],["publish-sub-stream-to-cdn",this._initParamsForTencentCDN]])}installEvents(){this._core.innerEmitter.on("104",this.handlePublished,this),this._core.room.on("left",this.handleRoomLeft,this)}uninstallEvents(){this._core.innerEmitter.off("104",this.handlePublished,this),this._core.room.off("left",this.handleRoomLeft,this)}async handlePublished({track:e}){var t;if(e.room!==this._room)return;if(this._log.info(`[CDNStreaming] handlePublished: mediaType ${e.mediaType}, roomID ${null==(t=null==e?void 0:e.room)?void 0:t.roomId}`),1===e.mediaType)return;const r=4===e.mediaType?"publish-main-stream-to-cdn":"publish-sub-stream-to-cdn",o=this._paramsForTencentCDN.get(r)||null;(null==o?void 0:o.target)&&o.isStarted&&await this.startPublishTencentCDN(o.target)}async handleRoomLeft(){this._log.info("[CDNStreaming] handleRoomLeft"),this.changeDataStatus("publish-main-stream-to-cdn",{isPublished:!1}),this.changeDataStatus("publish-sub-stream-to-cdn",{isPublished:!1})}isStreamPublished(e){return"publish-main-stream-to-cdn"!==e||this._room.isMainStreamPublished?!("publish-sub-stream-to-cdn"===e&&!this._room.isAuxStreamPublished)||(this._log.info("[CDNStreaming] Sub has not already published, will auto reStart after published."),!1):(this._log.info("[CDNStreaming] Main stream has not already published, will auto reStart after published."),!1)}changeDataStatus(e,t){const r=this._paramsForTencentCDN.get(e),o=__spreadValues(__spreadValues({},r),t);this._paramsForTencentCDN.set(e,o)}async startPublishTencentCDN(e){if(this._log.info(`[CDNStreaming] startPublishTencentCDN ${JSON.stringify(e)}`),this.installEvents(),this.changeDataStatus(e.publishMode,{target:e,isStarted:!0}),!this.isStreamPublished(e.publishMode))return;const t=e.streamId||"",r=this.generatePublishCDNStreamId(t,e.publishMode),o=this.generatePublishCDNSessionId(e.publishMode),i="publish-sub-stream-to-cdn"===e.publishMode?1:0,s={requestTime:Date.now(),sessionId:o,streamId:r,streamType:i};await this.doStartPublishTencentCDN(s,e.publishMode);const{appId:a,bizId:n,url:d}=e;if(a&&n&&d){const t=this._paramsForTencentCDN.get(e.publishMode)||this._initParamsForTencentCDN;(null==t?void 0:t.givenCDNManager)||(t.givenCDNManager=new GivenCDNManager(this._core,this._log),this._paramsForTencentCDN.set(e.publishMode,t)),await t.givenCDNManager.startPublishGivenCDN({publishMode:e.publishMode,appId:a,bizId:n,url:d,streamId:r})}}async doStartPublishTencentCDN(e,t){this._log.info(`[CDNStreaming] doStartPublishTencentCDN: ${JSON.stringify(e)}`);let r=0;for(;;){const o=await this._room.sendStartPublishCDN(e,!0),{code:i}=o.data;let{message:s}=o.data;if(0===i){this._log.info("[CDNStreaming] server success: start tencent cdn"),this.changeDataStatus(t,{isPublished:!0});break}if(!(-10006===i&&r<6))throw this.changeDataStatus(t,{isPublished:!1}),-102083===i&&(s=`Please enable relayed-push in ${this._core.constants.CLOUD_CONSOLE_URL} and try later, refer to ${this._core.constants.DOC_URL}tutorial-26-advanced-publish-cdn-stream.html`),this._log.error(`[CDNStreaming] server failed: start tencent cdn errCode: ${i} errMsg: ${s}`),new Error(`[CDNStreaming] server failed: start tencent cdn errCode: ${i} errMsg: ${s}`);this._log.warn(`[CDNStreaming] doStartPublishTencentCDN: retry...${r+1}/6, reason: ${s}`),r+=1,await new Promise((e=>setTimeout(e,500)))}}async stopPublishTencentCDN(e){this._log.info(`[CDNStreaming] doStartPublishTencentCDN: ${JSON.stringify(e)}`);const t=this._paramsForTencentCDN.get(e)||this._initParamsForTencentCDN;if(t.isPublished){const{target:r}=t;(null==r?void 0:r.bizId)&&r.appId&&r.url&&(null==t?void 0:t.givenCDNManager)&&await(null==t?void 0:t.givenCDNManager.stopPublishGivenCDN()),await this.doStopPublishTencentCDN(e)}this._paramsForTencentCDN.set(e,this._initParamsForTencentCDN)}async doStopPublishTencentCDN(e){const t={requestTime:Date.now(),sessionId:(0,import_blueimp_md52.default)(`${this._room.roomId}_${this._room.userId}_${this.convertPublishModeToStreamType(e)}`)};this._log.info(`[CDNStreaming] doStopPublishTencentCDN: ${JSON.stringify(t)}`);const r=await this._room.sendStopPublishCDN(t,!0),{code:o}=r.data;let{message:i}=r.data;if(0!==o)throw-102069===o&&(this._paramsForTencentCDN.set(e,this._initParamsForTencentCDN),i=`can not stop in auto relayed-push mode ${i}`),this._log.error(`[CDNStreaming] server failed: stop tencent cdn errCode: ${o} errMsg: ${i}`),new Error(`[CDNStreaming] server failed: stop tencent cdn errCode: ${o} errMsg: ${i}`);this._log.info("[CDNStreaming] server success: stop tencent cdn"),this._paramsForTencentCDN.set(e,this._initParamsForTencentCDN),this.reset(e)}reset(e){this.uninstallEvents(),this._paramsForTencentCDN.set(e,this._initParamsForTencentCDN)}generatePublishCDNStreamId(e,t){if(""===e){let e=`${this._room.roomId}_${this._room.userId}_${this.convertPublishModeToStreamType(t)}`;return/^[A-Za-z\d_-]*$/.test(e)||(e=(0,import_blueimp_md52.default)(e)),`${this._room.sdkAppId}_${e}`}return e}convertPublishModeToStreamType(e){return"publish-main-stream-to-cdn"===e?"main":"aux"}generatePublishCDNSessionId(e){return(0,import_blueimp_md52.default)(`${this._room.roomId}_${this._room.userId}_${this.convertPublishModeToStreamType(e)}`)}},import_blueimp_md53=__toESM(require_md5(),1),PushStreamToRoom=class{constructor(e,t){__publicField(this,"_core"),__publicField(this,"_room"),__publicField(this,"_log"),__publicField(this,"_seq"),__publicField(this,"_taskId",null),__publicField(this,"_startData",null),__publicField(this,"_updateData",null),__publicField(this,"_stopData",null),this._core=e,this._room=e.room,this._log=t,this._seq=0}async startPushStreamToRoom(e){var t,r;this._seq+=1,this._startData=__spreadValues({roomid:String(this._room.roomId),roomType:this._room.useStringRoomId?1:0,sessionId:(0,import_blueimp_md53.default)(`${this._room.roomId}_${this._room.userId}_start`),agentParam:{cdnRobotUserid:`mcu_robot_${this._room.roomId}_${this._room.userId}`}},this.getCommonParams(e)),this._log.info(`startPushStreamToRoom: ${JSON.stringify(this._startData)}`);const o=await this._room.sendStartPushStreamToRoom(this._startData),{code:i,message:s}=o.data;0===i?(this._taskId=null==(r=null==(t=o.data)?void 0:t.data)?void 0:r.taskId,this._taskId||this.reportServerError("startPushStreamToRoom",i,`can't resolve task id: ${JSON.stringify(o.data)}`),this._log.info("[CDNStreaming] server success: taskId",this._taskId)):this.reportServerError("startPushStreamToRoom",i,s)}async updatePushStreamToRoom(e){this._seq+=1,this._updateData=__spreadProps(__spreadValues({taskid:this._taskId},this.getCommonParams(e)),{enableNtpSync:!0}),this._log.info(`updatePushStreamToRoom: ${JSON.stringify(this._updateData)}`);const t=await this._room.sendUpdatePushStreamToRoom(this._updateData),{code:r,message:o}=t.data;0===r?this._log.info("server success: updatePushStreamToRoom"):this.reportServerError("updatePushStreamToRoom",r,o)}async stopPushStreamToRoom(){this._seq+=1,this._stopData={sdkappid:this._room.sdkAppId,taskid:this._taskId},this._log.info(`stopPushStreamToRoom: ${JSON.stringify(this._stopData)}`);const e=await this._room.sendStopPushStreamToRoom(this._stopData),{code:t,message:r}=e.data;0===t?this._log.info("server success: start mix"):this.reportServerError("stopPushStreamToRoom",t,r)}reportServerError(e,t,r){const o=`server failed: ${e} errCode: ${t} errMsg: ${r}`;throw this._log.error(o),new Error(o)}getPushRtcRoomParams(e){const{robotUser:t}=e.target;return t?[{roomid:String((null==t?void 0:t.roomId)||(null==t?void 0:t.strRoomId))||this._room.roomId,roomType:(null==t?void 0:t.roomId)?0:1,pushRobotUserid:null==t?void 0:t.userId}]:[]}getCommonParams(e){return{sdkappid:this._room.sdkAppId,transcode:!0,audioParam:this.getAudioParam(e),videoParam:this.getVideoParam(e),pushRtcRoomParams:this.getPushRtcRoomParams(e),sequenceNumber:this._seq}}getAudioParam(e){const{mix:t={},encoding:r={}}=e,o={audioSamplerate:r.audioSampleRate||48e3,audioBitrateKbps:r.audioBitrate||64,audioChannels:r.audioChannels||1},{audioMixUserList:i}=t;return{audioEncodeParam:o,mixAudioUsers:(null==i?void 0:i.map((e=>({roomid:String(e.roomId||e.strRoomId)||this._room.roomId,userid:e.userId,roomType:e.roomId?0:1}))))||[]}}getVideoParam(e){const{mix:t={},encoding:r={}}=e,o={videoCodec:2,videoWidth:r.videoWidth||640,videoHeight:r.videoHeight||480,videoFramerate:r.videoFramerate||15,videoGop:r.videoGOP||2,videoBitrateKbps:r.videoBitrate||800},{videoLayoutList:i}=t;return{videoEncodeParam:o,layoutParams:(null==i?void 0:i.map((e=>({userMediaStream:{userInfo:{roomid:String(e.fixedVideoUser.roomId||e.fixedVideoUser.strRoomId)||this._room.roomId,userid:e.fixedVideoUser.userId,roomType:e.fixedVideoUser.roomId?0:1},streamType:"sub"===e.fixedVideoStreamType?1:0},imageWidth:e.width||0,imageHeight:e.height||0,locationX:e.locationX||0,locationY:e.locationY||0,imageZorder:e.zOrder||1,renderMode:e.fillMode||0}))))||[],backgroundColor:t.backgroundColor||0,backgroundImageUrl:t.backgroundImage||""}}},isString=e=>"string"==typeof e;function streamIdValidate(e,t,r,o){if(!/^[A-Za-z\d_-]*$/.test(e)){const{RtcError:e,ErrorCode:t,ErrorCodeDictionary:r}=errorModule;throw new e({code:t.INVALID_PARAMETER,extraCode:r.INVALID_STREAM_ID,messageParams:{key:"streamId"}})}}function roomIdValidate(e,t,r,o){const{RtcError:i,ErrorCode:s,ErrorCodeDictionary:a}=errorModule;if(isString(e))throw new i({code:s.INVALID_PARAMETER,extraCode:a.INVALID_ROOM_ID_INTEGER_STRING,fnName:r,messageParams:{key:"roomId"}});if(void 0!==e){if(!(/^[1-9]\d*$/.test(String(e))&&e<4294967295))throw new i({code:s.INVALID_PARAMETER,extraCode:a.INVALID_ROOM_ID_INTEGER,fnName:r,messageParams:{key:"roomId"}})}}function strRoomIdValidate(e,t,r,o){const{RtcError:i,ErrorCode:s,ErrorCodeDictionary:a}=errorModule;if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(e))throw new i({code:s.INVALID_PARAMETER,extraCode:a.INVALID_ROOM_ID_STRING,fnName:r,messageParams:{key:"strRoomId"}})}var notLessThanZero={type:"number",notLessThanZero:!0},UserRule={type:"object",properties:{userId:{required:!0,type:"string"},roomId:{type:["string","number"],validate:roomIdValidate},strRoomId:{type:"string",validate:strRoomIdValidate}}},TargetRule={required:!0,properties:{publishMode:{required:!0,values:["publish-main-stream-to-cdn","publish-mix-stream-to-cdn","publish-sub-stream-to-cdn","publish-mix-stream-to-room"]},streamId:{required:!1,type:"string",validate:streamIdValidate},appId:{type:"number",allowEmpty:!1},bizId:{type:"number",allowEmpty:!1},url:{type:"string",allowEmpty:!1},robotUser:__spreadValues({},UserRule)},validate(e,t,r,o){const{publishMode:i,robotUser:s}=e;if("publish-mix-stream-to-room"===i&&!s){const{RtcError:e,ErrorCode:t}=errorModule;throw new e({code:t.INVALID_PARAMETER,message:"Invalid parameter target, the value of publishMode is PublishMixStreamToRoom, robotUser is required."})}}},EncodingRule={required:!1,type:"object",properties:{videoWidth:notLessThanZero,videoHeight:notLessThanZero,videoBitrate:__spreadProps(__spreadValues({},notLessThanZero),{allowEmpty:!1}),videoFramerate:{type:"number",validate(e,t,r,o){if(e<=0||e>30){const{RtcError:e,ErrorCode:t}=errorModule;throw new e({code:t.INVALID_PARAMETER,message:"Invalid parameter mixConfig -> videoFramerate, the value must be between (0, 30]."})}}},videoGOP:{type:"number",validate(e,t,r,o){if(e<1||e>8){const{RtcError:e,ErrorCode:t}=errorModule;throw new e({code:t.INVALID_PARAMETER,message:"Invalid parameter mixConfig -> videoGOP, the value must be between [1, 8]."})}}},audioSampleRate:notLessThanZero,audioBitrate:{type:"number",validate(e,t,r,o){if(e<32||e>192){const{RtcError:e,ErrorCode:t}=errorModule;throw new e({code:t.INVALID_PARAMETER,message:"Invalid parameter mixConfig -> audioBitrate, the value must be between [32, 192]."})}}},audioChannels:{type:"number",values:[1,2]}}},MixRule={required:!1,type:"object",properties:{backgroundColor:{type:"number"},backgroundImage:{type:"string"},audioMixUserList:{type:"array",arrayItem:__spreadValues({},UserRule)},videoLayoutList:{type:"array",required:!0,arrayItem:{type:"object",properties:{fixedVideoUser:__spreadValues({},UserRule),fixedVideoStreamType:{type:"string",required:!0,values:["main","sub"]},fillMode:{type:"number",values:[0,1,2,4]},zOrder:{type:"number",required:!0,validate(e,t,r,o){if(e<1||e>15){const{RtcError:e,ErrorCode:t}=errorModule;throw new e({code:t.INVALID_PARAMETER,message:"Invalid parameter mix -> videoLayoutList -> zOrder, the value must be between [1, 15]."})}}},width:notLessThanZero,height:notLessThanZero,locationX:notLessThanZero,locationY:notLessThanZero}}}}};function startValidateRule(e){return errorModule=e.errorModule,{name:"CDNStreamingOptions",type:"object",required:!0,allowEmpty:!1,properties:{target:__spreadValues({},TargetRule),encoding:__spreadValues({},EncodingRule),mix:__spreadValues({},MixRule)},validate(t,r,o,i){var s,a;const{publishMode:n}=t.target,{encoding:d,mix:u}=t;if("publish-mix-stream-to-cdn"===n){const{RtcError:t,ErrorCode:r,ErrorCodeDictionary:i}=e.errorModule;if(!d)throw new t({code:r.INVALID_PARAMETER,extraCode:i.INVALID_PARAMETER_REQUIRED,fnName:o,messageParams:{key:"encoding"}});if(!u)throw new t({code:r.INVALID_PARAMETER,extraCode:i.INVALID_PARAMETER_REQUIRED,fnName:o,messageParams:{key:"mix"}});if(u&&u.videoLayoutList){let o=0,i=0;const n=[];if(u.videoLayoutList.forEach(((e,t)=>{n.push(e.fixedVideoUser.userId),e.width+e.locationX>o&&(o=e.width+e.locationX),e.height+e.locationY>i&&(i=e.height+e.locationY)})),n.indexOf(e.room.userId)<0)throw new t({code:r.INVALID_PARAMETER,message:"Invalid parameter mix -> videoLayoutList, the value must be include self."});const l=null!=(s=null==d?void 0:d.videoWidth)?s:640,h=null!=(a=null==d?void 0:d.videoHeight)?a:480;if(l<o||h<i)throw new t({code:r.INVALID_PARAMETER,message:"Invalid parameter encoding, the width and height of the mixed video must encompass all the mixed-in video streams."})}}}}}function updateValidateRule(e){return errorModule=e.errorModule,{name:"CDNStreamingOptions",type:"object",required:!0,allowEmpty:!1,properties:{target:__spreadValues({},TargetRule),encoding:__spreadValues({},EncodingRule),mix:__spreadValues({},MixRule)}}}function stopValidateRule(e){return errorModule=e.errorModule,{name:"CDNStreamingOptions",type:"object",required:!0,allowEmpty:!1,properties:{target:{required:!0,properties:{publishMode:{required:!0,values:["publish-main-stream-to-cdn","publish-mix-stream-to-cdn","publish-sub-stream-to-cdn","publish-mix-stream-to-room"]}}}}}}var cdnSeq=0,_CDNStreaming=class e{constructor(e){this.core=e,__publicField(this,"_mixTranscodeManager"),__publicField(this,"_publishCDNManager"),__publicField(this,"_pushStreamToRoomManager"),__publicField(this,"_core"),__publicField(this,"_modeOptions"),__publicField(this,"seq"),__publicField(this,"_log"),cdnSeq+=1,this.seq=cdnSeq,this._log=e.log.createChild({id:`${this.getAlias()}${cdnSeq}`}),this._log.info(`[CDNStreaming] created id=${this.getAlias()}${cdnSeq}`),this._core=e,this._modeOptions=new Map,this._mixTranscodeManager=new MixTranscodeManager(e,this._log),this._publishCDNManager=new PublishCDNManager(e,this._log),this._pushStreamToRoomManager=new PushStreamToRoom(e,this._log)}getName(){return e.Name}getAlias(){return"cdn"}getValidateRule(e){switch(e){case"start":return startValidateRule(this._core);case"update":return updateValidateRule(this._core);case"stop":return stopValidateRule(this._core)}}getGroup(e){return e.target.publishMode}async start(e){return this._modeOptions.set(e.target.publishMode,e),"publish-mix-stream-to-room"===e.target.publishMode?this._pushStreamToRoomManager.startPushStreamToRoom(e):await this.doStart(e)}async update(e){const t=this._modeOptions.get(e.target.publishMode);return this._core.utils.deepMerge(t,e),"publish-mix-stream-to-room"===e.target.publishMode?this._pushStreamToRoomManager.updatePushStreamToRoom(t):await this.doStart(t)}async stop(e){switch(e.target.publishMode){case"publish-mix-stream-to-cdn":await this._mixTranscodeManager.stopMixTranscode();break;case"publish-main-stream-to-cdn":case"publish-sub-stream-to-cdn":await this._publishCDNManager.stopPublishTencentCDN(e.target.publishMode);break;case"publish-mix-stream-to-room":this._pushStreamToRoomManager.stopPushStreamToRoom()}this._modeOptions.delete(e.target.publishMode)}async doStart(e){switch(this._log.info(`[CDNStreaming] doStart: ${JSON.stringify(e)}`),e.target.publishMode){case"publish-mix-stream-to-cdn":await this._mixTranscodeManager.startMixTranscode(e);break;case"publish-main-stream-to-cdn":case"publish-sub-stream-to-cdn":await this._publishCDNManager.startPublishTencentCDN(e.target)}}};__publicField(_CDNStreaming,"TYPE",{PublishMode:{PublishMainStreamToCDN:"publish-main-stream-to-cdn",PublishSubStreamToCDN:"publish-sub-stream-to-cdn",PublishMixStreamToCDN:"publish-mix-stream-to-cdn",PublishMixStreamToRoom:"publish-mix-stream-to-room"}}),__publicField(_CDNStreaming,"Name","CDNStreaming");var CDNStreaming=_CDNStreaming,index_default=CDNStreaming;export{index_default as default};export{CDNStreaming};export const PublishMode=CDNStreaming.TYPE.PublishMode;
|
|
1
|
+
var errorModule,__create=Object.create,__defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__commonJS=(e,t)=>function(){return t||(0,e[__getOwnPropNames(e)[0]])((t={exports:{}}).exports,t),t.exports},__copyProps=(e,t,r,o)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let i of __getOwnPropNames(t))__hasOwnProp.call(e,i)||i===r||__defProp(e,i,{get:()=>t[i],enumerable:!(o=__getOwnPropDesc(t,i))||o.enumerable});return e},__toESM=(e,t,r)=>(r=null!=e?__create(__getProtoOf(e)):{},__copyProps(!t&&e&&e.__esModule?r:__defProp(r,"default",{value:e,enumerable:!0}),e)),require_md5=__commonJS({"../node_modules/.pnpm/blueimp-md5@2.19.0/node_modules/blueimp-md5/js/md5.js"(e,t){"use strict";!function(e){function r(e,t){var r=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(r>>16)<<16|65535&r}function o(e,t,o,i,s,a){return r((n=r(r(t,e),r(i,a)))<<(d=s)|n>>>32-d,o);var n,d}function i(e,t,r,i,s,a,n){return o(t&r|~t&i,e,t,s,a,n)}function s(e,t,r,i,s,a,n){return o(t&i|r&~i,e,t,s,a,n)}function a(e,t,r,i,s,a,n){return o(t^r^i,e,t,s,a,n)}function n(e,t,r,i,s,a,n){return o(r^(t|~i),e,t,s,a,n)}function d(e,t){var o,d,m,h,u;e[t>>5]|=128<<t%32,e[14+(t+64>>>9<<4)]=t;var l=1732584193,c=-271733879,p=-1732584194,g=271733878;for(o=0;o<e.length;o+=16)d=l,m=c,h=p,u=g,l=i(l,c,p,g,e[o],7,-680876936),g=i(g,l,c,p,e[o+1],12,-389564586),p=i(p,g,l,c,e[o+2],17,606105819),c=i(c,p,g,l,e[o+3],22,-1044525330),l=i(l,c,p,g,e[o+4],7,-176418897),g=i(g,l,c,p,e[o+5],12,1200080426),p=i(p,g,l,c,e[o+6],17,-1473231341),c=i(c,p,g,l,e[o+7],22,-45705983),l=i(l,c,p,g,e[o+8],7,1770035416),g=i(g,l,c,p,e[o+9],12,-1958414417),p=i(p,g,l,c,e[o+10],17,-42063),c=i(c,p,g,l,e[o+11],22,-1990404162),l=i(l,c,p,g,e[o+12],7,1804603682),g=i(g,l,c,p,e[o+13],12,-40341101),p=i(p,g,l,c,e[o+14],17,-1502002290),l=s(l,c=i(c,p,g,l,e[o+15],22,1236535329),p,g,e[o+1],5,-165796510),g=s(g,l,c,p,e[o+6],9,-1069501632),p=s(p,g,l,c,e[o+11],14,643717713),c=s(c,p,g,l,e[o],20,-373897302),l=s(l,c,p,g,e[o+5],5,-701558691),g=s(g,l,c,p,e[o+10],9,38016083),p=s(p,g,l,c,e[o+15],14,-660478335),c=s(c,p,g,l,e[o+4],20,-405537848),l=s(l,c,p,g,e[o+9],5,568446438),g=s(g,l,c,p,e[o+14],9,-1019803690),p=s(p,g,l,c,e[o+3],14,-187363961),c=s(c,p,g,l,e[o+8],20,1163531501),l=s(l,c,p,g,e[o+13],5,-1444681467),g=s(g,l,c,p,e[o+2],9,-51403784),p=s(p,g,l,c,e[o+7],14,1735328473),l=a(l,c=s(c,p,g,l,e[o+12],20,-1926607734),p,g,e[o+5],4,-378558),g=a(g,l,c,p,e[o+8],11,-2022574463),p=a(p,g,l,c,e[o+11],16,1839030562),c=a(c,p,g,l,e[o+14],23,-35309556),l=a(l,c,p,g,e[o+1],4,-1530992060),g=a(g,l,c,p,e[o+4],11,1272893353),p=a(p,g,l,c,e[o+7],16,-155497632),c=a(c,p,g,l,e[o+10],23,-1094730640),l=a(l,c,p,g,e[o+13],4,681279174),g=a(g,l,c,p,e[o],11,-358537222),p=a(p,g,l,c,e[o+3],16,-722521979),c=a(c,p,g,l,e[o+6],23,76029189),l=a(l,c,p,g,e[o+9],4,-640364487),g=a(g,l,c,p,e[o+12],11,-421815835),p=a(p,g,l,c,e[o+15],16,530742520),l=n(l,c=a(c,p,g,l,e[o+2],23,-995338651),p,g,e[o],6,-198630844),g=n(g,l,c,p,e[o+7],10,1126891415),p=n(p,g,l,c,e[o+14],15,-1416354905),c=n(c,p,g,l,e[o+5],21,-57434055),l=n(l,c,p,g,e[o+12],6,1700485571),g=n(g,l,c,p,e[o+3],10,-1894986606),p=n(p,g,l,c,e[o+10],15,-1051523),c=n(c,p,g,l,e[o+1],21,-2054922799),l=n(l,c,p,g,e[o+8],6,1873313359),g=n(g,l,c,p,e[o+15],10,-30611744),p=n(p,g,l,c,e[o+6],15,-1560198380),c=n(c,p,g,l,e[o+13],21,1309151649),l=n(l,c,p,g,e[o+4],6,-145523070),g=n(g,l,c,p,e[o+11],10,-1120210379),p=n(p,g,l,c,e[o+2],15,718787259),c=n(c,p,g,l,e[o+9],21,-343485551),l=r(l,d),c=r(c,m),p=r(p,h),g=r(g,u);return[l,c,p,g]}function m(e){var t,r="",o=32*e.length;for(t=0;t<o;t+=8)r+=String.fromCharCode(e[t>>5]>>>t%32&255);return r}function h(e){var t,r=[];for(r[(e.length>>2)-1]=void 0,t=0;t<r.length;t+=1)r[t]=0;var o=8*e.length;for(t=0;t<o;t+=8)r[t>>5]|=(255&e.charCodeAt(t/8))<<t%32;return r}function u(e){var t,r,o="0123456789abcdef",i="";for(r=0;r<e.length;r+=1)t=e.charCodeAt(r),i+=o.charAt(t>>>4&15)+o.charAt(15&t);return i}function l(e){return unescape(encodeURIComponent(e))}function c(e){return function(e){return m(d(h(e),8*e.length))}(l(e))}function p(e,t){return function(e,t){var r,o,i=h(e),s=[],a=[];for(s[15]=a[15]=void 0,i.length>16&&(i=d(i,8*e.length)),r=0;r<16;r+=1)s[r]=909522486^i[r],a[r]=1549556828^i[r];return o=d(s.concat(h(t)),512+8*t.length),m(d(a.concat(o),640))}(l(e),l(t))}function g(e,t,r){return t?r?p(t,e):u(p(t,e)):r?c(e):u(c(e))}"function"==typeof define&&define.amd?define((function(){return g})):"object"==typeof t&&t.exports?t.exports=g:e.md5=g}(e)}}),import_blueimp_md5=__toESM(require_md5(),1),MIX_INPUT_TYPE={IT_AUDIO_VIDEO:0,IT_PICTURE:2,IT_CANVAS:3,IT_PURE_AUDIO:4,IT_PURE_VIDEO:5},GivenCDNManager=class{_core;_room;_log;_params;_publishGivenCDNData=null;get isPublishingGivenCDN(){return!!this._params}constructor(e,t){this._core=e,this._room=e.room,this._log=t}async startPublishGivenCDN(e){if(this._log.info(`[CDNStreaming] startPublishGivenCDN() current: ${JSON.stringify(this._params)}, params: ${JSON.stringify(e)}`),this.isPublishingGivenCDN){const{appId:t,bizId:r,url:o}=this._params||{};if(t===e.appId&&r===e.bizId&&o===e.url)return;await this.stopPublishGivenCDN()}this._params=e,this._publishGivenCDNData={pushRequestTime:Date.now(),pushAppId:e.appId,pushBizId:e.bizId,pushCdnUrl:e.url,pushStreamType:this.convertStreamType(e?.publishMode),pushStreamId:e.streamId};try{const t=await this._room.sendStartPublishCDN(this._publishGivenCDNData,!1),{code:r,message:o}=t.data;if(0!==r)throw this.resetGivenCDN(),this._log.error(`[CDNStreaming] server failed: start given cdn errCode: ${r} errMsg: ${o} options: ${JSON.stringify(e)}`),new Error(`[CDNStreaming] server failed: start given cdn errCode: ${r} errMsg: ${o}`);this._log.info("[CDNStreaming] server success: start given cdn.")}catch(e){throw this.resetGivenCDN(),e}}async stopPublishGivenCDN(){if(this._log.info("[CDNStreaming] stopPublishGivenCDN"),!this.isPublishingGivenCDN||!this._publishGivenCDNData)return void this.resetGivenCDN();const{pushAppId:e,pushBizId:t,pushCdnUrl:r,pushStreamType:o,pushStreamId:i}=this._publishGivenCDNData,s={pushRequestTime:Date.now(),pushAppId:e,pushBizId:t,pushCdnUrl:r,pushStreamType:o,pushStreamId:i},a=await this._room.sendStopPublishCDN(s,!1),{code:n,message:d}=a.data;if(0!==n)throw this._log.error(`[CDNStreaming] server failed: stop given cdn errCode: ${n} errMsg: ${d} data: ${JSON.stringify(s)}`),new Error(`[CDNStreaming] server failed: stop given cdn errCode: ${n} errMsg: ${d}`);this._log.info("[CDNStreaming] server success: stop given cdn."),this.resetGivenCDN()}resetGivenCDN(){this._publishGivenCDNData=null,this._params=void 0}convertStreamType(e){return"publish-sub-stream-to-cdn"===e?"aux":"main"}},MixTranscodeManager=class{_core;_room;_log;_config=null;_data=null;_givenCDNManager;get isMixing(){return!!this._data}get isStarted(){return!!this._config}get hasCustomCDN(){return this._config?.target.appId&&this._config?.target.bizId&&this._config?.target.url}constructor(e,t){this._core=e,this._room=e.room,this._log=t,this.reset()}async startMixTranscode(e){if(this._log.info(`startMixTranscode: ${JSON.stringify(e)}`),this._config=e,this.installEvents(),this._core.room.isJoined)try{const t=this.getInputParam(e),r=this.getOutputParam(e),o=this.getOutputSessionId({config:e,roomId:this._room.roomId,userId:this._room.userId});this.isMixing&&this._data&&o!==this._data.outputSessionId&&(this._log.info("[CDNStreaming] streamId changed, auto stop mixing before start"),await this.doStopMixTranscode()),await this.doStartMixTranscode({outputSessionId:o,inputParam:t,outputParam:r});const{appId:i,bizId:s,url:a,streamId:n=""}=e.target;i&&s&&a&&(this._givenCDNManager||(this._givenCDNManager=new GivenCDNManager(this._core,this._log)),await this._givenCDNManager.startPublishGivenCDN({publishMode:e.target.publishMode,appId:i,bizId:s,url:a,streamId:n}))}catch(e){throw this.reset(),e}}async doStartMixTranscode({outputSessionId:e,inputParam:t,outputParam:r}){const o={roomId:String(this._room.roomId),mcuRequestTime:Date.now(),outputSessionId:e,inputParam:t,outputParam:r};this._log.info(`[CDNStreaming] doStartMixTranscode: ${JSON.stringify(o)}`);const i=await this._room.sendStartMixTranscode(o),{code:s}=i.data;let{message:a}=i.data;if(0!==s)throw-102083===s&&(a=`Please enable relayed-push in ${this._core.constants.CLOUD_CONSOLE_URL} and try later, refer to ${this._core.constants.DOC_URL}tutorial-26-advanced-publish-cdn-stream.html`),this._log.error(`[CDNStreaming] server failed: start mix errCode: ${s} errMsg: ${a}`),new Error(`[CDNStreaming] server failed: start mix errCode: ${s} errMsg: ${a}`);this._log.info("[CDNStreaming] server success: start mix"),this._data=o}async stopMixTranscode(){this._log.info("[CDNStreaming] stopMixTranscode");try{this.isStarted&&this.isMixing&&(await this.doStopMixTranscode(),this._config&&this.hasCustomCDN&&this._givenCDNManager&&await this._givenCDNManager.stopPublishGivenCDN())}catch(e){throw e}this.reset()}async doStopMixTranscode(){const e={mcuRequestTime:Date.now(),outputSessionId:this._data.outputSessionId,streamType:this._data.outputParam.streamType};this._log.info(`[CDNStreaming] doStopMixTranscode: ${JSON.stringify(e)}`);const t=await this._room.sendStopMixTranscode(e),{code:r,message:o}=t.data;if(0!==r)throw this._log.error(`[CDNStreaming] server failed: stop mix errCode: ${r} errMsg: ${o}`),new Error(`[CDNStreaming] server failed: stop mix errCode: ${r} errMsg: ${o}`);this._log.info("[CDNStreaming] server success: stop mix"),this.reset()}reset(){this._config=null,this._data=null,this.uninstallEvents()}installEvents(){this._core.room.on("joined",this.handleRoomJoined,this),this._core.room.on("left",this.handleRoomLeft,this)}uninstallEvents(){this._core.room.off("joined",this.handleRoomJoined,this),this._core.room.off("left",this.handleRoomLeft,this)}async handleRoomJoined(){this._log.info(`[CDNStreaming] handleJoined: ${JSON.stringify(this._config)}`),this.isStarted&&this._config&&await this.startMixTranscode(this._config)}async handleRoomLeft(){this._log.info(`[CDNStreaming] handleRoomLeft: ${JSON.stringify(this._config)}`),this._data=null}getOutputSessionId({config:e,userId:t,roomId:r}){return this._core.utils.isString(e.target.streamId)&&e.target.streamId.length>0?e.target.streamId:(0,import_blueimp_md5.default)(`${r}_${t}_main`)}getStringRoomId(e,t){return e?String(e):t}getInputParam(e){const{mix:t={}}=e,{audioMixUserList:r=[],videoLayoutList:o=[]}=t,i=o.map((e=>({userId:e.fixedVideoUser.userId,roomId:this.getStringRoomId(e.fixedVideoUser.roomId,e.fixedVideoUser.strRoomId)||this._core.room.roomId,width:e.width||0,height:e.height||0,locationX:e.locationX||0,locationY:e.locationY||0,zOrder:e.zOrder||1,streamType:"sub"===e.fixedVideoStreamType?1:0,inputType:MIX_INPUT_TYPE.IT_PURE_VIDEO,renderMode:e.fillMode||0})));return r.forEach((e=>{let t=this._core.room.roomId;(e.roomId||e.strRoomId)&&(t=this.getStringRoomId(e.roomId,e.strRoomId));const r=i.findIndex((r=>r.userId===e.userId&&r.roomId===t));-1!==r?i[r].inputType=MIX_INPUT_TYPE.IT_AUDIO_VIDEO:i.push({userId:e.userId,roomId:e.roomId||e.strRoomId||this._core.room.roomId,inputType:MIX_INPUT_TYPE.IT_PURE_AUDIO})})),i}getOutputParam(e){const t=e.target.streamId||"",{encoding:r={},mix:o={}}=e;return{streamId:t,streamType:t.length>0?1:0,width:this._core.utils.isUndefined(r.videoWidth)?640:r.videoWidth,height:this._core.utils.isUndefined(r.videoHeight)?480:r.videoHeight,videoBps:r.videoBitrate||0,fps:r.videoFramerate||15,gop:r.videoGOP||2,audioSampleRate:r.audioSampleRate||48e3,audioBps:r.audioBitrate||64,audioChannels:r.audioChannels||1,backgroundColor:o.backgroundColor||0,backgroundImg:o.backgroundImage||"",extraInfo:"",videoCodec:2,audioCodec:0}}},import_blueimp_md52=__toESM(require_md5(),1),PublishCDNManager=class{_room;_core;_log;_paramsForTencentCDN;_initParamsForTencentCDN={isPublished:!1,isStarted:!1};constructor(e,t){this._core=e,this._room=e.room,this._log=t,this._paramsForTencentCDN=new Map([["publish-main-stream-to-cdn",this._initParamsForTencentCDN],["publish-sub-stream-to-cdn",this._initParamsForTencentCDN]])}installEvents(){this._core.innerEmitter.on("104",this.handlePublished,this),this._core.room.on("left",this.handleRoomLeft,this)}uninstallEvents(){this._core.innerEmitter.off("104",this.handlePublished,this),this._core.room.off("left",this.handleRoomLeft,this)}async handlePublished({track:e}){if(e.room!==this._room)return;if(this._log.info(`[CDNStreaming] handlePublished: mediaType ${e.mediaType}, roomID ${e?.room?.roomId}`),1===e.mediaType)return;const t=4===e.mediaType?"publish-main-stream-to-cdn":"publish-sub-stream-to-cdn",r=this._paramsForTencentCDN.get(t)||null;r?.target&&r.isStarted&&await this.startPublishTencentCDN(r.target)}async handleRoomLeft(){this._log.info("[CDNStreaming] handleRoomLeft"),this.changeDataStatus("publish-main-stream-to-cdn",{isPublished:!1}),this.changeDataStatus("publish-sub-stream-to-cdn",{isPublished:!1})}isStreamPublished(e){return"publish-main-stream-to-cdn"!==e||this._room.isMainStreamPublished?!("publish-sub-stream-to-cdn"===e&&!this._room.isAuxStreamPublished)||(this._log.info("[CDNStreaming] Sub has not already published, will auto reStart after published."),!1):(this._log.info("[CDNStreaming] Main stream has not already published, will auto reStart after published."),!1)}changeDataStatus(e,t){const r={...this._paramsForTencentCDN.get(e),...t};this._paramsForTencentCDN.set(e,r)}async startPublishTencentCDN(e){if(this._log.info(`[CDNStreaming] startPublishTencentCDN ${JSON.stringify(e)}`),this.installEvents(),this.changeDataStatus(e.publishMode,{target:e,isStarted:!0}),!this.isStreamPublished(e.publishMode))return;const t=e.streamId||"",r=this.generatePublishCDNStreamId(t,e.publishMode),o=this.generatePublishCDNSessionId(e.publishMode),i="publish-sub-stream-to-cdn"===e.publishMode?1:0,s={requestTime:Date.now(),sessionId:o,streamId:r,streamType:i};await this.doStartPublishTencentCDN(s,e.publishMode);const{appId:a,bizId:n,url:d}=e;if(a&&n&&d){const t=this._paramsForTencentCDN.get(e.publishMode)||this._initParamsForTencentCDN;t?.givenCDNManager||(t.givenCDNManager=new GivenCDNManager(this._core,this._log),this._paramsForTencentCDN.set(e.publishMode,t)),await t.givenCDNManager.startPublishGivenCDN({publishMode:e.publishMode,appId:a,bizId:n,url:d,streamId:r})}}async doStartPublishTencentCDN(e,t){this._log.info(`[CDNStreaming] doStartPublishTencentCDN: ${JSON.stringify(e)}`);let r=0;for(;;){const o=await this._room.sendStartPublishCDN(e,!0),{code:i}=o.data;let{message:s}=o.data;if(0===i){this._log.info("[CDNStreaming] server success: start tencent cdn"),this.changeDataStatus(t,{isPublished:!0});break}if(!(-10006===i&&r<6))throw this.changeDataStatus(t,{isPublished:!1}),-102083===i&&(s=`Please enable relayed-push in ${this._core.constants.CLOUD_CONSOLE_URL} and try later, refer to ${this._core.constants.DOC_URL}tutorial-26-advanced-publish-cdn-stream.html`),this._log.error(`[CDNStreaming] server failed: start tencent cdn errCode: ${i} errMsg: ${s}`),new Error(`[CDNStreaming] server failed: start tencent cdn errCode: ${i} errMsg: ${s}`);this._log.warn(`[CDNStreaming] doStartPublishTencentCDN: retry...${r+1}/6, reason: ${s}`),r+=1,await new Promise((e=>setTimeout(e,500)))}}async stopPublishTencentCDN(e){this._log.info(`[CDNStreaming] doStartPublishTencentCDN: ${JSON.stringify(e)}`);const t=this._paramsForTencentCDN.get(e)||this._initParamsForTencentCDN;if(t.isPublished){const{target:r}=t;r?.bizId&&r.appId&&r.url&&t?.givenCDNManager&&await(t?.givenCDNManager.stopPublishGivenCDN()),await this.doStopPublishTencentCDN(e)}this._paramsForTencentCDN.set(e,this._initParamsForTencentCDN)}async doStopPublishTencentCDN(e){const t={requestTime:Date.now(),sessionId:(0,import_blueimp_md52.default)(`${this._room.roomId}_${this._room.userId}_${this.convertPublishModeToStreamType(e)}`)};this._log.info(`[CDNStreaming] doStopPublishTencentCDN: ${JSON.stringify(t)}`);const r=await this._room.sendStopPublishCDN(t,!0),{code:o}=r.data;let{message:i}=r.data;if(0!==o)throw-102069===o&&(this._paramsForTencentCDN.set(e,this._initParamsForTencentCDN),i=`can not stop in auto relayed-push mode ${i}`),this._log.error(`[CDNStreaming] server failed: stop tencent cdn errCode: ${o} errMsg: ${i}`),new Error(`[CDNStreaming] server failed: stop tencent cdn errCode: ${o} errMsg: ${i}`);this._log.info("[CDNStreaming] server success: stop tencent cdn"),this._paramsForTencentCDN.set(e,this._initParamsForTencentCDN),this.reset(e)}reset(e){this.uninstallEvents(),this._paramsForTencentCDN.set(e,this._initParamsForTencentCDN)}generatePublishCDNStreamId(e,t){if(""===e){let e=`${this._room.roomId}_${this._room.userId}_${this.convertPublishModeToStreamType(t)}`;return/^[A-Za-z\d_-]*$/.test(e)||(e=(0,import_blueimp_md52.default)(e)),`${this._room.sdkAppId}_${e}`}return e}convertPublishModeToStreamType(e){return"publish-main-stream-to-cdn"===e?"main":"aux"}generatePublishCDNSessionId(e){return(0,import_blueimp_md52.default)(`${this._room.roomId}_${this._room.userId}_${this.convertPublishModeToStreamType(e)}`)}},import_blueimp_md53=__toESM(require_md5(),1),PushStreamToRoom=class{_core;_room;_log;_seq;_taskId=null;_startData=null;_updateData=null;_stopData=null;constructor(e,t){this._core=e,this._room=e.room,this._log=t,this._seq=0}async startPushStreamToRoom(e){this._seq+=1,this._startData={roomid:String(this._room.roomId),roomType:this._room.useStringRoomId?1:0,sessionId:(0,import_blueimp_md53.default)(`${this._room.roomId}_${this._room.userId}_start`),agentParam:{cdnRobotUserid:`mcu_robot_${this._room.roomId}_${this._room.userId}`},...this.getCommonParams(e)},this._log.info(`startPushStreamToRoom: ${JSON.stringify(this._startData)}`);const t=await this._room.sendStartPushStreamToRoom(this._startData),{code:r,message:o}=t.data;0===r?(this._taskId=t.data?.data?.taskId,this._taskId||this.reportServerError("startPushStreamToRoom",r,`can't resolve task id: ${JSON.stringify(t.data)}`),this._log.info("[CDNStreaming] server success: taskId",this._taskId)):this.reportServerError("startPushStreamToRoom",r,o)}async updatePushStreamToRoom(e){this._seq+=1,this._updateData={taskid:this._taskId,...this.getCommonParams(e),enableNtpSync:!0},this._log.info(`updatePushStreamToRoom: ${JSON.stringify(this._updateData)}`);const t=await this._room.sendUpdatePushStreamToRoom(this._updateData),{code:r,message:o}=t.data;0===r?this._log.info("server success: updatePushStreamToRoom"):this.reportServerError("updatePushStreamToRoom",r,o)}async stopPushStreamToRoom(){this._seq+=1,this._stopData={sdkappid:this._room.sdkAppId,taskid:this._taskId},this._log.info(`stopPushStreamToRoom: ${JSON.stringify(this._stopData)}`);const e=await this._room.sendStopPushStreamToRoom(this._stopData),{code:t,message:r}=e.data;0===t?this._log.info("server success: start mix"):this.reportServerError("stopPushStreamToRoom",t,r)}reportServerError(e,t,r){const o=`server failed: ${e} errCode: ${t} errMsg: ${r}`;throw this._log.error(o),new Error(o)}getPushRtcRoomParams(e){const{robotUser:t}=e.target;return t?[{roomid:String(t?.roomId||t?.strRoomId)||this._room.roomId,roomType:t?.roomId?0:1,pushRobotUserid:t?.userId}]:[]}getCommonParams(e){return{sdkappid:this._room.sdkAppId,transcode:!0,audioParam:this.getAudioParam(e),videoParam:this.getVideoParam(e),pushRtcRoomParams:this.getPushRtcRoomParams(e),sequenceNumber:this._seq}}getAudioParam(e){const{mix:t={},encoding:r={}}=e,o={audioSamplerate:r.audioSampleRate||48e3,audioBitrateKbps:r.audioBitrate||64,audioChannels:r.audioChannels||1},{audioMixUserList:i}=t;return{audioEncodeParam:o,mixAudioUsers:i?.map((e=>({roomid:String(e.roomId||e.strRoomId)||this._room.roomId,userid:e.userId,roomType:e.roomId?0:1})))||[]}}getVideoParam(e){const{mix:t={},encoding:r={}}=e,o={videoCodec:2,videoWidth:r.videoWidth||640,videoHeight:r.videoHeight||480,videoFramerate:r.videoFramerate||15,videoGop:r.videoGOP||2,videoBitrateKbps:r.videoBitrate||800},{videoLayoutList:i}=t;return{videoEncodeParam:o,layoutParams:i?.map((e=>({userMediaStream:{userInfo:{roomid:String(e.fixedVideoUser.roomId||e.fixedVideoUser.strRoomId)||this._room.roomId,userid:e.fixedVideoUser.userId,roomType:e.fixedVideoUser.roomId?0:1},streamType:"sub"===e.fixedVideoStreamType?1:0},imageWidth:e.width||0,imageHeight:e.height||0,locationX:e.locationX||0,locationY:e.locationY||0,imageZorder:e.zOrder||1,renderMode:e.fillMode||0})))||[],backgroundColor:t.backgroundColor||0,backgroundImageUrl:t.backgroundImage||""}}},isString=e=>"string"==typeof e;function streamIdValidate(e,t,r,o){if(!/^[A-Za-z\d_-]*$/.test(e)){const{RtcError:e,ErrorCode:t,ErrorCodeDictionary:r}=errorModule;throw new e({code:t.INVALID_PARAMETER,extraCode:r.INVALID_STREAM_ID,messageParams:{key:"streamId"}})}}function roomIdValidate(e,t,r,o){const{RtcError:i,ErrorCode:s,ErrorCodeDictionary:a}=errorModule;if(isString(e))throw new i({code:s.INVALID_PARAMETER,extraCode:a.INVALID_ROOM_ID_INTEGER_STRING,fnName:r,messageParams:{key:"roomId"}});if(void 0!==e){if(!(/^[1-9]\d*$/.test(String(e))&&e<4294967295))throw new i({code:s.INVALID_PARAMETER,extraCode:a.INVALID_ROOM_ID_INTEGER,fnName:r,messageParams:{key:"roomId"}})}}function strRoomIdValidate(e,t,r,o){const{RtcError:i,ErrorCode:s,ErrorCodeDictionary:a}=errorModule;if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(e))throw new i({code:s.INVALID_PARAMETER,extraCode:a.INVALID_ROOM_ID_STRING,fnName:r,messageParams:{key:"strRoomId"}})}var notLessThanZero={type:"number",notLessThanZero:!0},UserRule={type:"object",properties:{userId:{required:!0,type:"string"},roomId:{type:["string","number"],validate:roomIdValidate},strRoomId:{type:"string",validate:strRoomIdValidate}}},TargetRule={required:!0,properties:{publishMode:{required:!0,values:["publish-main-stream-to-cdn","publish-mix-stream-to-cdn","publish-sub-stream-to-cdn","publish-mix-stream-to-room"]},streamId:{required:!1,type:"string",validate:streamIdValidate},appId:{type:"number",allowEmpty:!1},bizId:{type:"number",allowEmpty:!1},url:{type:"string",allowEmpty:!1},robotUser:{...UserRule}},validate(e,t,r,o){const{publishMode:i,robotUser:s}=e;if("publish-mix-stream-to-room"===i&&!s){const{RtcError:e,ErrorCode:t}=errorModule;throw new e({code:t.INVALID_PARAMETER,message:"Invalid parameter target, the value of publishMode is PublishMixStreamToRoom, robotUser is required."})}}},EncodingRule={required:!1,type:"object",properties:{videoWidth:notLessThanZero,videoHeight:notLessThanZero,videoBitrate:{...notLessThanZero,allowEmpty:!1},videoFramerate:{type:"number",validate(e,t,r,o){if(e<=0||e>30){const{RtcError:e,ErrorCode:t}=errorModule;throw new e({code:t.INVALID_PARAMETER,message:"Invalid parameter mixConfig -> videoFramerate, the value must be between (0, 30]."})}}},videoGOP:{type:"number",validate(e,t,r,o){if(e<1||e>8){const{RtcError:e,ErrorCode:t}=errorModule;throw new e({code:t.INVALID_PARAMETER,message:"Invalid parameter mixConfig -> videoGOP, the value must be between [1, 8]."})}}},audioSampleRate:notLessThanZero,audioBitrate:{type:"number",validate(e,t,r,o){if(e<32||e>192){const{RtcError:e,ErrorCode:t}=errorModule;throw new e({code:t.INVALID_PARAMETER,message:"Invalid parameter mixConfig -> audioBitrate, the value must be between [32, 192]."})}}},audioChannels:{type:"number",values:[1,2]}}},MixRule={required:!1,type:"object",properties:{backgroundColor:{type:"number"},backgroundImage:{type:"string"},audioMixUserList:{type:"array",arrayItem:{...UserRule}},videoLayoutList:{type:"array",required:!0,arrayItem:{type:"object",properties:{fixedVideoUser:{...UserRule},fixedVideoStreamType:{type:"string",required:!0,values:["main","sub"]},fillMode:{type:"number",values:[0,1,2,4]},zOrder:{type:"number",required:!0,validate(e,t,r,o){if(e<1||e>15){const{RtcError:e,ErrorCode:t}=errorModule;throw new e({code:t.INVALID_PARAMETER,message:"Invalid parameter mix -> videoLayoutList -> zOrder, the value must be between [1, 15]."})}}},width:notLessThanZero,height:notLessThanZero,locationX:notLessThanZero,locationY:notLessThanZero}}}}};function startValidateRule(e){return errorModule=e.errorModule,{name:"CDNStreamingOptions",type:"object",required:!0,allowEmpty:!1,properties:{target:{...TargetRule},encoding:{...EncodingRule},mix:{...MixRule}},validate(t,r,o,i){const{publishMode:s}=t.target,{encoding:a,mix:n}=t;if("publish-mix-stream-to-cdn"===s){const{RtcError:t,ErrorCode:r,ErrorCodeDictionary:i}=e.errorModule;if(!a)throw new t({code:r.INVALID_PARAMETER,extraCode:i.INVALID_PARAMETER_REQUIRED,fnName:o,messageParams:{key:"encoding"}});if(!n)throw new t({code:r.INVALID_PARAMETER,extraCode:i.INVALID_PARAMETER_REQUIRED,fnName:o,messageParams:{key:"mix"}});if(n&&n.videoLayoutList){let o=0,i=0;const s=[];if(n.videoLayoutList.forEach(((e,t)=>{s.push(e.fixedVideoUser.userId),e.width+e.locationX>o&&(o=e.width+e.locationX),e.height+e.locationY>i&&(i=e.height+e.locationY)})),s.indexOf(e.room.userId)<0)throw new t({code:r.INVALID_PARAMETER,message:"Invalid parameter mix -> videoLayoutList, the value must be include self."});if((a?.videoWidth??640)<o||(a?.videoHeight??480)<i)throw new t({code:r.INVALID_PARAMETER,message:"Invalid parameter encoding, the width and height of the mixed video must encompass all the mixed-in video streams."})}}}}}function updateValidateRule(e){return errorModule=e.errorModule,{name:"CDNStreamingOptions",type:"object",required:!0,allowEmpty:!1,properties:{target:{...TargetRule},encoding:{...EncodingRule},mix:{...MixRule}}}}function stopValidateRule(e){return errorModule=e.errorModule,{name:"CDNStreamingOptions",type:"object",required:!0,allowEmpty:!1,properties:{target:{required:!0,properties:{publishMode:{required:!0,values:["publish-main-stream-to-cdn","publish-mix-stream-to-cdn","publish-sub-stream-to-cdn","publish-mix-stream-to-room"]}}}}}}var cdnSeq=0,CDNStreaming=class e{constructor(e){this.core=e,cdnSeq+=1,this.seq=cdnSeq,this._log=e.log.createChild({id:`${this.getAlias()}${cdnSeq}`}),this._log.info(`[CDNStreaming] created id=${this.getAlias()}${cdnSeq}`),this._core=e,this._modeOptions=new Map,this._mixTranscodeManager=new MixTranscodeManager(e,this._log),this._publishCDNManager=new PublishCDNManager(e,this._log),this._pushStreamToRoomManager=new PushStreamToRoom(e,this._log)}static TYPE={PublishMode:{PublishMainStreamToCDN:"publish-main-stream-to-cdn",PublishSubStreamToCDN:"publish-sub-stream-to-cdn",PublishMixStreamToCDN:"publish-mix-stream-to-cdn",PublishMixStreamToRoom:"publish-mix-stream-to-room"}};_mixTranscodeManager;_publishCDNManager;_pushStreamToRoomManager;_core;_modeOptions;seq;_log;static Name="CDNStreaming";getName(){return e.Name}getAlias(){return"cdn"}getValidateRule(e){switch(e){case"start":return startValidateRule(this._core);case"update":return updateValidateRule(this._core);case"stop":return stopValidateRule(this._core)}}getGroup(e){return e.target.publishMode}async start(e){return this._modeOptions.set(e.target.publishMode,e),"publish-mix-stream-to-room"===e.target.publishMode?this._pushStreamToRoomManager.startPushStreamToRoom(e):await this.doStart(e)}async update(e){const t=this._modeOptions.get(e.target.publishMode);return this._core.utils.deepMerge(t,e),"publish-mix-stream-to-room"===e.target.publishMode?this._pushStreamToRoomManager.updatePushStreamToRoom(t):await this.doStart(t)}async stop(e){switch(e.target.publishMode){case"publish-mix-stream-to-cdn":await this._mixTranscodeManager.stopMixTranscode();break;case"publish-main-stream-to-cdn":case"publish-sub-stream-to-cdn":await this._publishCDNManager.stopPublishTencentCDN(e.target.publishMode);break;case"publish-mix-stream-to-room":this._pushStreamToRoomManager.stopPushStreamToRoom()}this._modeOptions.delete(e.target.publishMode)}async doStart(e){switch(this._log.info(`[CDNStreaming] doStart: ${JSON.stringify(e)}`),e.target.publishMode){case"publish-mix-stream-to-cdn":await this._mixTranscodeManager.startMixTranscode(e);break;case"publish-main-stream-to-cdn":case"publish-sub-stream-to-cdn":await this._publishCDNManager.startPublishTencentCDN(e.target)}}},index_default=CDNStreaming;export{index_default as default};export{CDNStreaming};export const PublishMode=CDNStreaming.TYPE.PublishMode;
|