1 |
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self)["jessibuca-audio-demo"]=t()}(this,(function(){"use strict";class t{on(e,t,s){const i=this.e||(this.e={});return(i[e]||(i[e]=[])).push({fn:t,ctx:s}),this}once(e,t,s){const i=this;function A(){i.off(e,A);for(var r=arguments.length,o=new Array(r),a=0;a<r;a++)o[a]=arguments[a];t.apply(s,o)}return A._=t,this.on(e,A,s)}emit(e){const t=((this.e||(this.e={}))[e]||[]).slice();for(var s=arguments.length,i=new Array(s>1?s-1:0),A=1;A<s;A++)i[A-1]=arguments[A];for(let e=0;e<t.length;e+=1)t[e].fn.apply(t[e].ctx,i);return this}off(e,t){const s=this.e||(this.e={});if(!e)return Object.keys(s).forEach((e=>{delete s[e]})),void delete this.e;const i=s[e],A=[];if(i&&t)for(let e=0,s=i.length;e<s;e+=1)i[e].fn!==t&&i[e].fn._!==t&&A.push(i[e]);return A.length?s[e]=A:delete s[e],this}}const s=1,i=2,A=3,r=4,o=5,a=6,n=["","websocket","fetch","hls","webrtc","webTransport","aliyunRtc","ts"],h="fetch",l="hls",u="websocket",d="webrtc",c="webTransport",p="worker",g="aliyunRtc",m="player",f="playerAudio",y="playbackTF",b="flv",B="m7s",C="debug",w="warn",E=1e4,S="init",k="playAudio",T="initAudio",I="audioCode",_="workerFetch",v="workerEnd",R="closeEnd",P="init",D="close",M="updateConfig",N="fetchStream",L="sendWsMessage",Q="fetch",H="destroy",W="destroyEnd",G="buffer",j="fetchError",O="fetchClose",x="fetchSuccess",F={fullscreen:"fullscreen$2",webFullscreen:"webFullscreen",decoderWorkerInit:"decoderWorkerInit",play:"play",playing:"playing",pause:"pause",mute:"mute",load:"load",loading:"loading",zooming:"zooming",videoInfo:"videoInfo",timeUpdate:"timeUpdate",audioInfo:"audioInfo",log:"log",error:"error",kBps:"kBps",timeout:"timeout",delayTimeout:"delayTimeout",delayTimeoutRetryEnd:"delayTimeoutRetryEnd",loadingTimeout:"loadingTimeout",loadingTimeoutRetryEnd:"loadingTimeoutRetryEnd",stats:"stats",performance:"performance",videoSmooth:"videoSmooth",faceDetectActive:"faceDetectActive",objectDetectActive:"objectDetectActive",occlusionDetectActive:"occlusionDetectActive",imageDetectActive:"imageDetectActive",record:"record",recording:"recording",recordingTimestamp:"recordingTimestamp",recordStart:"recordStart",recordEnd:"recordEnd",recordCreateError:"recordCreateError",recordBlob:"recordBlob",buffer:"buffer",videoFrame:"videoFrame",videoSEI:"videoSEI",start:"start",metadata:"metadata",resize:"resize",volumechange:"volumechange",destroy:"destroy",beforeDestroy:"beforeDestroy",streamEnd:"streamEnd",streamRate:"streamRate",streamAbps:"streamAbps",streamVbps:"streamVbps",streamDts:"streamDts",streamSuccess:"streamSuccess",streamMessage:"streamMessage",streamError:"streamError",streamStats:"streamStats",mseSourceOpen:"mseSourceOpen",mseSourceClose:"mseSourceClose",mseSourceended:"mseSourceended",mseSourceStartStreaming:"mseSourceStartStreaming",mseSourceEndStreaming:"mseSourceEndStreaming",mseSourceBufferError:"mseSourceBufferError",mseAddSourceBufferError:"mseAddSourceBufferError",mseSourceBufferBusy:"mseSourceBufferBusy",mseSourceBufferFull:"mseSourceBufferFull",videoWaiting:"videoWaiting",videoTimeUpdate:"videoTimeUpdate",videoSyncAudio:"videoSyncAudio",playToRenderTimes:"playToRenderTimes",playbackTime:"playbackTime",playbackTimestamp:"playbackTimestamp",playbackTimeScroll:"playbackTimeScroll",playbackPrecision:"playbackPrecision",playbackShowPrecisionChange:"playbackShowPrecisionChange",playbackJustTime:"playbackJustTime",playbackStats:"playbackStats",playbackSeek:"playbackSeek",playbackPause:"playbackPause",playbackPauseOrResume:"playbackPauseOrResume",playbackRateChange:"playbackRateChange",playbackPreRateChange:"playbackPreRateChange",ptz:"ptz",streamQualityChange:"streamQualityChange",visibilityChange:"visibilityChange",netBuf:"netBuf",close:"close",networkDelayTimeout:"networkDelayTimeout",togglePerformancePanel:"togglePerformancePanel",viewResizeChange:"viewResizeChange",flvDemuxBufferSizeTooLarge:"flvDemuxBufferSizeTooLarge",talkGetUserMediaSuccess:"talkGetUserMediaSuccess",talkGetUserMediaFail:"talkGetUserMediaFail",talkGetUserMediaTimeout:"talkGetUserMediaTimeout",talkStreamStart:"talkStreamStart",talkStreamOpen:"talkStreamOpen",talkStreamClose:"talkStreamClose",talkStreamError:"talkStreamError",talkStreamInactive:"talkStreamInactive",webrtcDisconnect:"webrtcDisconnect",webrtcFailed:"webrtcFailed",webrtcClosed:"webrtcClosed",webrtcOnConnectionStateChange:"webrtcOnConnectionStateChange",webrtcOnIceConnectionStateChange:"webrtcOnIceConnectionStateChange",crashLog:"crashLog",focus:"focus",blur:"blur",visibilityHiddenTimeout:"visibilityHiddenTimeout",websocketOpen:"websocketOpen",websocketClose:"websocketClose",websocketError:"websocketError",websocketMessage:"websocketMessage",aiObjectDetectorInfo:"aiObjectDetectorInfo",aiFaceDetectorInfo:"aiFaceDetectorInfo",aiOcclusionDetectResult:"aiOcclusionDetectResult",aiImageDetectResult:"aiImageDetectResult",playFailedAndPaused:"playFailedAndPaused",audioResumeState:"audioResumeState",webrtcStreamH265:"webrtcStreamH265",flvMetaData:"flvMetaData",talkFailedAndStop:"talkFailedAndStop",removeLoadingBgImage:"removeLoadingBgImage",memoryLog:"memoryLog",downloadMemoryLog:"downloadMemoryLog",pressureObserverCpu:"pressureObserverCpu",currentPts:"currentPts"},Y={load:F.load,timeUpdate:F.timeUpdate,audioInfo:F.audioInfo,error:F.error,kBps:F.kBps,start:F.start,timeout:F.timeout,loadingTimeout:F.loadingTimeout,loadingTimeoutRetryEnd:F.loadingTimeoutRetryEnd,delayTimeout:F.delayTimeout,delayTimeoutRetryEnd:F.delayTimeoutRetryEnd,play:F.play,pause:F.pause,mute:F.mute,stats:F.stats,playToRenderTimes:F.playToRenderTimes,crashLog:F.crashLog,websocketOpen:F.websocketOpen,websocketClose:F.websocketClose,playFailedAndPaused:F.playFailedAndPaused,audioResumeState:F.audioResumeState},z={playError:"playIsNotPauseOrUrlIsNull",fetchError:"fetchError",websocketError:"websocketError",webcodecsH265NotSupport:"webcodecsH265NotSupport",webcodecsDecodeError:"webcodecsDecodeError",webcodecsUnsupportedConfigurationError:"webcodecsUnsupportedConfigurationError",webcodecsDecodeConfigureError:"webcodecsDecodeConfigureError",mediaSourceH265NotSupport:"mediaSourceH265NotSupport",mediaSourceAudioG711NotSupport:"mediaSourceAudioG711NotSupport",mediaSourceAudioInitTimeout:"mediaSourceAudioInitTimeout",mediaSourceAudioNoDataTimeout:"mediaSourceAudioNoDataTimeout",mediaSourceDecoderConfigurationError:"mediaSourceDecoderConfigurationError",mediaSourceFull:F.mseSourceBufferFull,mseSourceBufferError:F.mseSourceBufferError,mseAddSourceBufferError:F.mseAddSourceBufferError,mediaSourceAppendBufferError:"mediaSourceAppendBufferError",mediaSourceTsIsMaxDiff:"mediaSourceTsIsMaxDiff",mediaSourceUseCanvasRenderPlayFailed:"mediaSourceUseCanvasRenderPlayFailed",mediaSourceBufferedIsZeroError:"mediaSourceBufferedIsZeroError",wasmDecodeError:"wasmDecodeError",wasmUseVideoRenderError:"wasmUseVideoRenderError",hlsError:"hlsError",webrtcError:"webrtcError",webrtcClosed:F.webrtcClosed,webrtcIceCandidateError:"webrtcIceCandidateError",webglAlignmentError:"webglAlignmentError",wasmWidthOrHeightChange:"wasmWidthOrHeightChange",mseWidthOrHeightChange:"mseWidthOrHeightChange",wcsWidthOrHeightChange:"wcsWidthOrHeightChange",widthOrHeightChange:"widthOrHeightChange",tallWebsocketClosedByError:"tallWebsocketClosedByError",flvDemuxBufferSizeTooLarge:F.flvDemuxBufferSizeTooLarge,wasmDecodeVideoNoResponseError:"wasmDecodeVideoNoResponseError",audioChannelError:"audioChannelError",simdH264DecodeVideoWidthIsTooLarge:"simdH264DecodeVideoWidthIsTooLarge",simdDecodeError:"simdDecodeError",webglContextLostError:"webglContextLostError",videoElementPlayingFailed:"videoElementPlayingFailed",videoElementPlayingFailedForWebrtc:"videoElementPlayingFailedForWebrtc",decoderWorkerInitError:"decoderWorkerInitError",videoInfoError:"videoInfoError",videoCodecIdError:"videoCodecIdError",streamEnd:F.streamEnd,delayTimeout:F.delayTimeout,loadingTimeout:F.loadingTimeout,networkDelayTimeout:F.networkDelayTimeout,aliyunRtcError:"aliyunRtcError",...{talkStreamError:F.talkStreamError,talkStreamClose:F.talkStreamClose}},U="notConnect",q="open",$="close",V="error",J={10:"AAC",7:"ALAW",8:"MULAW",2:"MP3"},Z="The user aborted a request",X="AbortError",K="AbortError",ee="worklet",te="script",se="active",ie={playType:f,timeout:10,loadingTimeout:10,heartTimeout:10,debug:!1,debugLevel:w,protocol:i,demuxType:b,isFlv:!1,isNotMute:!1,videoBuffer:1e3,videoBufferDelay:1e3,videoBufferMax:5e3,loadingTimeoutReplay:!0,heartTimeoutReplay:!0,loadingTimeoutReplayTimes:3,heartTimeoutReplayTimes:3,decoder:"decoder-pro-audio-player.js",isDecoderUseCDN:!1,weiXinInAndroidAudioBufferSize:4800,audioEngine:null,supportLockScreenPlayAudio:!0},Ae="idle",re="buffering",oe="complete";class ae{constructor(e){this.log=function(t){if(e._opt.debug&&e._opt.debugLevel==C){const r=e._opt.debugUuid?`[${e._opt.debugUuid}]`:"";for(var s=arguments.length,i=new Array(s>1?s-1:0),A=1;A<s;A++)i[A-1]=arguments[A];console.log(`JbPro${r}[✅✅✅][${t}]`,...i)}},this.warn=function(t){if(e._opt.debug&&(e._opt.debugLevel==C||e._opt.debugLevel==w)){const r=e._opt.debugUuid?`[${e._opt.debugUuid}]`:"";for(var s=arguments.length,i=new Array(s>1?s-1:0),A=1;A<s;A++)i[A-1]=arguments[A];console.log(`JbPro${r}[❗❗❗][${t}]`,...i)}},this.error=function(t){const s=e._opt.debugUuid?`[${e._opt.debugUuid}]`:"";for(var i=arguments.length,A=new Array(i>1?i-1:0),r=1;r<i;r++)A[r-1]=arguments[r];console.error(`JbPro${s}[❌❌❌][${t}]`,...A)}}}function ne(){}function he(){return(new Date).getTime()}function le(e,t,s){return Math.max(Math.min(e,Math.max(t,s)),Math.min(t,s))}function ue(){return performance&&"function"==typeof performance.now?performance.now():Date.now()}function de(e){let t=0,s=ue();return i=>{if(A=i,"[object Number]"!==Object.prototype.toString.call(A))return;var A;t+=i;const r=ue(),o=r-s;o>=1e3&&(e(t/o*1e3),s=r,t=0)}}(function(e,t){return e(t={exports:{}},t.exports),t.exports})((function(e){!function(){var t="undefined"!=typeof window&&void 0!==window.document?window.document:{},s=e.exports,i=function(){for(var e,s=[["requestFullscreen","exitFullscreen","fullscreenElement","fullscreenEnabled","fullscreenchange","fullscreenerror"],["webkitRequestFullscreen","webkitExitFullscreen","webkitFullscreenElement","webkitFullscreenEnabled","webkitfullscreenchange","webkitfullscreenerror"],["webkitRequestFullScreen","webkitCancelFullScreen","webkitCurrentFullScreenElement","webkitCancelFullScreen","webkitfullscreenchange","webkitfullscreenerror"],["mozRequestFullScreen","mozCancelFullScreen","mozFullScreenElement","mozFullScreenEnabled","mozfullscreenchange","mozfullscreenerror"],["msRequestFullscreen","msExitFullscreen","msFullscreenElement","msFullscreenEnabled","MSFullscreenChange","MSFullscreenError"]],i=0,A=s.length,r={};i<A;i++)if((e=s[i])&&e[1]in t){for(i=0;i<e.length;i++)r[s[0][i]]=e[i];return r}return!1}(),A={change:i.fullscreenchange,error:i.fullscreenerror},r={request:function(e,s){return new Promise(function(A,r){var o=function(){this.off("change",o),A()}.bind(this);this.on("change",o);var a=(e=e||t.documentElement)[i.requestFullscreen](s);a instanceof Promise&&a.then(o).catch(r)}.bind(this))},exit:function(){return new Promise(function(e,s){if(this.isFullscreen){var A=function(){this.off("change",A),e()}.bind(this);this.on("change",A);var r=t[i.exitFullscreen]();r instanceof Promise&&r.then(A).catch(s)}else e()}.bind(this))},toggle:function(e,t){return this.isFullscreen?this.exit():this.request(e,t)},onchange:function(e){this.on("change",e)},onerror:function(e){this.on("error",e)},on:function(e,s){var i=A[e];i&&t.addEventListener(i,s,!1)},off:function(e,s){var i=A[e];i&&t.removeEventListener(i,s,!1)},raw:i};i?(Object.defineProperties(r,{isFullscreen:{get:function(){return Boolean(t[i.fullscreenElement])}},element:{enumerable:!0,get:function(){return t[i.fullscreenElement]}},isEnabled:{enumerable:!0,get:function(){return Boolean(t[i.fullscreenEnabled])}}}),s?e.exports=r:window.screenfull=r):s?e.exports={isEnabled:!1}:window.screenfull={isEnabled:!1}}()})).isEnabled,(()=>{try{if("object"==typeof WebAssembly&&"function"==typeof WebAssembly.instantiate){const e=new WebAssembly.Module(Uint8Array.of(0,97,115,109,1,0,0,0));if(e instanceof WebAssembly.Module)return new WebAssembly.Instance(e)instanceof WebAssembly.Instance}}catch(e){}})();function ce(){const e=window.navigator.userAgent.toLowerCase();return e&&/iphone|ipad|ipod|ios/.test(e)}function pe(e){return null==e}function ge(e){return!pe(e)}const me=()=>{const e=window.navigator.userAgent;return/MicroMessenger/i.test(e)},fe=()=>{const e=window.navigator.userAgent;return/Chrome/i.test(e)},ye=()=>me()&&function(){const e=window.navigator.userAgent.toLowerCase();return/android/i.test(e)}();function be(e){let t=Se(e.hasAudio)&&(e.useMSE||e.useWCS&&!e.useOffscreen)&&Se(e.demuxUseWorker);return!!(Se(t)&&e.useMSE&&e.mseDecodeAudio&&Se(e.demuxUseWorker))||t}function Be(){return"https:"===window.location.protocol||"localhost"===window.location.hostname}function Ce(e){const t=Object.prototype.toString;return function(e){switch(t.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":return!0;default:try{return e instanceof Error}catch(e){return!1}}}(e)?e.message:null==e?"":"object"==typeof e?JSON.stringify(e,null,2):String(e)}function we(){return function(e){let t="";if("object"==typeof e)try{t=JSON.stringify(e),t=JSON.parse(t)}catch(s){t=e}else t=e;return t}(ie)}function Ee(e){return!0===e||"true"===e}function Se(e){return!0!==e&&"true"!==e}class ke{constructor(e){this.destroys=[],this.proxy=this.proxy.bind(this),this.master=e}proxy(e,t,s){let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};if(!e)return;if(Array.isArray(t))return t.map((t=>this.proxy(e,t,s,i)));e.addEventListener(t,s,i);const A=()=>{"function"==typeof e.removeEventListener&&e.removeEventListener(t,s,i)};return this.destroys.push(A),A}destroy(){this.master.debug&&this.master.debug.log("Events","destroy"),this.destroys.forEach((e=>e())),this.destroys=[]}}var Te=e=>{e.on(F.decoderWorkerInit,(()=>{e.debug.log("audioPlayer","listen decoderWorkerInit and set loaded true"),e.loaded=!0})),e.on(F.play,(()=>{e.loading=!1})),e._opt.debug&&(Object.keys(F).forEach((t=>{e.on(F[t],(s=>{e.debug.log("audioPlayer events",F[t],s)}))})),Object.keys(z).forEach((t=>{e.on(z[t],(s=>{e.debug.log("audioPlayer event error",z[t],s)}))})))};class Ie extends t{constructor(e){super(),this.player=e,this.playing=!1,this._requestAbort=!1,this._status=Ae,this.writableStream=null,this.abortController=new AbortController,this.streamRate=de((t=>{e.emit(F.kBps,(t/1024).toFixed(2))})),this.streamRateInterval=null,e.debug.log("FetchStream","init")}destroy(){this.abort(),this.writableStream&&Se(this.writableStream.locked)&&this.writableStream.close().catch((e=>{this.player.debug.log("FetchStream","destroy and writableStream.close()",e)})),this.writableStream=null,this.off(),this._status=Ae,this.streamRate=null,this.stopStreamRateInterval(),this.player.debug.log("FetchStream","destroy")}startStreamRateInterval(){this.stopStreamRateInterval(),this.streamRateInterval=setInterval((()=>{this.streamRate&&this.streamRate(0)}),1e3)}stopStreamRateInterval(){this.streamRateInterval&&(clearInterval(this.streamRateInterval),this.streamRateInterval=null)}fetchStream(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const{demux:s}=this.player;this.player._times.streamStart=he();const i=Object.assign({signal:this.abortController.signal},{headers:t.headers||{}});fetch(e,i).then((e=>{if(this._requestAbort)return this._status=Ae,void e.body.cancel();if(!function(e){return e.ok&&e.status>=200&&e.status<=299}(e))return this.player.debug.error("FetchStream",`fetch response status is ${e.status} and ok is ${e.ok} and emit error and next abort()`),this.abort(),void this.emit(z.fetchError,`fetch response status is ${e.status} and ok is ${e.ok}`);if(this.emit(F.streamSuccess),this.startStreamRateInterval(),"undefined"!=typeof WritableStream)this.player.debug.log("FetchStream","use WritableStream() to read stream"),this.writableStream=new WritableStream({write:e=>this.abortController&&this.abortController.signal&&this.abortController.signal.aborted?(this.player.debug.log("FetchStream","writableStream.write() and this.abortController.signal.aborted so return"),void(this._status=oe)):Ee(this._requestAbort)?(this.player.debug.log("FetchStream","writableStream.write() and this._requestAbort is true so return"),void(this._status=oe)):(this._status=re,this.streamRate&&this.streamRate(e.byteLength),s.dispatch(e)),close:()=>{this._status=oe,s.close(),this.emit(F.streamEnd,"fetch done")},abort:e=>{if(this.abortController&&this.abortController.signal&&this.abortController.signal.aborted)return this.player.debug.log("FetchStream","writableStream.abort() and this.abortController.signal.aborted so return"),void(this._status=oe);s.close();const t=e.toString();-1===t.indexOf(Z)&&-1===t.indexOf(X)&&e.name!==K&&(this.abort(),this.emit(z.fetchError,e))}}),e.body.pipeTo(this.writableStream);else{this.player.debug.log("FetchStream","not support WritableStream and use getReader() to read stream");const t=e.body.getReader(),i=()=>{t.read().then((e=>{let{done:t,value:A}=e;return t?(this._status=oe,s.close(),void this.emit(F.streamEnd,"fetch done")):this.abortController&&this.abortController.signal&&this.abortController.signal.aborted?(this.player.debug.log("FetchStream","reader.read() and this.abortController.signal.aborted so return"),void(this._status=oe)):Ee(this._requestAbort)?(this.player.debug.log("FetchStream","reader.read() and this._requestAbort is true so return"),void(this._status=oe)):(this._status=re,this.streamRate&&this.streamRate(A.byteLength),s.dispatch(A),void i())})).catch((e=>{if(this.abortController&&this.abortController.signal&&this.abortController.signal.aborted)return this.player.debug.log("FetchStream","reader.read().catch() and this.abortController.signal.aborted so return"),void(this._status=oe);s.close();const t=e.toString();-1===t.indexOf(Z)&&-1===t.indexOf(X)&&e.name!==K&&(this.abort(),this.emit(z.fetchError,e))}))};i()}})).catch((e=>{this.abortController&&this.abortController.signal&&this.abortController.signal.aborted||"AbortError"!==e.name&&(s.close(),this.abort(),this.emit(z.fetchError,e))}))}abort(){this._requestAbort=!0;const e=fe();if(this._status!==re||Se(e)){if(this.abortController){try{this.abortController.abort()}catch(e){}this.abortController=null}}else this.abortController=null,this.player.debug.log("FetchStream",`abort() and not abortController.abort() _status is ${this._status} and _isChrome is ${e}`)}getStreamType(){return h}}class _e extends t{constructor(e){super(),this.TAG_NAME="FetchWorkerLoader",this.player=e,this.playing=!1,this.fetchWorker=null,this.workerClearTimeout=null,this.workerUrl=null,this.destroyResolve=null,this.decoderWorkerCloseTimeout=null,this.abortController=new AbortController,this.streamRate=de((t=>{e.emit(F.kBps,(t/1024).toFixed(2))})),this.streamRateInterval=null,this._initFetchWorker(),e.debug.log(this.TAG_NAME,"init")}destroy(){return new Promise(((e,t)=>{this.fetchWorker?(this.player.debug.log(this.TAG_NAME,"send destroy"),this.fetchWorker.postMessage({cmd:H}),this.destroyResolve=e,this.decoderWorkerCloseTimeout=setTimeout((()=>{this.player.debug.warn(this.TAG_NAME,"send close but not response and destroy directly"),this.decoderWorkerCloseTimeout&&(clearTimeout(this.decoderWorkerCloseTimeout),this.decoderWorkerCloseTimeout=null),this._destroy(),setTimeout((()=>{e()}),0)}),2e3)):(this._destroy(),setTimeout((()=>{e()}),0))}))}_destroy(){this.off(),this.decoderWorkerCloseTimeout&&(clearTimeout(this.decoderWorkerCloseTimeout),this.decoderWorkerCloseTimeout=null),this.workerUrl&&(window.URL.revokeObjectURL(this.workerUrl),this.workerUrl=null),this.workerClearTimeout&&(clearTimeout(this.workerClearTimeout),this.workerClearTimeout=null),this._stopStreamRateInterval(),this.streamRate=null,this.fetchWorker&&(this.fetchWorker.terminate(),this.fetchWorker.onmessage=null,this.fetchWorker=null),this.destroyResolve&&(this.destroyResolve(),this.destroyResolve=null),this.player.debug.log(this.TAG_NAME,"destroy")}_initFetchWorker(){const e=(t=function(){function e(e){return!0===e||"true"===e}function t(e){return!1===e||"false"===e}const s="The user aborted a request",i="AbortError",A="AbortError",r="fetch",o="destroy",a="destroyEnd",n="buffer",h="fetchError",l="fetchClose",u="fetchSuccess",d="idle",c="buffering",p="complete";let g=new class{constructor(){this._requestAbort=!1,this._status=d,this.writableStream=null,this.isChrome=!1,this.abortController=new AbortController}destroy(){this.abort(),this.writableStream&&t(this.writableStream.locked)&&this.writableStream.close().catch((e=>{})),this.writableStream=null,this._status=d}fetchStream(t){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const o=Object.assign({signal:this.abortController.signal},{headers:r.headers||{}});fetch(t,o).then((t=>{if(this._requestAbort)return this._status=d,void t.body.cancel();if(!function(e){return e.ok&&e.status>=200&&e.status<=299}(t))return this.abort(),void postMessage({cmd:h,message:`fetch response status is ${t.status} and ok is ${t.ok}`});if(postMessage({cmd:u}),"undefined"!=typeof WritableStream)this.writableStream=new WritableStream({write:t=>{this.abortController&&this.abortController.signal&&this.abortController.signal.aborted||e(this._requestAbort)?this._status=p:(this._status=c,postMessage({cmd:n,buffer:t},[t.buffer]))},close:()=>{this._status=p,postMessage({cmd:l})},abort:e=>{if(this.abortController&&this.abortController.signal&&this.abortController.signal.aborted)return void(this._status=p);const t=e.toString();-1===t.indexOf(s)&&-1===t.indexOf(i)&&e.name!==A&&(this.abort(),postMessage({cmd:h,message:e.toString()}))}}),t.body.pipeTo(this.writableStream);else{const r=t.body.getReader(),o=()=>{r.read().then((t=>{let{done:s,value:i}=t;if(s)return this._status=p,void postMessage({cmd:l});this.abortController&&this.abortController.signal&&this.abortController.signal.aborted||e(this._requestAbort)?this._status=p:(this._status=c,postMessage({cmd:n,buffer:i},[i.buffer]),o())})).catch((e=>{if(this.abortController&&this.abortController.signal&&this.abortController.signal.aborted)return void(this._status=p);const t=e.toString();-1===t.indexOf(s)&&-1===t.indexOf(i)&&e.name!==A&&(this.abort(),postMessage({cmd:h,message:e.toString()}))}))};o()}})).catch((e=>{this.abortController&&this.abortController.signal&&this.abortController.signal.aborted||"AbortError"!==e.name&&(this.abort(),postMessage({cmd:h,message:e.toString()}))}))}abort(){if(this._requestAbort=!0,this._status!==c||t(g.isChrome)){if(this.abortController){try{this.abortController.abort()}catch(e){}this.abortController=null}}else this.abortController=null}};self.onmessage=t=>{const s=t.data;switch(s.cmd){case r:g.isChrome=e(s.isChrome),g.fetchStream(s.url,JSON.parse(s.options));break;case o:g.destroy(),g=null,postMessage({cmd:a})}}}.toString(),t.trim().match(/^function\s*\w*\s*\([\w\s,]*\)\s*{([\w\W]*?)}$/)[1]);var t;const s=new Blob([e],{type:"text/javascript"});let i=URL.createObjectURL(s);const A=new Worker(i);this.workerUrl=i,this.workerClearTimeout=setTimeout((()=>{window.URL.revokeObjectURL(this.workerUrl),this.workerUrl=null,this.workerClearTimeout=null}),E),A.onmessage=e=>{const{demux:t}=this.player,s=e.data;switch(s.cmd){case G:this.streamRate&&this.streamRate(s.buffer.byteLength),t.dispatch(s.buffer);break;case x:this.emit(F.streamSuccess),this._startStreamRateInterval();break;case O:t.close(),this.emit(F.streamEnd,"fetch done");break;case j:t.close(),this.emit(z.fetchError,s.message);break;case W:this._destroy()}},this.fetchWorker=A}_startStreamRateInterval(){this._stopStreamRateInterval(),this.streamRateInterval=setInterval((()=>{this.streamRate&&this.streamRate(0)}),1e3)}_stopStreamRateInterval(){this.streamRateInterval&&(clearInterval(this.streamRateInterval),this.streamRateInterval=null)}fetchStream(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.player._times.streamStart=he(),this.fetchWorker.postMessage({cmd:Q,url:e,isChrome:fe(),options:JSON.stringify(t)})}getStreamType(){return h}}class ve extends t{constructor(e){super(),this.player=e,this.socket=null,this.socketStatus=U,this.wsUrl=null,this.requestAbort=!1,this.socketDestroyFnList=[],this.streamRate=de((t=>{e.emit(F.kBps,(t/1024).toFixed(2))})),this.streamRateInterval=null,e.debug.log("WebsocketStream","init")}destroy(){this._closeWebSocket(),this.stopStreamRateInterval(),this.wsUrl=null,this.off(),this.player.debug.log("WebsocketStream","destroy")}startStreamRateInterval(){this.stopStreamRateInterval(),this.streamRateInterval=setInterval((()=>{this.streamRate&&this.streamRate(0)}),1e3)}stopStreamRateInterval(){this.streamRateInterval&&(clearInterval(this.streamRateInterval),this.streamRateInterval=null)}_createWebSocket(){const e=this.player,{debug:t,events:{proxy:s},demux:i}=e;this.socket=new WebSocket(this.wsUrl),this.socket.binaryType="arraybuffer";const A=s(this.socket,"open",(()=>{t.log("WebsocketStream","socket open"),this.socketStatus=q,this.emit(F.streamSuccess),this.player.emit(F.websocketOpen),this.startStreamRateInterval()})),r=s(this.socket,"message",(e=>{this.streamRate&&this.streamRate(e.data.byteLength),this._handleMessage(e.data)})),o=s(this.socket,"close",(e=>{if(t.log("WebsocketStream",`socket close and code is ${e.code}`),1006===e.code&&t.error("WebsocketStream",`socket close abnormally and code is ${e.code}`),Ee(this.requestAbort))return this.requestAbort=!1,void t.log("WebsocketStream","socket close and requestAbort is true");i.close(),this.socketStatus=$,this.player.emit(F.websocketClose,e.code),this.emit(F.streamEnd,e.code)})),a=s(this.socket,"error",(e=>{t.error("WebsocketStream","socket error",e),this.socketStatus=V,this.emit(z.websocketError,e),i.close(),t.log("WebsocketStream","socket error:",e.isTrusted?"websocket user aborted":"websocket error")}));this.socketDestroyFnList.push(A,r,o,a)}_closeWebSocket(){this.socketDestroyFnList.forEach((e=>e())),!this.socket||0!==this.socket.readyState&&1!==this.socket.readyState?this.socket&&this.player.debug.log("WebsocketStream",`_closeWebSocket() socket is null or socket status is ${this.socket&&this.socket.readyState}`):(this.requestAbort=!0,this.socket.close(1e3,"Client disconnecting")),this.socket=null,this.socketStatus=U,this.streamRate=null}_handleMessage(e){const{demux:t}=this.player;t?t.dispatch(e):this.player.debug.warn("WebsocketStream","websocket handle message demux is null")}fetchStream(e,t){this.player._times.streamStart=he(),this.wsUrl=e,this._createWebSocket()}sendMessage(e){this.socket?this.socketStatus===q?this.socket.send(e):this.player.debug.error("WebsocketStream",`websocket send message error and socket status is ${this.socketStatus}`):this.player.debug.error("WebsocketStream","websocket send message socket is null")}resetFetchStream(){this._closeWebSocket(),this._createWebSocket()}getStreamType(){return u}}class Re extends t{constructor(e){super(),this.player=e,e.debug.log("HlsStream","init")}destroy(){this.off(),this.player.debug.log("HlsStream","destroy")}fetchStream(e){const{hlsDecoder:t,debug:s}=this.player;this.player._times.streamStart=he(),t.loadSource(e).then((()=>{this.player.debug.log("HlsStream","loadSource success"),this.emit(F.streamSuccess)})).catch((e=>{this.emit(z.hlsError,e)}))}getStreamType(){return l}}class Pe extends t{constructor(e){super(),this.player=e,this.webrctUrl=null,e.debug.log("WebrtcStream","init")}destroy(){this.webrctUrl=null,this.off(),this.player.debug.log("WebrtcStream","destroy")}fetchStream(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const{webrtc:s,debug:i}=this.player;if(this.player._times.streamStart=he(),this.webrctUrl=e.replace("webrtc:",window.location.protocol),-1===this.webrctUrl.indexOf("/webrtc/play")&&this.player.isWebrtcForM7S()){const t=new URL(this.webrctUrl),s="/webrtc/play"+t.pathname;this.webrctUrl=t.origin+s+t.search,this.player.debug.log("WebrtcStream",`original url is ${e}, and new url is: ${this.webrctUrl}`)}s.loadSource(this.webrctUrl,t).then((()=>{this.player.debug.log("WebrtcStream","loadSource success"),this.emit(F.streamSuccess)})).catch((e=>{this.player.debug.error("WebrtcStream","loadSource error",e),this.emit(z.webrtcError,e)}))}getStreamType(){return d}}class De extends t{constructor(e){super(),this.player=e,this.transport=null,this.wtUrl=null,this.streamRate=de((t=>{e.emit(F.kBps,(t/1024).toFixed(2))})),this.streamRateInterval=null,e.debug.log("WebTransportLoader","init")}destroy(){this.abort(),this.off(),this.player.debug.log("WebTransportLoader","destroy")}startStreamRateInterval(){this.stopStreamRateInterval(),this.streamRateInterval=setInterval((()=>{this.streamRate&&this.streamRate(0)}),1e3)}stopStreamRateInterval(){this.streamRateInterval&&(clearInterval(this.streamRateInterval),this.streamRateInterval=null)}_createWebTransport(){const e=this.player,{debug:t,events:{proxy:s},demux:i}=e;try{this.transport=new WebTransport(this.wtUrl),this.transport.ready.then((()=>{this.emit(F.streamSuccess),this.startStreamRateInterval(),this.transport.createBidirectionalStream().then((e=>{e.readable.pipeTo(new WritableStream(i.input))}))})).catch((e=>{this.player.debug.warn("WebTransportLoader","_createWebTransport-ready",e)}))}catch(e){this.player.debug.warn("WebTransportLoader","_createWebTransport",e)}}fetchStream(e){this.player._times.streamStart=he(),this.wtUrl=e.replace(/^wt:/,"https:"),this._createWebTransport()}abort(){if(this.transport)try{this.transport.close(),this.transport=null}catch(e){this.transport=null}}getStreamType(){return c}}class Me extends t{constructor(e){super(),this.player=e,this.workUrl=null,e.debug.log("WorkerStream","init")}destroy(){this.workUrl=null,this.off(),this.player.debug.log("WorkerStream","destroy")}sendMessage(e){this.player.decoderWorker.workerSendMessage(e)}fetchStream(e){this.workUrl=e,this.player._times.streamStart=he(),this.player.decoderWorker.workerFetchStream(e)}getStreamType(){const e=this.player._opt.protocol;return p+" "+(e===i?h:u)}}class Ne extends t{constructor(e){super(),this.TAG_NAME="AliyunRtcLoader",this.player=e,e.debug.log(this.TAG_NAME,"init")}destroy(){this.off(),this.player.debug.log(this.TAG_NAME,"destroy")}fetchStream(e){const{aliyunRtcDecoder:t}=this.player;this.player._times.streamStart=he(),t.loadSource(e).then((()=>{this.player.debug.log(this.TAG_NAME,"loadSource success"),this.emit(F.streamSuccess)})).catch((e=>{this.player.debug.error(this.TAG_NAME,"loadSource error",e),this.emit(z.aliyunRtcError,e)}))}getStreamType(){return g}}class Le{constructor(e){return new(Le.getLoaderFactory(e._opt))(e)}static getLoaderFactory(e){const{protocol:t,useWasm:n,playType:h,useWCS:l,useMSE:u,demuxUseWorker:d,mainThreadFetchUseWorker:c}=e;return t===i?h===f?Me:h===m?n&&!be(e)||d?Me:c?_e:Ie:l||u?d?Me:c?_e:Ie:Me:t===s?h===f?Me:h===m?n&&!be(e)||d?Me:ve:l||u?d?Me:ve:Me:t===A?Re:t===r?Pe:t===o?De:t===a?Ne:void 0}}class Qe extends t{constructor(e){super(),this.bufferList=[],this.player=e,this.$audio=null,this.scriptNode=null,this.workletProcessorNode=null,this.hasInitScriptNode=!1,this.audioContext=new(window.AudioContext||window.webkitAudioContext)({sampleRate:48e3}),this.gainNode=this.audioContext.createGain();const t=this.audioContext.createBufferSource();t.buffer=this.audioContext.createBuffer(1,1,22050),t.connect(this.audioContext.destination),t.noteOn?t.noteOn(0):t.start(0),this.audioBufferSourceNode=t,this.mediaStreamAudioDestinationNode=this.audioContext.createMediaStreamDestination(),this.gainNode.gain.value=0,this.playing=!1,this.audioInfo={encTypeCode:"",encType:"",channels:"",sampleRate:"",depth:""},this.init=!1,this.hasAudio=!1,this.audioResumeStateTimeout=null}destroy(){this.closeAudio(),this.resetInit(),this.audioContext&&(this.audioContext.close(),this.audioContext=null),this.gainNode=null,this.hasAudio=!1,this.playing=!1,this.scriptNode&&(this.scriptNode.onaudioprocess=ne,this.scriptNode=null),this.workletProcessorNode&&(this.workletProcessorNode.port.onmessage=ne,this.workletProcessorNode=null),this.clearAudioResumeStateTimeout(),this.audioBufferSourceNode=null,this.mediaStreamAudioDestinationNode=null,this.hasInitScriptNode=!1,this.off()}resetInit(){this.audioInfo={encTypeCode:"",encType:"",channels:"",sampleRate:"",depth:""},this.init=!1}getAudioInfo(){return this.audioInfo}updateAudioInfo(e){e.encTypeCode&&(this.audioInfo.encTypeCode=e.encTypeCode,this.audioInfo.encType=J[e.encTypeCode]),e.channels&&(this.audioInfo.channels=e.channels),e.sampleRate&&(this.audioInfo.sampleRate=e.sampleRate),e.depth&&(this.audioInfo.depth=e.depth),this.audioInfo.sampleRate&&this.audioInfo.channels&&this.audioInfo.encType&&!this.init&&(this.player.emit(F.audioInfo,this.audioInfo),this.init=!0)}get isPlaying(){return this.playing}get isMute(){return 0===this.gainNode.gain.value}get volume(){return this.gainNode.gain.value}get bufferSize(){return this.bufferList.length}get audioContextState(){let e=null;return this.audioContext&&(e=this.audioContext.state),e}initScriptNode(){}initMobileScriptNode(){}initWorkletScriptNode(){}getEngineType(){return""}mute(e){e?(this.isMute||this.player.emit(F.mute,e),this.setVolume(0),this.clear()):(this.isMute&&this.player.emit(F.mute,e),this.setVolume(this.player.lastVolume||.5))}setVolume(e){e=parseFloat(e).toFixed(2),isNaN(e)||(this.audioEnabled(!0),e=le(e,0,1),this.gainNode.gain.value=e,this.player.emit(F.volumechange,this.player.volume))}closeAudio(){this.hasInitScriptNode&&(this.scriptNode&&this.scriptNode.disconnect(this.gainNode),this.workletProcessorNode&&this.workletProcessorNode.disconnect(this.gainNode),this.gainNode&&(this.gainNode.disconnect(this.mediaStreamAudioDestinationNode),this.$audio||this.gainNode.disconnect(this.audioContext.destination))),this.clear()}audioEnabled(e){e?this.isStateSuspended()&&(this.audioContext.resume().then((()=>{this.player.emit(F.audioResumeState,{state:this.audioContextState,isRunning:this.isStateRunning()})})),this.audioResumeStateTimeout=setTimeout((()=>{this.clearAudioResumeStateTimeout(),this.isStateSuspended()&&this.player.emit(F.audioResumeState,{state:this.audioContextState,isRunning:this.isStateRunning()})}),1e3)):this.isStateRunning()&&this.audioContext.suspend()}isStateRunning(){return"running"===this.audioContextState}isStateSuspended(){return"suspended"===this.audioContextState}clearAudioResumeStateTimeout(){this.audioResumeStateTimeout&&(clearTimeout(this.audioResumeStateTimeout),this.audioResumeStateTimeout=null)}clear(){this.bufferList=[]}play(e,t){}pause(){this.playing=!1}resume(){this.playing=!0}setRate(e){}getAudioBufferSize(){return 0}}class He{constructor(e,t,s,i){this.player=e,this.audio=t,this.channel=s,this.bufferSize=i}extract(e,t){let s=this.provide(t);for(let t=0;t<s.size;t++)e[2*t]=s.left[t],e[2*t+1]=s.right[t];return this.audio.tempAudioTimestamp=s.ts,s.size}provide(e){let t=new Float32Array(e),s=new Float32Array(e),i=0,A=0,r=0,o=e/this.bufferSize;const a=this.audio.bufferList;if(o&&a.length>=o){try{for(let e=0;e<o;e++){const e=a.shift();2===this.channel?(t.set(e.buffer[0],r),s.set(e.buffer[1],r)):(t.set(e.buffer[0],r),s.set(e.buffer[0],r)),r+=this.bufferSize,A=e.ts}}catch(e){this.player.debug.warn("Processor","provide()",e),t=new Float32Array(0),s=new Float32Array(0)}i=t.length}return{size:i,ts:A,left:t,right:s}}destroy(){this.buffer=null,this.channel=null}}class We{constructor(){this._vector=new Float32Array,this._position=0,this._frameCount=0}get vector(){return this._vector}get position(){return this._position}get startIndex(){return 2*this._position}get frameCount(){return this._frameCount}get endIndex(){return 2*(this._position+this._frameCount)}clear(){this.receive(this._frameCount),this.rewind()}put(e){this._frameCount+=e}putSamples(e,t){let s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;const i=2*(t=t||0);s>=0||(s=(e.length-i)/2);const A=2*s;this.ensureCapacity(s+this._frameCount);const r=this.endIndex;this.vector.set(e.subarray(i,i+A),r),this._frameCount+=s}putBuffer(e,t){let s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;t=t||0,s>=0||(s=e.frameCount-t),this.putSamples(e.vector,e.position+t,s)}receive(e){e>=0&&!(e>this._frameCount)||(e=this.frameCount),this._frameCount-=e,this._position+=e}receiveSamples(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;const s=2*t,i=this.startIndex;e.set(this._vector.subarray(i,i+s)),this.receive(t)}extract(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;const i=this.startIndex+2*t,A=2*s;e.set(this._vector.subarray(i,i+A))}ensureCapacity(){const e=parseInt(2*(arguments.length>0&&void 0!==arguments[0]?arguments[0]:0));if(this._vector.length<e){const t=new Float32Array(e);t.set(this._vector.subarray(this.startIndex,this.endIndex)),this._vector=t,this._position=0}else this.rewind()}ensureAdditionalCapacity(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.ensureCapacity(this._frameCount+e)}rewind(){this._position>0&&(this._vector.set(this._vector.subarray(this.startIndex,this.endIndex)),this._position=0)}}class Ge{constructor(e){e?(this._inputBuffer=new We,this._outputBuffer=new We):this._inputBuffer=this._outputBuffer=null}get inputBuffer(){return this._inputBuffer}set inputBuffer(e){this._inputBuffer=e}get outputBuffer(){return this._outputBuffer}set outputBuffer(e){this._outputBuffer=e}clear(){this._inputBuffer.clear(),this._outputBuffer.clear()}}class je extends Ge{constructor(e){super(e),this.reset(),this._rate=1}set rate(e){this._rate=e}reset(){this.slopeCount=0,this.prevSampleL=0,this.prevSampleR=0}clone(){const e=new je;return e.rate=this._rate,e}process(){const e=this._inputBuffer.frameCount;this._outputBuffer.ensureAdditionalCapacity(e/this._rate+1);const t=this.transpose(e);this._inputBuffer.receive(),this._outputBuffer.put(t)}transpose(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;if(0===e)return 0;const t=this._inputBuffer.vector,s=this._inputBuffer.startIndex,i=this._outputBuffer.vector,A=this._outputBuffer.endIndex;let r=0,o=0;for(;this.slopeCount<1;)i[A+2*o]=(1-this.slopeCount)*this.prevSampleL+this.slopeCount*t[s],i[A+2*o+1]=(1-this.slopeCount)*this.prevSampleR+this.slopeCount*t[s+1],o+=1,this.slopeCount+=this._rate;if(this.slopeCount-=1,1!==e)e:for(;;){for(;this.slopeCount>1;)if(this.slopeCount-=1,r+=1,r>=e-1)break e;const a=s+2*r;i[A+2*o]=(1-this.slopeCount)*t[a]+this.slopeCount*t[a+2],i[A+2*o+1]=(1-this.slopeCount)*t[a+1]+this.slopeCount*t[a+3],o+=1,this.slopeCount+=this._rate}return this.prevSampleL=t[s+2*e-2],this.prevSampleR=t[s+2*e-1],o}}const Oe=function(){};class xe extends class{constructor(e){this._pipe=e}get pipe(){return this._pipe}get inputBuffer(){return this._pipe.inputBuffer}get outputBuffer(){return this._pipe.outputBuffer}fillInputBuffer(){throw new Error("fillInputBuffer() not overridden")}fillOutputBuffer(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;for(;this.outputBuffer.frameCount<e;){const e=16384-this.inputBuffer.frameCount;if(this.fillInputBuffer(e),this.inputBuffer.frameCount<16384)break;this._pipe.process()}}clear(){this._pipe.clear()}}{constructor(e,t){let s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Oe;super(t),this.callback=s,this.sourceSound=e,this.historyBufferSize=22050,this._sourcePosition=0,this.outputBufferPosition=0,this._position=0}get position(){return this._position}set position(e){if(e>this._position)throw new RangeError("New position may not be greater than current position");const t=this.outputBufferPosition-(this._position-e);if(t<0)throw new RangeError("New position falls outside of history buffer");this.outputBufferPosition=t,this._position=e}get sourcePosition(){return this._sourcePosition}set sourcePosition(e){this.clear(),this._sourcePosition=e}onEnd(){this.callback()}fillInputBuffer(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;const t=new Float32Array(2*e),s=this.sourceSound.extract(t,e,this._sourcePosition);this._sourcePosition+=s,this.inputBuffer.putSamples(t,0,s)}extract(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;this.fillOutputBuffer(this.outputBufferPosition+t);const s=Math.min(t,this.outputBuffer.frameCount-this.outputBufferPosition);this.outputBuffer.extract(e,this.outputBufferPosition,s);const i=this.outputBufferPosition+s;return this.outputBufferPosition=Math.min(this.historyBufferSize,i),this.outputBuffer.receive(Math.max(i-this.historyBufferSize,0)),this._position+=s,s}handleSampleData(e){this.extract(e.data,4096)}clear(){super.clear(),this.outputBufferPosition=0}}const Fe=[[124,186,248,310,372,434,496,558,620,682,744,806,868,930,992,1054,1116,1178,1240,1302,1364,1426,1488,0],[-100,-75,-50,-25,25,50,75,100,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[-20,-15,-10,-5,5,10,15,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[-4,-3,-2,-1,1,2,3,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]],Ye=-10/1.5;class ze extends Ge{constructor(e){super(e),this._quickSeek=!0,this.midBufferDirty=!1,this.midBuffer=null,this.overlapLength=0,this.autoSeqSetting=!0,this.autoSeekSetting=!0,this._tempo=1,this.setParameters(44100,0,0,8)}clear(){super.clear(),this.clearMidBuffer()}clearMidBuffer(){this.midBufferDirty&&(this.midBufferDirty=!1,this.midBuffer=null)}setParameters(e,t,s,i){e>0&&(this.sampleRate=e),i>0&&(this.overlapMs=i),t>0?(this.sequenceMs=t,this.autoSeqSetting=!1):this.autoSeqSetting=!0,s>0?(this.seekWindowMs=s,this.autoSeekSetting=!1):this.autoSeekSetting=!0,this.calculateSequenceParameters(),this.calculateOverlapLength(this.overlapMs),this.tempo=this._tempo}set tempo(e){let t;this._tempo=e,this.calculateSequenceParameters(),this.nominalSkip=this._tempo*(this.seekWindowLength-this.overlapLength),this.skipFract=0,t=Math.floor(this.nominalSkip+.5),this.sampleReq=Math.max(t+this.overlapLength,this.seekWindowLength)+this.seekLength}get tempo(){return this._tempo}get inputChunkSize(){return this.sampleReq}get outputChunkSize(){return this.overlapLength+Math.max(0,this.seekWindowLength-2*this.overlapLength)}calculateOverlapLength(){let e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;e=this.sampleRate*t/1e3,e=e<16?16:e,e-=e%8,this.overlapLength=e,this.refMidBuffer=new Float32Array(2*this.overlapLength),this.midBuffer=new Float32Array(2*this.overlapLength)}checkLimits(e,t,s){return e<t?t:e>s?s:e}calculateSequenceParameters(){let e,t;this.autoSeqSetting&&(e=150+-50*this._tempo,e=this.checkLimits(e,50,125),this.sequenceMs=Math.floor(e+.5)),this.autoSeekSetting&&(t=28.333333333333332+Ye*this._tempo,t=this.checkLimits(t,15,25),this.seekWindowMs=Math.floor(t+.5)),this.seekWindowLength=Math.floor(this.sampleRate*this.sequenceMs/1e3),this.seekLength=Math.floor(this.sampleRate*this.seekWindowMs/1e3)}set quickSeek(e){this._quickSeek=e}clone(){const e=new ze;return e.tempo=this._tempo,e.setParameters(this.sampleRate,this.sequenceMs,this.seekWindowMs,this.overlapMs),e}seekBestOverlapPosition(){return this._quickSeek?this.seekBestOverlapPositionStereoQuick():this.seekBestOverlapPositionStereo()}seekBestOverlapPositionStereo(){let e,t,s,i=0;for(this.preCalculateCorrelationReferenceStereo(),e=0,t=Number.MIN_VALUE;i<this.seekLength;i+=1)s=this.calculateCrossCorrelationStereo(2*i,this.refMidBuffer),s>t&&(t=s,e=i);return e}seekBestOverlapPositionStereoQuick(){let e,t,s,i,A,r=0;for(this.preCalculateCorrelationReferenceStereo(),t=Number.MIN_VALUE,e=0,i=0,A=0;r<4;r+=1){let o=0;for(;Fe[r][o]&&(A=i+Fe[r][o],!(A>=this.seekLength));)s=this.calculateCrossCorrelationStereo(2*A,this.refMidBuffer),s>t&&(t=s,e=A),o+=1;i=e}return e}preCalculateCorrelationReferenceStereo(){let e,t,s=0;for(;s<this.overlapLength;s+=1)t=s*(this.overlapLength-s),e=2*s,this.refMidBuffer[e]=this.midBuffer[e]*t,this.refMidBuffer[e+1]=this.midBuffer[e+1]*t}calculateCrossCorrelationStereo(e,t){const s=this._inputBuffer.vector;e+=this._inputBuffer.startIndex;let i=0,A=2;const r=2*this.overlapLength;let o;for(;A<r;A+=2)o=A+e,i+=s[o]*t[A]+s[o+1]*t[A+1];return i}overlap(e){this.overlapStereo(2*e)}overlapStereo(e){const t=this._inputBuffer.vector;e+=this._inputBuffer.startIndex;const s=this._outputBuffer.vector,i=this._outputBuffer.endIndex;let A,r,o=0;const a=1/this.overlapLength;let n,h,l;for(;o<this.overlapLength;o+=1)r=(this.overlapLength-o)*a,n=o*a,A=2*o,h=A+e,l=A+i,s[l+0]=t[h+0]*n+this.midBuffer[A+0]*r,s[l+1]=t[h+1]*n+this.midBuffer[A+1]*r}process(){let e,t,s;if(null===this.midBuffer){if(this._inputBuffer.frameCount<this.overlapLength)return;this.midBuffer=new Float32Array(2*this.overlapLength),this._inputBuffer.receiveSamples(this.midBuffer,this.overlapLength)}for(;this._inputBuffer.frameCount>=this.sampleReq;){e=this.seekBestOverlapPosition(),this._outputBuffer.ensureAdditionalCapacity(this.overlapLength),this.overlap(Math.floor(e)),this._outputBuffer.put(this.overlapLength),t=this.seekWindowLength-2*this.overlapLength,t>0&&this._outputBuffer.putBuffer(this._inputBuffer,e+this.overlapLength,t);const i=this._inputBuffer.startIndex+2*(e+this.seekWindowLength-this.overlapLength);this.midBuffer.set(this._inputBuffer.vector.subarray(i,i+2*this.overlapLength)),this.skipFract+=this.nominalSkip,s=Math.floor(this.skipFract),this.skipFract-=s,this._inputBuffer.receive(s)}}}const Ue=function(e,t){return(e>t?e-t:t-e)>1e-10};class qe{constructor(){this.transposer=new je(!1),this.stretch=new ze(!1),this._inputBuffer=new We,this._intermediateBuffer=new We,this._outputBuffer=new We,this._rate=0,this._tempo=0,this.virtualPitch=1,this.virtualRate=1,this.virtualTempo=1,this.calculateEffectiveRateAndTempo()}clear(){this.transposer.clear(),this.stretch.clear()}clone(){const e=new qe;return e.rate=this.rate,e.tempo=this.tempo,e}get rate(){return this._rate}set rate(e){this.virtualRate=e,this.calculateEffectiveRateAndTempo()}set rateChange(e){this._rate=1+.01*e}get tempo(){return this._tempo}set tempo(e){this.virtualTempo=e,this.calculateEffectiveRateAndTempo()}set tempoChange(e){this.tempo=1+.01*e}set pitch(e){this.virtualPitch=e,this.calculateEffectiveRateAndTempo()}set pitchOctaves(e){this.pitch=Math.exp(.69314718056*e),this.calculateEffectiveRateAndTempo()}set pitchSemitones(e){this.pitchOctaves=e/12}get inputBuffer(){return this._inputBuffer}get outputBuffer(){return this._outputBuffer}calculateEffectiveRateAndTempo(){const e=this._tempo,t=this._rate;this._tempo=this.virtualTempo/this.virtualPitch,this._rate=this.virtualRate*this.virtualPitch,Ue(this._tempo,e)&&(this.stretch.tempo=this._tempo),Ue(this._rate,t)&&(this.transposer.rate=this._rate),this._rate>1?this._outputBuffer!=this.transposer.outputBuffer&&(this.stretch.inputBuffer=this._inputBuffer,this.stretch.outputBuffer=this._intermediateBuffer,this.transposer.inputBuffer=this._intermediateBuffer,this.transposer.outputBuffer=this._outputBuffer):this._outputBuffer!=this.stretch.outputBuffer&&(this.transposer.inputBuffer=this._inputBuffer,this.transposer.outputBuffer=this._intermediateBuffer,this.stretch.inputBuffer=this._intermediateBuffer,this.stretch.outputBuffer=this._outputBuffer)}process(){this._rate>1?(this.stretch.process(),this.transposer.process()):(this.transposer.process(),this.stretch.process())}}class $e{constructor(e,t,s){this.player=e,this.audio=t,this.soundTouch=new qe,this.soundTouch.tempo=1,this.soundTouch.rate=1,this.filter=new xe(s,this.soundTouch)}setRate(e){e!==this.soundTouch.rate&&(this.soundTouch.tempo=e)}provide(e){let t=new Float32Array(2*e),s=this.filter.extract(t,e),i=new Float32Array(s),A=new Float32Array(s);for(let e=0;e<s;e++)i[e]=t[2*e],A[e]=t[2*e+1];return{size:s,left:i,right:A,ts:this.audio.tempAudioTimestamp||0}}destroy(){this.soundTouch&&(this.soundTouch.clear(),this.soundTouch=null),this.filter&&(this.filter=null)}}class Ve extends Qe{constructor(e){super(e),this.defaultPlaybackRate=1,this.playbackRate=1,this.rateProcessor=null,this.processor=null,this.scriptNodeInterval=null,this.engineType=this.getAutoAudioEngineType(),this.audioBufferSize=this.getAudioBufferSizeByType(),this.$audio=null,this._delayPlay=!1,this.eventListenList=[],this.workletUrl=null,this.clearWorkletUrlTimeout=null,this.player._opt.supportLockScreenPlayAudio&&ce()&&(this.$audio=document.createElement("audio"),Object.assign(this.$audio.style,{position:"absolute",left:"-100%",top:"-100%"}),e.$container?e.$container.appendChild(this.$audio):document.body.appendChild(this.$audio),this._bindAudioProxy(),this.player.debug.log("AudioContext","create audio element")),this.scriptStartTime=0,this.player.debug.log("AudioContext","init",`engineType: ${this.engineType}, audioBufferSize: ${this.audioBufferSize}`)}destroy(){super.destroy(),this.workletUrl&&(URL.revokeObjectURL(this.workletUrl),this.workletUrl=null),this.clearWorkletUrlTimeout&&(clearTimeout(this.clearWorkletUrlTimeout),this.clearWorkletUrlTimeout=null),this.eventListenList&&(this.eventListenList.forEach((e=>{e()})),this.eventListenList=[]),this.$audio&&(this.$audio.pause(),this.$audio.srcObject=null,this.$audio.parentNode&&this.$audio.parentNode.removeChild(this.$audio),this.$audio=null),this.processor&&(this.processor.destroy(),this.processor=null),this.rateProcessor&&(this.rateProcessor.destroy(),this.rateProcessor=null),this.scriptNodeInterval&&(clearInterval(this.scriptNodeInterval),this.scriptNodeInterval=null),this.defaultPlaybackRate=1,this.playbackRate=1,this.scriptStartTime=0,this.audioBufferSize=0,this.engineType=te,this.player.debug.log("AudioContext","destroy")}isAudioPlaying(){return this.$audio&&Se(this.$audio.paused)&&Se(this.$audio.ended)&&0!==this.$audio.playbackRate&&0!==this.$audio.readyState}_bindAudioProxy(){const{proxy:e}=this.player.events,t=e(this.$audio,"canplay",(()=>{this.player.debug.log("AudioContext","canplay"),this._delayPlay&&this._audioElementPlay()}));this.eventListenList.push(t)}_getAudioElementReadyState(){let e=0;return this.$audio&&(e=this.$audio.readyState),e}audioElementPlay(){if(this.$audio){const e=this._getAudioElementReadyState();if(this.player.debug.log("AudioContext",`play and readyState: ${e}`),!(0!==e||me()&&ce()))return this.player.debug.warn("AudioContext","readyState is 0 and set _delayPlay to true"),void(this._delayPlay=!0);this._audioElementPlay()}}_audioElementPlay(){this.$audio&&this.$audio.play().then((()=>{this._delayPlay=!1,this.player.debug.log("AudioContext","_audioElementPlay success"),setTimeout((()=>{this.isAudioPlaying()||(this.player.debug.warn("AudioContext","play failed and retry play"),this._audioElementPlay())}),100),this.isAudioPlaying()&&(this.player.debug.log("AudioContext","play success and remove document click event listener"),document.removeEventListener("click",this._audioElementPlay.bind(this)))})).catch((e=>{this.player.debug.error("AudioContext","_audioElementPlay error",e),document.addEventListener("click",this._audioElementPlay.bind(this))}))}getAudioBufferSize(){return this.audioBufferSize}get oneBufferDuration(){return this.audioBufferSize/this.audioContext.sampleRate*1e3}get isActiveEngineType(){return this.engineType===se}initProcessor(){this.processor=new He(this.player,this,this.audioInfo.channels,this.audioBufferSize),this.rateProcessor=new $e(this.player,this,this.processor)}getAutoAudioEngineType(){let e=this.player._opt.audioEngine||te;const t=()=>{e=ye()?se:ce()&&this.player._opt.supportLockScreenPlayAudio?te:Be()&&this.supportAudioWorklet()?ee:te};return this.player._opt.audioEngine?this.player._opt.audioEngine===ee&&Be()?e=ee:this.player._opt.audioEngine===se?e=se:this.player._opt.audioEngine===te?e=te:t():t(),e}getAudioBufferSizeByType(){const e=this.engineType;this.player._opt.hasVideo;const t=this.player._opt.weiXinInAndroidAudioBufferSize;return e===ee?1024:e===se?t||4800:1024}supportAudioWorklet(){return this.audioContext&&this.audioContext.audioWorklet}initScriptNode(){this.playing=!0,this.hasInitScriptNode||(this.initProcessor(),this.engineType===ee?this.initWorkletScriptNode():this.engineType===se?this.initIntervalScriptNode():this.engineType===te&&this.initProcessScriptNode(),this.audioElementPlay())}getEngineType(){return this.engineType}isPlaybackRateSpeed(){return this.playbackRate>this.defaultPlaybackRate}initProcessScriptNode(){const e=this.audioContext.createScriptProcessor(this.audioBufferSize,0,this.audioInfo.channels);e.onaudioprocess=e=>{const t=e.outputBuffer;this.handleScriptNodeCallback(t)},e.connect(this.gainNode),this.scriptNode=e,this.gainNode.connect(this.mediaStreamAudioDestinationNode),this.$audio?this.$audio.srcObject=this.mediaStreamAudioDestinationNode.stream:this.gainNode.connect(this.audioContext.destination),this.hasInitScriptNode=!0}initIntervalScriptNode(){this.scriptStartTime=0;const e=1e3*this.audioBufferSize/this.audioContext.sampleRate;this.scriptNodeInterval=setInterval((()=>{if(0===this.bufferList.length||Se(this.playing)||this.isMute)return void(this.playing&&Se(this.isMute)&&this.player.debug.log("AudioContext",`interval script node and bufferList is ${this.bufferList.length} or playing is ${this.playing}`));const e=this.audioContext.createBufferSource(),t=this.audioContext.createBuffer(this.audioInfo.channels,this.audioBufferSize,this.audioContext.sampleRate);this.handleScriptNodeCallback(t,(()=>{this.scriptStartTime<this.audioContext.currentTime&&(this.player.debug.log("AudioContext",`script start time ${this.scriptStartTime} is less than current time ${this.audioContext.currentTime}`),this.scriptStartTime=this.audioContext.currentTime),e.buffer=t,e.connect(this.gainNode),e.start(this.scriptStartTime),this.scriptStartTime+=t.duration}))}),e),this.gainNode.connect(this.mediaStreamAudioDestinationNode),this.$audio?this.$audio.srcObject=this.mediaStreamAudioDestinationNode.stream:this.gainNode.connect(this.audioContext.destination),this.hasInitScriptNode=!0}initWorkletScriptNode(){let e=function(e){const t=e.toString().trim().match(/^function\s*\w*\s*\([\w\s,]*\)\s*{([\w\W]*?)}$/)[1],s=new Blob([t],{type:"application/javascript"});return URL.createObjectURL(s)}((function(){class e extends AudioWorkletProcessor{constructor(){super(),this.audioBufferSize=1024,this.start=!1,this.channels=1,this.samplesArray=[],this.offset=0,this.state=0,this.port.onmessage=e=>{"init"===e.data.message?(this.audioBufferSize=e.data.audioBufferSize,this.start=e.data.start,this.channels=e.data.channels,this.state=0,this.offset=0,this.samplesArray=[]):"stop"===e.data.message?(this.state=0,this.start=!1,this.offset=0,this.samplesArray=[]):"data"===e.data.message?this.samplesArray.push(e.data.buffer):"zero"===e.data.message&&this.samplesArray.push({left:new Float32Array(this.audioBufferSize).fill(0),right:new Float32Array(this.audioBufferSize).fill(0)})}}process(e,t,s){const i=t[0][0],A=t[0][1];if(0===this.offset&&this.port.postMessage({message:"beep"}),0===this.state)this.state=1;else if(1===this.state&&this.samplesArray.length>=4)this.state=2;else if(2===this.state){const e=this.samplesArray[0];for(let t=0;t<i.length;t++)1===this.channels?i[t]=e.left[t+this.offset]:2===this.channels&&(i[t]=e.left[t+this.offset],A&&(A[t]=e.right[t+this.offset]))}else 1===this.channels?i.fill(0):2===this.channels&&(i.fill(0),A&&A.fill(0));return this.offset+=128,this.offset===this.audioBufferSize&&(this.offset=0,2===this.state&&this.samplesArray.shift(),0===this.samplesArray.length&&(this.state=0)),this.start}}registerProcessor("worklet-processor",e)}));this.workletUrl=e,this.audioContext.audioWorklet.addModule(e).then((()=>{if(this.player.isDestroyedOrClosed())return void this.player.debug.log("AudioContext","initWorkletScriptNode() player is destroyed");if(!this.audioContext)return void this.player.debug.warn("AudioContext","initWorkletScriptNode audioContext is null");let e=[1];2===this.audioInfo.channels&&(e=[1,1]);try{this.workletProcessorNode=new AudioWorkletNode(this.audioContext,"worklet-processor",{numberOfOutputs:this.audioInfo.channels,outputChannelCount:e})}catch(e){this.player.debug.error("AudioContext","initWorkletScriptNode error",e),this.workletProcessorNode=null,this.tierDownToProcessScript()}this.workletProcessorNode&&(this.workletProcessorNode.connect(this.gainNode),this.gainNode.connect(this.mediaStreamAudioDestinationNode),this.$audio?this.$audio.srcObject=this.mediaStreamAudioDestinationNode.stream:this.gainNode.connect(this.audioContext.destination),this.hasInitScriptNode=!0,this.workletProcessorNode.port.postMessage({message:"init",audioBufferSize:this.audioBufferSize,start:!0,channels:this.audioInfo.channels}),this.workletProcessorNode.port.onmessage=e=>{this.workletProcessorNode?this.audioContext?this.handleScriptNodeCallback(this.workletProcessorNode,null,!0):this.workletProcessorNode.port.postMessage({message:"zero"}):this.player.debug.error("AudioContext","workletProcessorNode is null")})})),this.clearWorkletUrlTimeout=setTimeout((()=>{URL.revokeObjectURL(this.workletUrl),this.workletUrl=null,this.clearWorkletUrlTimeout=null}),E)}tierDownToProcessScript(){this.player.debug.log("AudioContext","tierDownToProcessScript"),this.engineType=te,this.audioBufferSize=this.getAudioBufferSizeByType(),this.initProcessScriptNode(),this.audioElementPlay()}handleScriptNodeCallback(e,t){let s,i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];t=t||ne;let A=e.length;i&&(s=e,A=this.audioBufferSize);const r=this.audioInfo.channels;if(this.bufferList.length&&this.playing){if(this.player._opt,this.player.openSyncAudioAndVideo()&&Ee(this.player.visibility)){this.calcPlaybackRateBySync();const A=this.player.getAudioSyncVideoDiff();if(A>this.player._opt.syncAudioAndVideoDiff)return this.player.debug.warn("AudioContext",`audioSyncVideoOption more than diff :${A}, waiting and bufferList is ${this.bufferList.length}`),i?s.port.postMessage({message:"zero"}):this.fillScriptNodeOutputBuffer(e,r),void t()}let o=this._provide(A);if(0===o.size)return this.player.debug.warn("AudioContext",`bufferList size is ${this.bufferList.length} outputBufferLength is ${A},and bufferItem.size is 0`),i?s.port.postMessage({message:"zero"}):this.fillScriptNodeOutputBuffer(e,r),void t();o&&o.ts&&(this.player.audioTimestamp=o.ts),i?s.port.postMessage({message:"data",buffer:o}):this.fillScriptNodeOutputBuffer(e,r,o),t()}else 0===this.bufferList.length&&this.playing&&Se(this.isMute)&&this.player.debug.warn("AudioContext",`bufferList size is 0 and outputBufferLength is ${A}`),i?s.port.postMessage({message:"zero"}):this.fillScriptNodeOutputBuffer(e,r),t()}fillScriptNodeOutputBuffer(e,t,s){if(1===t){const t=e.getChannelData(0);s?0===s.size?t.fill(0):t.set(s.left):t.fill(0)}else if(2===t){const t=e.getChannelData(0),i=e.getChannelData(1);s?0===s.size?(t.fill(0),i.fill(0)):(t.set(s.left),i.set(s.right)):(t.fill(0),i.fill(0))}}play(e,t){this.isMute||(this.hasInitScriptNode?(this.hasAudio=!0,this.player.latestAudioTimestamp=t,this.bufferList.push({buffer:e,ts:t}),Se(this.player.openSyncAudioAndVideo())&&this.calcPlaybackRateByBuffer()):this.player.debug.warn("AudioContext","play has not init script node"))}calcPlaybackRateBySync(){if(this.isMute)return;if(!this.playing)return;const e=Math.floor(2e3/this.oneBufferDuration);if(this.bufferList.length>e)return this.player.debug.warn("AudioContext",`bufferList length ${this.bufferList.length} more than ${e}, and drop`),void this.clear();const t=this.player.getAudioSyncVideoDiff();if(this.getEngineType()===se){if(t<-this.player._opt.syncAudioAndVideoDiff){this.player.debug.warn("AudioContext",`engine active , audioSyncVideoOption ${-this.player._opt.syncAudioAndVideoDiff} less than diff :${t},\n and bufferlist is ${this.bufferList.length}`);const e=this.player.getRenderCurrentPts();for(;this.bufferList.length>0;){const t=this.bufferList[0],s=t.ts-e;if(s>-this.player._opt.syncAudioAndVideoDiff/2){this.player.audioTimestamp=t.ts,this.player.debug.log("AudioContext",`engine active , audioSyncVideoOption\n item.ts is ${t.ts} and currentVideoTimestamp is ${e}, diff is ${s} > -${this.player._opt.syncAudioAndVideoDiff/2} and end`);break}this.bufferList.shift(),this.player.audioTimestamp=t.ts}}}else{let e=this.playbackRate;t<-this.player._opt.syncAudioAndVideoDiff?e===this.defaultPlaybackRate&&(this.player.debug.log("AudioContext",`audioSyncVideoOption ${-this.player._opt.syncAudioAndVideoDiff} less than diff :${t},\n speed up, playbackRate is ${e},\n and bufferList is ${this.bufferList.length}`),e=this.defaultPlaybackRate+.2):t>-this.player._opt.syncAudioAndVideoDiff/2&&e!==this.defaultPlaybackRate&&(this.player.debug.log("AudioContext",`diff is ${t} > -${this.player._opt.syncAudioAndVideoDiff/2} and speed to 1`),e=this.defaultPlaybackRate),this.updatePlaybackRate(e)}}calcPlaybackRateByBuffer(){if(this.isMute)return;if(!this.playing)return;let e=this.playbackRate,t=1e3,s=5e3;this.isAudioPlayer&&(t=this.player._opt.videoBufferDelay,s=this.player._opt.videoBufferMax);const i=Math.floor(t/this.oneBufferDuration),A=Math.floor(s/this.oneBufferDuration);if(this.bufferList.length>A)return this.player.debug.warn("AudioContext",`bufferList length ${this.bufferList.length} more than ${A}, and drop`),void this.clear();this.getEngineType()!==se&&(this.bufferList.length>i?(e=this.defaultPlaybackRate+.2,this.player.debug.log("AudioContext",`bufferList length ${this.bufferList.length} more than ${i}, speed up, playbackRate is ${e}`)):this.bufferList.length<i/2&&(e=this.defaultPlaybackRate),this.updatePlaybackRate(e))}updatePlaybackRate(e){this.rateProcessor&&(this.playbackRate=e,this.rateProcessor.setRate(this.playbackRate))}_provide(e){return(1===this.playbackRate?this.processor:this.rateProcessor).provide(e)}}class Je extends t{constructor(e){super(),this.player=e,this.$video=e.video.$videoElement,this.init=!1,this.player._opt.hlsUseCanvasRender&&(this.$video=this.player.hlsDecoder.$videoElement),this.player._opt.webrtcUseCanvasRender&&(this.$video=this.player.webrtc.$videoElement),this.audioInfo={encTypeCode:"",encType:"",channels:"",sampleRate:"",depth:""},this.player.debug.log("Audio","init")}destroy(){this.resetInit(),this.off(),this.player.debug.log("Audio","destroy")}resetInit(){this.init=!1,this.audioInfo={encTypeCode:"",encType:"",channels:"",sampleRate:"",depth:""}}getAudioInfo(){return this.audioInfo}updateAudioInfo(e){e.encTypeCode&&(this.audioInfo.encTypeCode=e.encTypeCode,this.audioInfo.encType=J[e.encTypeCode]),e.encType&&(this.audioInfo.encType=e.encType),e.channels&&(this.audioInfo.channels=e.channels),e.sampleRate&&(this.audioInfo.sampleRate=e.sampleRate),e.depth&&(this.audioInfo.depth=e.depth),this.audioInfo.sampleRate&&this.audioInfo.channels&&this.audioInfo.encType&&!this.init&&(this.player.debug.log("Audio","audioInfo",JSON.stringify(this.audioInfo)),this.player.emit(F.audioInfo,this.audioInfo),this.init=!0)}get isPlaying(){return!0}get volume(){return Ee(this.$video.muted)?0:this.$video.volume}get isMute(){return 0===this.$video.volume||Ee(this.$video.muted)}mute(e){this.setVolume(e?0:this.player.lastVolume||.5)}setVolume(e){e=parseFloat(e),isNaN(e)||(e=le(e,0,1),this.$video.muted&&(this.$video.muted=!1),ce()&&(this.$video.muted=0===e),this.player.isAliyunRtc()&&this.player.aliyunRtcDecoder&&this.player.aliyunRtcDecoder.aliyunRtcRemoteStream&&(this.player.aliyunRtcDecoder.aliyunRtcRemoteStream.muted=0===e),this.$video.volume=e,this.player.emit(F.volumechange,this.player.volume))}clear(){}play(){}pause(){}resume(){}getEngineType(){return"audio"}isPlaybackRateSpeed(){return!1}getAudioBufferSize(){return 0}setRate(){}initScriptNode(){}initScriptNodeDelay(){}}class Ze extends Ve{constructor(e){super(e),this.delayTimeout=null,this.player.on(F.playbackPause,(e=>{this.listenPlaybackPause(e)})),this.player.debug.log("AudioPlaybackContext","init")}destroy(){this.delayTimeout&&(clearTimeout(this.delayTimeout),this.delayTimeout=null),super.destroy(),this.player.debug.log("AudioPlaybackLoader","destroy")}listenPlaybackPause(e){e?(this.pause(),this.player.playback.isPlaybackPauseClearCache&&this.clear()):this.resume()}initScriptNodeDelay(){const e=this.player._opt.playbackDelayTime;e>0?this.delayTimeout=setTimeout((()=>{this.initScriptNode()}),e):this.initScriptNode()}setRate(e){e!==this.defaultPlaybackRate&&this.rateProcessor&&(this.player.debug.log("AudioPlaybackContext","setRate",e),this.defaultPlaybackRate=e,this.updatePlaybackRate(e))}}class Xe extends Ve{constructor(e){super(e),this.TAG_NAME="AudioPlayerLoader",this.isAudioPlayer=!0,this.player.debug.log(this.TAG_NAME,"init")}destroy(){super.destroy(),this.player.debug.log(this.TAG_NAME,"destroy")}play(e,t){Se(this.playing)||super.play(e,t)}pause(){this.player.debug.log(this.TAG_NAME,"pause"),this.playing=!1,this.clear()}resume(){this.player.debug.log(this.TAG_NAME,"resume"),this.playing=!0}}class Ke{constructor(e){return new(Ke.getLoaderFactory(e._opt))(e)}static getLoaderFactory(e){return e.playType===y?e.useMSE&&e.mseDecodeAudio?Je:Ze:e.playType===f?Xe:e.isHls&&Se(e.supportHls265)||e.isWebrtc&&Se(e.isWebrtcH265)||e.useMSE&&e.mseDecodeAudio||e.isAliyunRtc?Je:Ve}}const et=()=>"wakeLock"in navigator&&-1===window.navigator.userAgent.indexOf("Samsung")&&Se(ce());class tt{constructor(e){this.player=e,this.enabled=!1,et()?(this.player.debug.log("NoSleep","Native Wake Lock API supported."),this._wakeLock=null,this.handleVisibilityChange=()=>{null!==this._wakeLock&&"visible"===document.visibilityState&&this.enable()},document.addEventListener("visibilitychange",this.handleVisibilityChange),document.addEventListener("fullscreenchange",this.handleVisibilityChange)):(this.player.debug.log("NoSleep","Native Wake Lock API not supported. so use video element."),this.noSleepVideo=document.createElement("video"),this.noSleepVideo.setAttribute("title","No Sleep"),this.noSleepVideo.setAttribute("playsinline",""),this._addSourceToVideo(this.noSleepVideo,"webm","data:video/webm;base64,GkXfo59ChoEBQveBAULygQRC84EIQoKEd2VibUKHgQRChYECGFOAZwEAAAAAABLfEU2bdLpNu4tTq4QVSalmU6yBoU27i1OrhBZUrmtTrIHYTbuMU6uEElTDZ1OsggGXTbuMU6uEHFO7a1OsghLJ7AEAAAAAAABZ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jh4IDNYD4//6jh4IDSYD4//6jh4IDXYD4//6jh4IDcYD4//6jh4IDhYD4//6jnoEDiwDRAgAFEKwAGAAYWC/0AAiABDNfrXJPnHMAAKOHggOZgPj//qOHggOtgPj//qOHggPBgPj//qOHggPVgPj//qOHggPpgPj//qOegQPvANECAAUQrAAYABhYL/QACIAEM1+tck+ccwAAo4eCA/2A+P/+o4eCBBGA+P/+o4eCBCWA+P/+o4eCBDmA+P/+o4eCBE2A+P/+o56BBFMA0QIABRCsABgAGFgv9AAIgAQzX61yT5xzAACjh4IEiID4//6jh4IEnID4//6jh4IEsID4//6jnoEEtwDRAgAFEKwAGAAYWC/0AAiABDNfrXJPnHMAAKOHggTEgPj//qOHggTYgPj//qOHggTsgPj//qOHggUAgPj//qOHggUUgPj//qOegQUbANECAAUQrAAYABhYL/QACIAEM1+tck+ccwAAo4eCBSiA+P/+o4eCBTyA+P/+o4eCBVCA+P/+o4eCBWSA+P/+o4eCBXiA+P/+o56BBX8A0QIABRCsABgAGFgv9AAIgAQzX61yT5xzAACjh4IFjID4//6jh4IFoID4//6jh4IFtID4//6jh4IFyID4//6jh4IF3ID4//6jnoEF4wDRAgAFEKwAGAAYWC/0AAiABDNfrXJPnHMAAKOHggXwgPj//qOHggYEgPj//qOHggYYgPj//qOHggYsgPj//qOHggZAgPj//qOegQZHANECAAUQrAAYABhYL/QACIAEM1+tck+ccwAAo4eCBlSA+P/+o4eCBmiA+P/+o4eCBnyA+P/+o4eCBpCA+P/+o4eCBqSA+P/+o56BBqsA0QIABRCsABgAGFgv9AAIgAQzX61yT5xzAACjh4IGuID4//6jh4IGzID4//6jh4IG4ID4//6jh4IG9ID4//6jh4IHCID4//6jnoEHDwDRAgAFEBAUYABhYL/QACIAEM1+tck+ccwAAKOHggccgPj//qOHggcwgPj//qOHggdEgPj//qOHggdYgPj//qOHggdsgPj//qOegQdzANECAAUQrAAYABhYL/QACIAEM1+tck+ccwAAo4eCB4CA+P/+o4eCB5SA+P/+o4eCB6iA+P/+o4eCB7yA+P/+o4eCB9CA+P/+o56BB9cA0QIABRCsABgAGFgv9AAIgAQzX61yT5xzAACjh4IH5ID4//6jh4IH+ID4//6jh4IIDID4//6jh4IIIID4//6jh4IINID4//6jnoEIOwDRAgAFEKwAGAAYWC/0AAiABDNfrXJPnHMAAKOHgghIgPj//qOHgghcgPj//qOHgghwgPj//qOHggiEgPj//qOegQifANECAAUQrAAYABhYL/QACIAEM1+tck+ccwAAo4eCCMCA+P/+o4eCCNSA+P/+o4eCCOiA+P/+o4eCCPyA+P/+o56BCQMA0QIABRCsABgAGFgv9AAIgAQzX61yT5xzAACjh4IJEID4//6jh4IJJID4//6jh4IJOID4//6jh4IJTID4//6jh4IJYID4//6jnoEJZwDRAgAFEKwAGAAYWC/0AAiABDNfrXJPnHMAAKOHggl0gPj//qOHggmIgPj//qOHggmcgPj//qOHggmwgPj//qOHggnEgPj//qOegQnLANECAAUQrAAYABhYL/QACIAEM1+tck+ccwAAo4eCCdiA+P/+o4eCCeyA+P/+o4eCCgCA+P/+o4eCChSA+P/+o4eCCiiA+P/+o56BCi8A0QIABRCsABgAGFgv9AAIgAQzX61yT5xzAACjh4IKPID4//6jh4IKUID4//6jh4IKZID4//6jh4IKeID4//6jh4IKjID4//6jnoEKkwDRAgAFEKwAGAAYWC/0AAiABDNfrXJPnHMAAKOHggqggPj//qOHggq0gPj//qOHggrIgPj//qOHggrcgPj//qOHggrwgPj//qOegQr3ANECAAUQrAAYABhYL/QACIAEM1+tck+ccwAAo4eCCwSA+P/+o4eCCxiA+P/+o4eCCyyA+P/+o4eCC0CA+P/+o4eCC1SA+P/+o56BC1sA0QIABRAQFGAAYWC/0AAiABDNfrXJPnHMAACjh4ILaID4//6jh4ILfID4//6jh4ILkID4//6jh4ILpID4//6jh4ILuID4//6jnoELvwDRAgAFEKwAGAAYWC/0AAiABDNfrXJPnHMAAKOHggvMgPj//qOHggvggPj//qOHggv0gPj//qOHggwIgPj//qOHggwcgPj//qOegQwjANECAAUQrA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NfrXJPnHMAAKOHghB8gPj//qOHghCQgPj//qOHghCkgPj//qOHghC4gPj//qOHghDMgPj//qOegRDTANECAAUQrAAYABhYL/QACIAEM1+tck+ccwAAo4eCEOCA+P/+o4eCEPSA+P/+o4eCEQiA+P/+o56BETcA0QIABRCsABgAGFgv9AAIgAQzX61yT5xzAACjh4IRQ4D4//6jh4IRV4D4//6jh4IRa4D4//6jh4IRf4D4//6jh4IRk4D4//6jnoERmwDRAgAFEKwAGAAYWC/0AAiABDNfrXJPnHMAAKOHghGngPj//qOHghG7gPj//qOHghHPgPj//qOHghHjgPj//qOHghH3gPj//qOegRH/ANECAAUQrAAYABhYL/QACIAEM1+tck+ccwAAo4eCEguA+P/+o4eCEh+A+P/+o4eCEjOA+P/+o4eCEkeA+P/+o4eCEluA+P/+o56BEmMA0QIABRCsABgAGFgv9AAIgAQzX61yT5xzAACjh4ISb4D4//6jh4ISg4D4//6jh4ISl4D4//6jh4ISq4D4//6jh4ISv4D4//6jnoESxwDRAgAFEKwAGAAYWC/0AAiABDNfrXJPnHMAAKOHghLTgPj//qOHghLngPj//qOHghL7gPj//qOHghMPgPj//qOHghMjgPj//qOegRMrANECAAUQrAAYABhYL/QACIAEM1+tck+ccwAAo4eCEzeA+P/+o4eCE0uA+P/+o4eCE1+A+P/+o4eCE3OA+P/+oAEAAAAAAAAPoYeCE4cA+P/+daKDB/KBHFO7a5G7j7OBB7eK94EB8YIDX/CBDA=="),this._addSourceToVideo(this.noSleepVideo,"mp4","data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAAIZnJlZQAACORtZGF03gIATGF2YzU4LjM1LjEwMAACMEAOAAACcQYF//9t3EXpvebZSLeWLNgg2SPu73gyNjQgLSBjb3JlIDE2MSByMzAyNyA0MTIxMjc3IC0gSC4yNjQvTVBFRy00IEFWQyBjb2RlYyAtIENvcHlsZWZ0IDIwMDMtMjAyMCAtIGh0dHA6Ly93d3cudmlkZW9sYW4ub3JnL3gyNjQuaHRtbCAtIG9wdGlvbnM6IGNhYmFjPTAgcmVmPTMgZGVibG9jaz0xOjA6MCBhbmFseXNlPTB4MToweDExMSBtZT1oZXggc3VibWU9NyBwc3k9MSBwc3lfcmQ9MS4wMDowLjAwIG1peGVkX3JlZj0xIG1lX3JhbmdlPTE2IGNocm9tYV9tZT0xIHRyZWxsaXM9MSA4eDhkY3Q9MCBjcW09MCBkZWFkem9uZT0yMSwxMSBmYXN0X3Bza2lwPTEgY2hyb21hX3FwX29mZnNldD0tMiB0aHJlYWRzPTcgbG9va2FoZWFkX3RocmVhZHM9MSBzbGljZWRfdGhyZWFkcz0wIG5yPTAgZGVjaW1hdGU9MSBpbnRlcmxhY2VkPTAgYmx1cmF5X2NvbXBhdD0wIGNvbnN0cmFpbmVkX2ludHJhPTAgYmZyYW1lcz0wIHdlaWdodHA9MCBrZXlpbnQ9MjUwIGtleWludF9taW49MTAgc2NlbmVjdXQ9NDAgaW50cmFfcmVmcmVzaD0wIHJjX2xvb2thaGVhZD00MCByYz1jcmYgbWJ0cmVlPTEgY3JmPTIzLjAgcWNvbXA9MC42MCBxcG1pbj0wIHFwbWF4PTY5IHFwc3RlcD00IGlwX3JhdGlvPTEuNDAgYXE9MToxLjAwAIAAAADvZYiED/JigADD7JycnJycnJycnJycnJycnJycnJ11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111114BGCAHARggBwEYIAcBGCAHARggBwAAAAdBmjgf4BLYARggBwEYIAcBGCAHARggBwAAAAdBmlQH+AS2ARggBwEYIAcBGCAHARggBwAAAAdBmmA/wCWwARggBwEYIAcBGCAHARggBwEYIAcAAAAHQZqAP8AlsAEYIAcBGCAHARggBwEYIAcAAAAHQZqgP8AlsAEYIAcBGCAHARggBwEYIAcAAAAHQZrAP8AlsAEYIAcBGCAHARggBwEYIAcBGCAHAAAAB0Ga4D/AJbABGCAH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wAAARXAAAEdgAABJEAAASsAAAEywAABOIAAAT5AAAFGAAABTMAAAVOAAAFbQAABYgAAAWjAAAFwgAABd0AAAX4AAAGDwAABioAAAZFAAAGZAAABn8AAAaaAAAGuQAABtQAAAbvAAAHDgAABykAAAc8AAAHWwAAB3YAAAeRAAAHsAAAB8sAAAfmAAAIBQAACCAAAAg7AAAIWgAACG0AAAiIAAAIpwAACMIAAAjdAAAI/AAAABpzZ3BkAQAAAHJvbGwAAAACAAAAAf//AAAAHHNiZ3AAAAAAcm9sbAAAAAEAAADSAAAAAQAAAGJ1ZHRhAAAAWm1ldGEAAAAAAAAAIWhkbHIAAAAAAAAAAG1kaXJhcHBsAAAAAAAAAAAAAAAALWlsc3QAAAAlqXRvbwAAAB1kYXRhAAAAAQAAAABMYXZmNTguMjAuMTAw"),Object.assign(this.noSleepVideo.style,{position:"absolute",left:"-100%",top:"-100%"}),document.querySelector("body").append(this.noSleepVideo),this.handleNoSleepVideoTimeUpdate=()=>{this.noSleepVideo&&this.noSleepVideo.currentTime>4&&(this.noSleepVideo.currentTime=1)},this.noSleepVideo.addEventListener("timeupdate",this.handleNoSleepVideoTimeUpdate))}destroy(){if(this._wakeLock&&(this._wakeLock.release(),this._wakeLock=null),this.noSleepVideo){this.handleNoSleepVideoTimeUpdate&&this.noSleepVideo.removeEventListener("timeupdate",this.handleNoSleepVideoTimeUpdate);try{this.noSleepVideo.parentNode&&this.noSleepVideo.parentNode.removeChild(this.noSleepVideo)}catch(e){this.player.debug.warn("NoSleep","Failed to remove noSleepVideo element.")}this.noSleepVideo=null}this.handleVisibilityChange&&(document.removeEventListener("visibilitychange",this.handleVisibilityChange),document.removeEventListener("fullscreenchange",this.handleVisibilityChange))}_addSourceToVideo(e,t,s){var i=document.createElement("source");i.src=s,i.type=`video/${t}`,e.appendChild(i)}get isEnabled(){return this.enabled}enable(){const e=this.player.debug;if(et())return navigator.wakeLock.request("screen").then((t=>{this._wakeLock=t,this.enabled=!0,e.log("wakeLock","Wake Lock active."),this._wakeLock.addEventListener("release",(()=>{e.log("wakeLock","Wake Lock released.")}))})).catch((t=>{throw this.enabled=!1,e.warn("wakeLock",`${t.name}, ${t.message}`),t}));return this.noSleepVideo.play().then((t=>(e.log("wakeLock","noSleepVideo Wake Lock active."),this.enabled=!0,t))).catch((t=>{throw e.warn("wakeLock",`noSleepVideo ${t.name}, ${t.message}`),this.enabled=!1,t}))}disable(){et()?(this._wakeLock&&this._wakeLock.release(),this._wakeLock=null):this.noSleepVideo&&this.noSleepVideo.pause(),this.enabled=!1,this.player.debug.log("wakeLock","Disabling wake lock.")}}class st{constructor(e){this.player=e,this.TAG_NAME="decoderAudioWorker",this.destroyResolve=null,this.workerClearTimeout=null,this.workerUrl=null;let t=this.player._opt.decoder;if(this.decoderWorkerCloseTimeout=null,0===t.indexOf("http")&&this.player._opt.isDecoderUseCDN){const e=new Blob([`importScripts("${t}")`],{type:"application/javascript"});t=window.URL.createObjectURL(e),this.workerUrl=t,this.workerClearTimeout=setTimeout((()=>{window.URL.revokeObjectURL(this.workerUrl),this.workerUrl=null,this.workerClearTimeout=null}),E)}this.decoderWorker=new Worker(t),this._initDecoderWorker(),e.debug.log(this.TAG_NAME,`init and decoder url is ${t}`)}destroy(){return new Promise(((e,t)=>{this.player.loaded?(this.player.debug.log(this.TAG_NAME,"has loaded and post message to destroy"),this.decoderWorker?(this.decoderWorker.postMessage({cmd:D}),this.destroyResolve=e,this.decoderWorkerCloseTimeout=setTimeout((()=>{this.player.debug.warn(this.TAG_NAME,"send close but not response and destroy directly"),this.decoderWorkerCloseTimeout&&(clearTimeout(this.decoderWorkerCloseTimeout),this.decoderWorkerCloseTimeout=null),this._destroy(),setTimeout((()=>{e()}),0)}),2e3)):(this.player.debug.warn(this.TAG_NAME,"has loaded but decoderWorker is null and destroy directly"),this._destroy(),setTimeout((()=>{e()}),0))):(this.player.debug.log(this.TAG_NAME,"has not loaded and destroy directly"),this._destroy(),setTimeout((()=>{e()}),0))}))}_destroy(){this.decoderWorkerCloseTimeout&&(clearTimeout(this.decoderWorkerCloseTimeout),this.decoderWorkerCloseTimeout=null),this.workerUrl&&(window.URL.revokeObjectURL(this.workerUrl),this.workerUrl=null),this.workerClearTimeout&&(clearTimeout(this.workerClearTimeout),this.workerClearTimeout=null),this.decoderWorker&&(this.decoderWorker.terminate(),this.decoderWorker.onerror=null,this.decoderWorker.onmessageerror=null,this.decoderWorker.onmessage=null,this.decoderWorker=null),this.player.debug.log(this.TAG_NAME,"destroy"),this.destroyResolve&&(this.destroyResolve(),this.destroyResolve=null)}_initDecoderWorker(){const{debug:e,events:{proxy:t}}=this.player;this.decoderWorker.onerror=e=>{this.player.debug.error(this.TAG_NAME,"onerror",e),this.player.emitError(z.decoderWorkerInitError,e)},this.decoderWorker.onmessageerror=e=>{this.player.debug.error(this.TAG_NAME,"onmessageerror",e)},this.decoderWorker.onmessage=t=>{const s=t.data;switch(s.cmd){case S:e.log(this.TAG_NAME,"onmessage:",S),this.decoderWorker&&this._initWork(),this.player.loaded||this.player.emit(F.load),this.player.emit(F.decoderWorkerInit);break;case I:e.log(this.TAG_NAME,"onmessage:",I,s.code),this.player.audio&&this.player.audio.updateAudioInfo({encTypeCode:s.code});break;case T:if(e.log(this.TAG_NAME,"onmessage:",T,`channels:${s.channels},sampleRate:${s.sampleRate}`),s.channels>2)return this.player.emit(F.error,z.audioChannelError),void this.player.emit(z.audioChannelError,`audio channel is ${s.channels}, max is 2`);this.player.audio&&(this.player.audio.updateAudioInfo(s),this.player.audio.initScriptNode());break;case k:if(!this.player.audio)return void e.warn(this.TAG_NAME,"onmessage playAudio but audio is null");this.player.handleRender(),this.player.updateStats({ts:s.ts,buf:s.delay}),this.player.audio.play(s.buffer,s.ts);break;case _:s.type===F.streamSuccess?this.player.stream?this.player.stream.emit(F.streamSuccess):e.warn(this.TAG_NAME,"onmessage and workerFetch response stream success but stream is null"):s.type===F.streamRate?this.player.emit(F.kBps,(s.value/1024).toFixed(2)):s.type===F.streamEnd?this.player?(s.value===u&&this.player.emit(F.websocketClose,s.msg),this.player.stream?this.player.stream.emit(F.streamEnd,s.msg):e&&e.warn(this.TAG_NAME,"onmessage and workerFetch response stream end but player.stream is null")):e&&e.warn(this.TAG_NAME,"onmessage and workerFetch response stream end but player is null"):s.type===z.websocketError?(this.player&&this.player.stream?this.player.stream.emit(z.websocketError,s.value):e&&e.warn(this.TAG_NAME,"onmessage and workerFetch response websocket error but stream is null"),this.player&&this.player.emit(F.error,z.websocketError)):s.type===z.fetchError?(this.player&&this.player.stream?this.player.stream.emit(z.fetchError,s.value):e&&e.warn(this.TAG_NAME,"onmessage and workerFetch response fetch error but stream is null"),this.player&&this.player.emit(F.error,z.fetchError)):s.type===F.streamAbps&&this.player.updateStats({abps:s.value});break;case v:e.log(this.TAG_NAME,"onmessage:",v),this.player.destroy(),console.error("Jb pro 体验结束,请刷新页面再次体验(wasm内部会暂停解码),如需要购买商业授权,可以联系微信:bosswancheng"),alert("Jb pro 体验结束,请刷新页面再次体验,如需要购买商业授权,可以联系微信:bosswancheng"),window.location.reload();break;case R:e.log(this.TAG_NAME,"onmessage:",R),this._destroy();break;default:e.warn(this.TAG_NAME,"onmessage:",`unknown msg.cmd:${s.cmd}`)}}}_initWork(){const e={debug:this.player._opt.debug,debugLevel:this.player._opt.debugLevel,sampleRate:this.player.audio&&this.player.audio.audioContext&&this.player.audio.audioContext.sampleRate||0,audioBufferSize:this.player.audio&&this.player.audio.getAudioBufferSize()||1024,videoBuffer:this.player._opt.videoBuffer,isChrome:fe()};this.decoderWorker.postMessage({cmd:P,opt:JSON.stringify(e)})}updateWorkConfig(e){this.decoderWorker&&this.decoderWorker.postMessage({cmd:M,key:e.key,value:e.value})}workerFetchStream(e){const{_opt:t}=this.player,s={protocol:t.protocol,isFlv:t.isFlv};this.decoderWorker.postMessage({cmd:N,url:e,opt:JSON.stringify(s)})}workerSendMessage(e){this.decoderWorker.postMessage({cmd:L,message:e})}}class it extends t{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(),this._opt={},this.TAG_NAME="AudioPlayer";const t=we();this._opt=Object.assign({},t,e),this.debug=new ae(this),this._loading=!1,this._playing=!1,this._hasLoaded=!1,this._destroyed=!1,this._closed=!1,this._checkHeartTimeout=null,this._checkLoadingTimeout=null,this._checkStatsInterval=null,this._startBpsTime=null,this._stats={abps:0,ts:0,buf:0,audioBufferTs:0},this._audioTimestamp=0,this.stream=null,this._lastVolume=null,this._historyAbpsList=[],this._times={playInitStart:"",playStart:"",streamStart:"",streamResponse:"",demuxStart:"",decodeStart:"",videoStart:"",playTimestamp:"",streamTimestamp:"",streamResponseTimestamp:"",demuxTimestamp:"",decodeTimestamp:"",videoTimestamp:"",allTimestamp:""},this._tempWorkerStats=null,/(iphone|ipad|ipod|ios|android)/i.test(window.navigator.userAgent.toLowerCase())&&Se(this._opt.supportLockScreenPlayAudio&&ce())&&(this.keepScreenOn=new tt(this)),Te(this),this.stream=null,this.events=new ke(this),this.decoderWorker=new st(this),this.audio=new Ke(this),this.debug.log(this.TAG_NAME,"_opt",JSON.stringify(this._opt))}destroy(){return new Promise(((e,t)=>{this._destroyed=!0,this.emit("destroy"),this.off(),this.events&&(this.events.destroy(),this.events=null),this.clearCheckHeartTimeout(),this.clearCheckLoadingTimeout(),this.clearStatsInterval(),this.decoderWorker?this.decoderWorker.destroy().then((()=>{this.decoderWorker=null,this._destroy(),e()})):(this._destroy(),e())}))}_destroy(){this._loading=!1,this._playing=!1,this._hasLoaded=!1,this._destroyed=!1,this._checkHeartTimeout=null,this._checkLoadingTimeout=null,this._checkStatsInterval=null,this._resetStats(),this._audioTimestamp=0,this._times={playInitStart:"",playStart:"",streamStart:"",streamResponse:"",demuxStart:"",decodeStart:"",videoStart:"",playTimestamp:"",streamTimestamp:"",streamResponseTimestamp:"",demuxTimestamp:"",decodeTimestamp:"",videoTimestamp:"",allTimestamp:""},this._tempWorkerStats=null,this.audio&&(this.audio.destroy(),this.audio=null),this.stream&&(this.stream.destroy(),this.stream=null),this.debug.log(this.TAG_NAME,"destroy end"),this._opt=we()}_resetStats(){this._startBpsTime=null,this._playingStartTimestamp=null,this._historyAbpsList=[],this._stats={abps:0,ts:0,buf:0,audioBufferTs:0}}set loaded(e){this._hasLoaded=e}get loaded(){return this._hasLoaded}set playing(e){e&&(this.loading=!1),this.playing!==e&&(this._playing=e,this.emit(F.playing,e),this.emit(F.volumechange,this.volume),e?this.emit(F.play):this.emit(F.pause))}get playing(){return this._playing}get volume(){return this.audio&&this.audio.volume||0}set volume(e){e!==this.volume&&(this.audio?(this.audio.setVolume(e),this._lastVolume=this.volume):this.debug.warn(this.TAG_NAME,"set volume error, audio is null"))}get lastVolume(){return this._lastVolume}set loading(e){this.loading!==e&&(this._loading=e,this.emit(F.loading,this._loading))}get loading(){return this._loading}set audioTimestamp(e){null!==e&&(this._audioTimestamp=e)}get audioTimestamp(){return this._audioTimestamp}get isDebug(){return Ee(this._opt.debug)}isDestroyed(){return this._destroyed}updateOption(e){this._opt=Object.assign({},this._opt,e)}init(){return new Promise(((e,t)=>{this.audio||(this.audio=new Ke(this)),this.stream||(this.stream=new Le(this)),this.decoderWorker?this.loaded?e():this.once(F.decoderWorkerInit,(()=>{this.loaded=!0,e()})):(this.decoderWorker=new st(this),this.once(F.decoderWorkerInit,(()=>{this.loaded=!0,e()})))}))}play(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";return new Promise(((t,s)=>{if(!e&&!this._opt.url)return s("url is empty");this.loading=!0,this.playing=!1,this._closed=!1,this._times.playInitStart=he(),e||(e=this._opt.url),this._opt.url=e,this.clearCheckHeartTimeout(),this.init().then((()=>{this._times.playStart=he(),this._opt.isNotMute&&this.mute(!1),this.enableWakeLock(),this.checkLoadingTimeout(),this.stream&&(this.stream.once(z.fetchError,(e=>{this.emitError(z.fetchError,e)})),this.stream.once(z.websocketError,(e=>{this.emitError(z.websocketError,e)})),this.stream.once(F.streamEnd,(e=>{this.emit(F.streamEnd,e)})),this.stream.once(F.streamSuccess,(()=>{t(),this._times.streamResponse=he(),this.checkStatsInterval(),this.debug.log(this.TAG_NAME,"stream success and start play")})),this.stream.fetchStream(e))})).catch((()=>{s()}))}))}checkLoadingTimeout(){this._checkLoadingTimeout=setTimeout((()=>{this.playing?this.debug.warn(this.TAG_NAME,`checkLoadingTimeout but loading is ${this.loading} and playing is ${this.playing}`):this.isDestroyed()?this.debug&&this.debug.warn(this.TAG_NAME,"checkLoadingTimeout but player is destroyed"):(this.debug.warn(this.TAG_NAME,"checkLoadingTimeout and pause and emit loadingTimeout event"),this.emit(F.timeout,F.loadingTimeout),this.emit(F.loadingTimeout))}),1e3*this._opt.loadingTimeout)}clearCheckLoadingTimeout(){this._checkLoadingTimeout&&(this.debug.log(this.TAG_NAME,"clearCheckLoadingTimeout"),clearTimeout(this._checkLoadingTimeout),this._checkLoadingTimeout=null)}checkStatsInterval(){this.debug.log(this.TAG_NAME,"checkStatsInterval"),this._checkStatsInterval=setInterval((()=>{this.updateStats()}),1e3)}clearCheckHeartTimeout(){this.debug.log(this.TAG_NAME,"clearCheckHeartTimeout"),this._checkHeartTimeout&&(clearTimeout(this._checkHeartTimeout),this._checkHeartTimeout=null)}clearStatsInterval(){this.debug.log(this.TAG_NAME,"clearStatsInterval"),this._checkStatsInterval&&(clearInterval(this._checkStatsInterval),this._checkStatsInterval=null)}updateStats(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this._startBpsTime||(this._startBpsTime=he()),ge(e.ts)&&(this._stats.ts=e.ts,null===this._playingStartTimestamp&&e.ts>0&&(this._playingStartTimestamp=e.ts)),ge(e.buf)&&(this._stats.buf=e.buf);const t=he(),s=t-this._startBpsTime;if(e.abps&&(this._stats.abps+=e.abps),s<1e3)return;let i=0,A=0;this.audio&&this.audio.bufferList&&(i=this.audio.bufferList.length,A=i*this.audio.oneBufferDuration),this._stats.audioBufferTs=parseInt(A,10),this.emit(F.stats,this._stats),this.emit(F.timeUpdate,this._stats.ts),this.updateHistoryAbpsList(this._stats.abps),this._stats.abps=0,this._startBpsTime=t}enableWakeLock(){this._opt.keepScreenOn&&this.keepScreenOn&&this.keepScreenOn.enable()}releaseWakeLock(){this._opt.keepScreenOn&&this.keepScreenOn&&this.keepScreenOn.disable()}pause(){return new Promise(((e,t)=>{this._closed=!0;const s=()=>{this.stream&&(this.stream.destroy(),this.stream=null),this.off(),this.clearCheckHeartTimeout(),this.clearCheckLoadingTimeout(),this.clearStatsInterval(),this.releaseWakeLock(),this._resetStats(),this.loading=!1,this.playing=!1,this.audio&&this.audio.pause(),this._audioTimestamp=0,this._hasLoaded=!1,this._times={playInitStart:"",playStart:"",streamStart:"",streamResponse:"",demuxStart:"",decodeStart:"",videoStart:"",playTimestamp:"",streamTimestamp:"",streamResponseTimestamp:"",demuxTimestamp:"",decodeTimestamp:"",videoTimestamp:"",allTimestamp:""},Te(this)};this.decoderWorker?this.decoderWorker.destroy().then((()=>{this.decoderWorker=null,s(),e()})).catch((e=>{this.debug.error(this.TAG_NAME,"pause() decoderWorker destroy error",e),t(e)})):(s(),setTimeout((()=>{e()}),0))}))}handleRender(){this.isDestroyed()?this.debug&&this.debug.warn("player","handleRender but player is destroyed"):(this.loading&&(this.clearCheckLoadingTimeout(),this.emit(F.start),this.loading=!1),this.playing||(this.playing=!0))}updateHistoryAbpsList(e){this._historyAbpsList.length>this._opt.heartTimeout&&this._historyAbpsList.shift(),this._historyAbpsList.push(e),this.isHistoryAbpsListAllZero()&&this.checkHeartTimeout$2()}isHistoryAbpsListAllZero(){let e=!0;if(this._historyAbpsList.length<this._opt.heartTimeout&&(e=!1),e)for(let t=0;t<this._historyAbpsList.length;t++)if(this._historyAbpsList[t]>0){e=!1;break}return e}checkHeartTimeout$2(){if(this.playing){if(this.isDestroyed())return void(this.debug&&this.debug.warn("player","checkHeartTimeout$2 but player is destroyed"));if(Se(this.isHistoryAbpsListAllZero()))return void(this.debug&&this.debug.warn("player","checkHeartTimeout$2 but fps is not all zero"));if(Se(this.visibility)&&0!==this._stats.abps)return void(this.debug&&this.debug.warn("player",`checkHeartTimeout$2 but page is not visibility and vbps is ${this._stats.vbps}`));const e=this._historyAbpsList.join(",");this.debug.warn("player",`checkHeartTimeout$2 and\n pause and emit delayTimeout event and\n current abps is ${this._stats.abps} and\n history abpsList is ${e} and\n current visibility is ${this.visibility} and`),this.emit(F.timeout,F.delayTimeout),this.emit(F.delayTimeout)}else this.debug.log("player",`checkHeartTimeout$2() playing is ${this.playing}`)}getOption(){return this._opt}getDemuxType(){let e="";return e=this.getOption().demuxType,e}getAudioEngineType(){let e="";return this.audio&&(e=this.audio.getEngineType()),e}mute(e){this.audio&&this.audio.mute(e)}isAudioMute(){let e=!0;return this.audio&&(e=this.audio.isMute),e}isAudioNotMute(){return!this.isAudioMute()}getPlayType(){return this._opt.playType}emitError(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";this.emit(e,t),this.emit(F.error,e,t)}openSyncAudioAndVideo(){return!1}isDestroyedOrClosed(){return this.isDestroyed()||this.isClosed()}isClosed(){return this._closed}}class At extends t{constructor(e){super(),this._opt={},this.TAG_NAME="JbProAudio",Object.keys(e).forEach((t=>{if(void 0===e[t])throw new Error(`JbPro option "${t}" can not be undefined`)}));const t=we();let s=Object.assign({},t,e);ge(s.videoBuffer)&&(s.videoBuffer=1e3*Number(s.videoBuffer)),ge(s.videoBufferDelay)&&(s.videoBufferDelay=1e3*Number(s.videoBufferDelay)),ge(s.videoBufferMax)&&(s.videoBufferMax=1e3*Number(s.videoBufferMax)),ge(s.timeout)&&(pe(s.loadingTimeout)&&(s.loadingTimeout=s.timeout),pe(s.heartTimeout)&&(s.heartTimeout=s.timeout)),this._opt=s,this._destroyed=!1,this._loadingTimeoutReplayTimes=0,this._heartTimeoutReplayTimes=0,this.debug=new ae(this),this.events=new ke(this),this._initAudioPlayer(),this.debug.log(this.TAG_NAME,'init success and version is "3-5-2024"'),console.log('JbProAudio version is "3-5-2024"')}destroy(){return new Promise(((e,t)=>{this.debug.log(this.TAG_NAME,"destroy()"),this._destroyed=!0,this.off(),this.player?this.player.destroy().then((()=>{this.player=null,this._destroy(),e()})).catch((()=>{t()})):(this._destroy(),e())}))}_destroy(){this.events&&(this.events.destroy(),this.events=null),this.debug&&this.debug.log("JbPro","destroy end"),this._resetOpt(),this._loadingTimeoutReplayTimes=0,this._heartTimeoutReplayTimes=0}_initAudioPlayer(){this.player=new it(this._opt),this.debug.log(this.TAG_NAME,"_initPlayer",this.player.getOption()),this._bindEvents()}_resetOpt(){this._opt=we()}_bindEvents(){Object.keys(Y).forEach((e=>{this.player.on(Y[e],(t=>{this.emit(e,t)}))}))}_play(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";return new Promise(((A,r)=>{const o=0===t.indexOf("http"),a=-1!==t.indexOf(".flv");let h=null,l=null;if(h=o?i:s,a&&!this._opt.isFlv&&(this._opt.isFlv=!0),l=this._opt.isFlv?b:B,!h||!l)return r(`play protocol is ${h}, demuxType is ${l}`);this.debug.log(this.TAG_NAME,`play protocol is ${n[h]}, demuxType is ${l}`),this.player.updateOption({protocol:h,demuxType:l,isFlv:this._opt.isFlv}),this.player.once(z.fetchError,(e=>{this.emit(F.crashLog,this._getCrashLog(z.fetchError,e)),this.debug.log(this.TAG_NAME,"fetch error and reset player"),this.pause().then((()=>{this.emit(F.playFailedAndPaused,z.fetchError)})).catch((e=>{this.debug.error(this.TAG_NAME,"fetch error and pause",e)}))})),this.player.once(F.streamEnd,(e=>{this.emit(F.crashLog,this._getCrashLog(F.streamEnd,e)),this.debug.log(this.TAG_NAME,"streamEnd and reset player"),this.pause().then((()=>{this.emit(F.playFailedAndPaused,F.streamEnd)})).catch((e=>{this.debug.error(this.TAG_NAME,"streamEnd and pause",e)}))})),this.player.once(z.websocketError,(e=>{this.emit(F.crashLog,this._getCrashLog(z.websocketError,e)),this.debug.log(this.TAG_NAME,"websocketError and reset player"),this.pause().then((()=>{this.emit(F.playFailedAndPaused,z.websocketError)})).catch((e=>{this.debug.error(this.TAG_NAME,"websocketError and pause",e)}))})),this.player.on(F.delayTimeout,(e=>{this.emit(F.crashLog,this._getCrashLog(F.delayTimeout,e)),this.isDestroyed()?this.debug.log(this.TAG_NAME,"delay timeout but player is destroyed"):this.pause().then((()=>{if(this.player&&this.player._opt.heartTimeoutReplay&&(this._heartTimeoutReplayTimes<this.player._opt.heartTimeoutReplayTimes||-1===this.player._opt.heartTimeoutReplayTimes)){if(this.debug.log(this.TAG_NAME,`delay timeout and\n replay time is ${this._heartTimeoutReplayTimes} and\n heartTimeoutReplayTimes is ${this.player._opt.heartTimeoutReplayTimes}`),this.isDestroyed())return void(this.debug&&this.debug.warn(this.TAG_NAME,"delay timeout replay but player is destroyed"));this._heartTimeoutReplayTimes+=1;const e=this._opt.url;this.play(e).then((()=>{})).catch((e=>{this.debug.error(this.TAG_NAME,"delay timeout replay error",e)}))}else this.emit(F.playFailedAndPaused,F.delayTimeout),this.emit(F.delayTimeoutRetryEnd),this.debug.warn(this.TAG_NAME,`delayTimeoutRetryEnd and\n opt.heartTimeout is ${this.player&&this.player._opt.heartTimeout} and\n opt.heartTimeoutReplay is ${this.player&&this.player._opt.heartTimeoutReplay} and\n opt.heartTimeoutReplayTimes is ${this.player&&this.player._opt.heartTimeoutReplayTimes},and\n local._heartTimeoutReplayTimes is ${this._heartTimeoutReplayTimes}`)})).catch((e=>{this.debug.error(this.TAG_NAME,"delay timeout and pause error",e)}))})),this.player.on(F.loadingTimeout,(t=>{this.emit(F.crashLog,this._getCrashLog(F.loadingTimeout,t)),this.isDestroyed()?this.debug.log(this.TAG_NAME,"loading timeout but player is destroyed"):this.pause().then((()=>{if(this.player&&this.player._opt.loadingTimeoutReplay&&(this._loadingTimeoutReplayTimes<this.player._opt.loadingTimeoutReplayTimes||-1===this.player._opt.loadingTimeoutReplayTimes)){if(this.debug.log(this.TAG_NAME,`loading timeout and\n replay time is ${this._loadingTimeoutReplayTimes} and\n loadingTimeoutReplayTimes is ${this.player._opt.loadingTimeoutReplayTimes}`),this.isDestroyed())return void(this.debug&&this.debug.warn(this.TAG_NAME,"loading timeout replay but player is destroyed"));this._loadingTimeoutReplayTimes+=1;const t=this._opt.url;this.play(t).then((()=>{})).catch((()=>{this.debug.error(this.TAG_NAME,"loading timeout replay error",e)}))}else this.emit(F.loadingTimeoutRetryEnd),this.emit(F.playFailedAndPaused,F.loadingTimeoutRetryEnd)})).catch((e=>{this.debug.error(this.TAG_NAME,"loading timeout and pause error",e)}))})),this.player.play(t).then((()=>{A()})).catch((e=>{this.debug.error(this.TAG_NAME,"hasLoaded and play error",e),this.emit(F.crashLog,this._getCrashLog("hasLoaded and play error",e)),this.player.pause().then((()=>{r(e)})).catch((e=>{this.debug.error(this.TAG_NAME,"hasLoaded and play error and next pause error",e)}))}))}))}isDestroyed(){return this._destroyed}play(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";return new Promise(((t,s)=>(this.debug.log(this.TAG_NAME,`play() ${e}`),e||this._opt.url?(e&&(e=(""+e).trim(),this._opt.url=e),this.player?void(this.player.playing||this.player.loading?(this.debug.warn(this.TAG_NAME,`play() and player is playing ${this.player.playing} or loading ${this.player.loading} and pause to play`),this.player.pause().then((()=>{this._play(this._opt.url).then((()=>{t()})).catch((e=>{s(e)}))}))):this._play(this._opt.url).then((()=>{t()})).catch((e=>{s(e)}))):s("player is null")):(this.emit(F.error,z.playError),void s("url is null and this._opt.url is null")))))}mute(){this.debug.log(this.TAG_NAME,"mute()"),this.player&&this.player.mute(!0)}cancelMute(){this.debug.log(this.TAG_NAME,"cancelMute()"),this.player&&this.player.mute(!1)}pause(){return new Promise(((e,t)=>{this.debug.log(this.TAG_NAME,"pause()"),this.player?this.player.pause().then((t=>{this._bindEvents(),e(t)})).catch((e=>{t(e)})):t("player is null")}))}setVolume(e){this.debug.log(this.TAG_NAME,`setVolume() ${e}`),this.player&&(this.player.volume=e)}getVolume(){let e=null;return this.player&&(e=this.player.volume,e=parseFloat(e).toFixed(2)),e}setTimeout(e){this.debug.log(this.TAG_NAME,`setTimeout() ${e}`),e=Number(e),this.player&&this.player.updateOption({timeout:e,loadingTimeout:e,heartTimeout:e})}audioResume(){this.debug.log(this.TAG_NAME,"audioResume()"),this.player&&this.player.audio?this.player.audio.audioEnabled(!0):this.debug.warn(this.TAG_NAME,"audioResume() player is not init")}setDebug(e){this.debug.log(this.TAG_NAME,`setDebug() ${e}`),this.player?this.player.updateOption({debug:!!e}):this.debug.warn(this.TAG_NAME,"setDebug() player is not init")}_getCrashLog(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";if(!this.player)return;const s=this.player;let i={url:this._opt.url,playType:f,demuxType:s.getDemuxType(),audioInfo:{encType:"",sampleRate:"",channels:""},audioEngine:s.getAudioEngineType(),timestamp:he(),type:e,error:Ce(t)||e};if(s.audio){const e=s.audio.audioInfo||{};i.audioInfo={encType:e.encType||"",sampleRate:e.sampleRate||"",channels:e.channels||""}}return i}}return window.JessibucaProAudio=At,window.JbProAudio=At,window.WebPlayerProAudio=At,At}));
|