1 |
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e(require("screenfull")):"function"==typeof define&&define.amd?define(["screenfull"],e):(t="undefined"!=typeof globalThis?globalThis:t||self)["jessibuca-pro-recorder"]=e()}(this,(function(){"use strict";class t{on(t,e,i){const s=this.e||(this.e={});return(s[t]||(s[t]=[])).push({fn:e,ctx:i}),this}once(t,e,i){const s=this;function r(){s.off(t,r);for(var a=arguments.length,n=new Array(a),o=0;o<a;o++)n[o]=arguments[o];e.apply(i,n)}return r._=e,this.on(t,r,i)}emit(t){const e=((this.e||(this.e={}))[t]||[]).slice();for(var i=arguments.length,s=new Array(i>1?i-1:0),r=1;r<i;r++)s[r-1]=arguments[r];for(let t=0;t<e.length;t+=1)e[t].fn.apply(e[t].ctx,s);return this}off(t,e){const i=this.e||(this.e={});if(!t)return Object.keys(i).forEach((t=>{delete i[t]})),void delete this.e;const s=i[t],r=[];if(s&&e)for(let t=0,i=s.length;t<i;t+=1)s[t].fn!==e&&s[t].fn._!==e&&r.push(s[t]);return r.length?i[t]=r:delete i[t],this}}const e=1,i=2,s=3,r=5,a="fetch",n="hls",o="websocket",h="webTransport",l={mp4:"mp4",webm:"webm",flv:"flv"},d="flv",u="m7s",p="hls",c="webTransport",f="nakedFlow",_="fmp4",m="debug",g="warn",y=1,b=2,S=8,v=9,w=18,x="fetch",U="destroy",A="buffer",T="fetchError",E="fetchClose",B="fetchSuccess",k={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",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",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",playFailedAndPaused:"playFailedAndPaused",audioResumeState:"audioResumeState",webrtcStreamH265:"webrtcStreamH265",flvMetaData:"flvMetaData",talkFailedAndStop:"talkFailedAndStop",removeLoadingBgImage:"removeLoadingBgImage",memoryLog:"memoryLog",downloadMemoryLog:"downloadMemoryLog",pressureObserverCpu:"pressureObserverCpu"},L={playError:"playIsNotPauseOrUrlIsNull",fetchError:"fetchError",websocketError:"websocketError",webcodecsH265NotSupport:"webcodecsH265NotSupport",webcodecsDecodeError:"webcodecsDecodeError",webcodecsUnsupportedConfigurationError:"webcodecsUnsupportedConfigurationError",mediaSourceH265NotSupport:"mediaSourceH265NotSupport",mediaSourceDecoderConfigurationError:"mediaSourceDecoderConfigurationError",mediaSourceFull:k.mseSourceBufferFull,mseSourceBufferError:k.mseSourceBufferError,mseAddSourceBufferError:k.mseAddSourceBufferError,mediaSourceAppendBufferError:"mediaSourceAppendBufferError",mediaSourceBufferListLarge:"mediaSourceBufferListLarge",mediaSourceAppendBufferEndTimeout:"mediaSourceAppendBufferEndTimeout",mediaSourceTsIsMaxDiff:"mediaSourceTsIsMaxDiff",mediaSourceUseCanvasRenderPlayFailed:"mediaSourceUseCanvasRenderPlayFailed",wasmDecodeError:"wasmDecodeError",wasmUseVideoRenderError:"wasmUseVideoRenderError",hlsError:"hlsError",hlsV2Mp4NotSupport:"hlsV2Mp4NotSupport",webrtcError:"webrtcError",webrtcClosed:k.webrtcClosed,webrtcIceCandidateError:"webrtcIceCandidateError",webglAlignmentError:"webglAlignmentError",wasmWidthOrHeightChange:"wasmWidthOrHeightChange",mseWidthOrHeightChange:"mseWidthOrHeightChange",wcsWidthOrHeightChange:"wcsWidthOrHeightChange",widthOrHeightChange:"widthOrHeightChange",tallWebsocketClosedByError:"tallWebsocketClosedByError",flvDemuxBufferSizeTooLarge:k.flvDemuxBufferSizeTooLarge,wasmDecodeVideoNoResponseError:"wasmDecodeVideoNoResponseError",audioChannelError:"audioChannelError",simdH264DecodeVideoWidthIsTooLarge:"simdH264DecodeVideoWidthIsTooLarge",simdDecodeError:"simdDecodeError",webglContextLostError:"webglContextLostError",videoElementPlayingFailed:"videoElementPlayingFailed",videoElementPlayingFailedForWebrtc:"videoElementPlayingFailedForWebrtc",decoderWorkerInitError:"decoderWorkerInitError",videoInfoError:"videoInfoError",videoCodecIdError:"videoCodecIdError",streamEnd:k.streamEnd,delayTimeout:k.delayTimeout,loadingTimeout:k.loadingTimeout,networkDelayTimeout:k.networkDelayTimeout},I="notConnect",C="open",D="close",P="error",F="download",R="blob",N={7:"H264(AVC)",12:"H265(HEVC)",99:"MPEG4"},M=7,z=12,G="H264(AVC)",O="H265(HEVC)",H={AAC:10,ALAW:7,MULAW:8,MP3:2},V="AAC",W="ALAW(g711a)",Y="MULAW(g711u)",$={10:"AAC",7:"ALAW",8:"MULAW",2:"MP3"},j={sps:7,pps:8,iFrame:5,kUnspecified:0,kSliceNonIDR:1,kSliceDPA:2,kSliceDPB:3,kSliceDPC:4,kSliceIDR:5,kSliceSEI:6,kSliceSPS:7,kSlicePPS:8,kSliceAUD:9,kEndOfSequence:10,kEndOfStream:11,kFiller:12,kSPSExt:13,kReserved0:14},q=32,K=33,X=34,J=39,Z="hevc",Q=0,tt=1,et=1,it=2,st=0,rt=1,at="subtitle-segments",nt="hls-manifest-loaded",ot="hls-level-loaded",ht="demuxed-track",lt="flv-script-data",dt="metadata-parsed",ut="ttfb",pt="load-retry",ct="load-start",ft="speed",_t="load-complete",mt="load-response-headers",gt="sei",yt="sei-in-time",bt="switch-url-failed",St="switch-url-success",vt="subtitle-playlist",wt="stream-parsed",xt="error",Ut={protocol:i,demuxType:d,isFlv:!1,isHls:!1,isFmp4:!1,isNakedFlow:!1,recordType:l.mp4,wasmMp4RecorderDecoder:"jessibuca-pro-mp4-recorder-decoder.js",debug:!1,debugLevel:g,debugUuid:"",hasAudio:!0,hasVideo:!0};function At(t){let{profile:e,sampleRate:i,channel:s}=t;return new Uint8Array([175,0,e<<3|(14&i)>>1,(1&i)<<7|s<<3])}function Tt(t){return t[0]>>4===H.AAC}const Et=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Bt=Et;function kt(t,e){if("mp4a.40.2"===t){if(1===e)return new Uint8Array([0,200,0,128,35,128]);if(2===e)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===e)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===e)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===e)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}}function Lt(t){return 1024*(arguments.length>1&&void 0!==arguments[1]?arguments[1]:9e4)/t}class It{constructor(t){this.buffer=t,this.buflen=t.length,this.bufpos=0,this.bufoff=0,this.iserro=!1}read(t){let e=0,i=0;for(;t;){if(t<0||this.bufpos>=this.buflen)return this.iserro=!0,0;this.iserro=!1,i=this.bufoff+t>8?8-this.bufoff:t,e<<=i,e+=this.buffer[this.bufpos]>>8-this.bufoff-i&255>>8-i,this.bufoff+=i,t-=i,8==this.bufoff&&(this.bufpos++,this.bufoff=0)}return e}look(t){let e=this.bufpos,i=this.bufoff,s=this.read(t);return this.bufpos=e,this.bufoff=i,s}read_golomb(){let t;for(t=0;0==this.read(1)&&!this.iserro;t++);return(1<<t)+this.read(t)-1}}function Ct(t){let e=t.read(5);return 31===e&&(e=t.read(6)+32),e}function Dt(t,e){return e.sampling_index=t.read(4),15==e.sampling_index?t.read(24):Pt[e.sampling_index]}const Pt=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350,0,0,0],Ft=[0,1,2,3,4,5,6,8];function Rt(){return(new Date).getTime()}function Nt(){return performance&&"function"==typeof performance.now?performance.now():Date.now()}function Mt(t){let e=0,i=Nt();return s=>{if(!function(t){const e=Object.prototype.toString;return"[object Number]"===e.call(t)}(s))return;e+=s;const r=Nt(),a=r-i;a>=1e3&&(t(e/a*1e3),i=r,e=0)}}(()=>{try{if("object"==typeof WebAssembly&&"function"==typeof WebAssembly.instantiate){const t=new WebAssembly.Module(Uint8Array.of(0,97,115,109,1,0,0,0));if(t instanceof WebAssembly.Module)return new WebAssembly.Instance(t)instanceof WebAssembly.Instance}}catch(t){}})();const zt='"10-30-2023"';function Gt(){const t=window.navigator.userAgent;return!t.match(/Chrome/gi)&&!!t.match(/Safari/gi)}function Ot(t){if(null==t||""==t)return"0 Bytes";const e=new Array("Bytes","KB","MB","GB","TB","PB","EB","ZB","YB");let i=0;const s=parseFloat(t);i=Math.floor(Math.log(s)/Math.log(1024));var r=s/Math.pow(1024,i);return(r=r.toFixed(2))+e[i]}function Ht(t,e){let i=window.URL.createObjectURL(e),s=window.document.createElement("a");s.download=t,s.href=i;let r=window.document.createEvent("MouseEvents");r.initEvent("click",!0,!0),s.dispatchEvent(r),setTimeout((()=>{window.URL.revokeObjectURL(i)}),function(){const t=window.navigator.userAgent.toLowerCase();return t&&/iphone|ipad|ipod|ios/.test(t)}()?1e3:0)}function Vt(t){return null==t}function Wt(t){return!Vt(t)}function Yt(t){var e;if(t>-1){var i=Math.floor(t/3600),s=Math.floor(t/60)%60,r=t%60;e=i<10?"0"+i+":":i+":",s<10&&(e+="0"),e+=s+":",(r=Math.round(r))<10&&(e+="0"),e+=r.toFixed(0)}return e}const $t=()=>{const t=window.navigator.userAgent;return/Chrome/i.test(t)};function jt(){return function(t){let e="";if("object"==typeof t)try{e=JSON.stringify(t),e=JSON.parse(e)}catch(i){e=t}else e=t;return e}(Ut)}function qt(t){return!0===t||"true"===t}function Kt(t){return!0!==t&&"true"!==t}function Xt(t){return t.trim().match(/^function\s*\w*\s*\([\w\s,]*\)\s*{([\w\W]*?)}$/)[1]}class Jt{constructor(t){this.log=function(e){if(t._opt.debug&&t._opt.debugLevel==m){const a=t._opt.debugUuid?`[${t._opt.debugUuid}]`:"";for(var i=arguments.length,s=new Array(i>1?i-1:0),r=1;r<i;r++)s[r-1]=arguments[r];console.log(`JbProRecorder${a}[✅✅✅][${e}]`,...s)}},this.warn=function(e){if(t._opt.debug&&(t._opt.debugLevel==m||t._opt.debugLevel==g)){const a=t._opt.debugUuid?`[${t._opt.debugUuid}]`:"";for(var i=arguments.length,s=new Array(i>1?i-1:0),r=1;r<i;r++)s[r-1]=arguments[r];console.log(`JbProRecorder${a}[❗❗❗][${e}]`,...s)}},this.error=function(e){const i=t._opt.debugUuid?`[${t._opt.debugUuid}]`:"";for(var s=arguments.length,r=new Array(s>1?s-1:0),a=1;a<s;a++)r[a-1]=arguments[a];console.error(`JbProRecorder${i}[❌❌❌][${e}]`,...r)}}}class Zt{constructor(t){this.destroys=[],this.proxy=this.proxy.bind(this),this.master=t}proxy(t,e,i){let s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};if(!t)return;if(Array.isArray(e))return e.map((e=>this.proxy(t,e,i,s)));t.addEventListener(e,i,s);const r=()=>{"function"==typeof t.removeEventListener&&t.removeEventListener(e,i,s)};return this.destroys.push(r),r}destroy(){this.master.debug&&this.master.debug.log("Events","destroy"),this.destroys.forEach((t=>t())),this.destroys=[]}}class Qt{constructor(t){this.player=t,this.videoInfo={width:null,height:null,encType:null,encTypeCode:null},this.init=!1}destroy(){this.isDestroyed=!0,this.resetInit()}resetInit(){this.videoInfo={width:null,height:null,encType:null,encTypeCode:null},this.init=!1}updateVideoInfo(t){Wt(t.encTypeCode)&&(this.videoInfo.encType=N[t.encTypeCode],this.videoInfo.encTypeCode=t.encTypeCode),Wt(t.encType)&&(this.videoInfo.encType=t.encType),Wt(t.width)&&(this.videoInfo.width=t.width),Wt(t.height)&&(this.videoInfo.height=t.height),Wt(this.videoInfo.encType)&&Wt(this.videoInfo.height)&&Wt(this.videoInfo.width)&&!this.init&&(this.player.emit(k.videoInfo,this.videoInfo),this.init=!0)}hasInit(){return this.init}getVideoInfo(){return this.videoInfo}}class te{constructor(t){this.player=t,this.audioInfo={encType:"",channels:"",sampleRate:"",depth:""},this.init=!1}destroy(){this.isDestroyed=!0,this.resetInit()}resetInit(){this.audioInfo={encType:"",channels:"",sampleRate:"",depth:""},this.init=!1}updateAudioInfo(t){t.encTypeCode&&(this.audioInfo.encTypeCode=t.encTypeCode,this.audioInfo.encType=$[t.encTypeCode]),t.channels&&(this.audioInfo.channels=t.channels),t.sampleRate&&(this.audioInfo.sampleRate=t.sampleRate),t.depth&&(this.audioInfo.depth=t.depth),Wt(this.audioInfo.sampleRate)&&Wt(this.audioInfo.channels)&&Wt(this.audioInfo.encType)&&!this.init&&(this.player.emit(k.audioInfo,this.audioInfo),this.init=!0)}hasInit(){return this.init}getAudioInfo(){return this.audioInfo}}function ee(){function t(t){return!0===t||"true"===t}function e(t){return!1===t||"false"===t}const i="The user aborted a request",s="AbortError",r="AbortError",a="fetch",n="destroy",o="buffer",h="fetchError",l="fetchClose",d="fetchSuccess",u="idle",p="buffering",c="complete";let f=new class{constructor(){this._requestAbort=!1,this._status=u,this.writableStream=null,this.isChrome=!1,this.abortController=new AbortController}destroy(){this.abort(),this.writableStream&&e(this.writableStream.locked)&&this.writableStream.close().catch((t=>{})),this.writableStream=null,this._status=u}fetchStream(e){let a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const n=Object.assign({signal:this.abortController.signal},{headers:a.headers||{}});fetch(e,n).then((e=>{if(this._requestAbort)return this._status=u,void e.body.cancel();if(!function(t){return t.ok&&t.status>=200&&t.status<=299}(e))return this.abort(),void postMessage({cmd:h,message:`fetch response status is ${e.status} and ok is ${e.ok}`});if(postMessage({cmd:d}),"undefined"!=typeof WritableStream)this.writableStream=new WritableStream({write:e=>{this.abortController&&this.abortController.signal&&this.abortController.signal.aborted||t(this._requestAbort)?this._status=c:(this._status=p,postMessage({cmd:o,buffer:e},[e.buffer]))},close:()=>{this._status=c,postMessage({cmd:l})},abort:t=>{if(this.abortController&&this.abortController.signal&&this.abortController.signal.aborted)return void(this._status=c);const e=t.toString();-1===e.indexOf(i)&&-1===e.indexOf(s)&&t.name!==r&&(this.abort(),postMessage({cmd:h,message:t.toString()}))}}),e.body.pipeTo(this.writableStream);else{const a=e.body.getReader(),n=()=>{a.read().then((e=>{let{done:i,value:s}=e;if(i)return this._status=c,void postMessage({cmd:l});this.abortController&&this.abortController.signal&&this.abortController.signal.aborted||t(this._requestAbort)?this._status=c:(this._status=p,postMessage({cmd:o,buffer:s},[s.buffer]),n())})).catch((t=>{if(this.abortController&&this.abortController.signal&&this.abortController.signal.aborted)return void(this._status=c);const e=t.toString();-1===e.indexOf(i)&&-1===e.indexOf(s)&&t.name!==r&&(this.abort(),postMessage({cmd:h,message:t.toString()}))}))};n()}})).catch((t=>{this.abortController&&this.abortController.signal&&this.abortController.signal.aborted||"AbortError"!==t.name&&(this.abort(),postMessage({cmd:h,message:t.toString()}))}))}abort(){if(this._requestAbort=!0,this._status!==p||e(f.isChrome)){if(this.abortController){try{this.abortController.abort()}catch(t){}this.abortController=null}}else this.abortController=null}};self.onmessage=e=>{const i=e.data;switch(i.cmd){case a:f.isChrome=t(i.isChrome),f.fetchStream(i.url,JSON.parse(i.options));break;case n:f.destroy(),f=null}}}class ie extends t{constructor(t){super(),this.TAG_NAME="FetchWorkerLoader",this.player=t,this.playing=!1,this.fetchWorker=null,this.workerClearTimeout=null,this.workerUrl=null,this.abortController=new AbortController,this.streamRate=Mt((e=>{t.emit(k.kBps,(e/1024).toFixed(2))})),this.streamRateInterval=null,this._initFetchWorker(),t.debug.log(this.TAG_NAME,"init")}destroy(){this.off(),this.workerUrl&&(window.URL.revokeObjectURL(this.workerUrl),this.workerUrl=null),this.workerClearTimeout&&(clearTimeout(this.workerClearTimeout),this.workerClearTimeout=null),this.fetchWorker&&(this.fetchWorker.postMessage({cmd:U}),this.fetchWorker.terminate(),this.fetchWorker=null),this._stopStreamRateInterval(),this.streamRate=null,this.player.debug.log(this.TAG_NAME,"destroy")}_initFetchWorker(){const t=Xt(ee.toString()),e=new Blob([t],{type:"text/javascript"});let i=URL.createObjectURL(e);const s=new Worker(i);this.workerUrl=i,this.workerClearTimeout=setTimeout((()=>{window.URL.revokeObjectURL(this.workerUrl),this.workerUrl=null,this.workerClearTimeout=null}),1e4),s.onmessage=t=>{const{demux:e}=this.player,i=t.data;switch(i.cmd){case A:this.streamRate&&this.streamRate(i.buffer.byteLength),e.dispatch(i.buffer);break;case B:this.emit(k.streamSuccess),this._startStreamRateInterval();break;case E:e.close(),this.emit(k.streamEnd);break;case T:e.close(),this.emit(L.fetchError,i.message)}},this.fetchWorker=s}_startStreamRateInterval(){this._stopStreamRateInterval(),this.streamRateInterval=setInterval((()=>{this.streamRate&&this.streamRate(0)}),1e3)}_stopStreamRateInterval(){this.streamRateInterval&&(clearInterval(this.streamRateInterval),this.streamRateInterval=null)}fetchStream(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.fetchWorker.postMessage({cmd:x,url:t,isChrome:$t(),options:JSON.stringify(e)})}getStreamType(){return a}}class se extends t{constructor(t){super(),this.player=t,this.socket=null,this.socketStatus=I,this.wsUrl=null,this.requestAbort=!1,this.socketDestroyFnList=[],this.streamRate=Mt((e=>{t.emit(k.kBps,(e/1024).toFixed(2))})),this.streamRateInterval=null,t.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 t=this.player,{debug:e,events:{proxy:i},demux:s}=t;this.socket=new WebSocket(this.wsUrl),this.socket.binaryType="arraybuffer";const r=i(this.socket,"open",(()=>{e.log("WebsocketStream","socket open"),this.socketStatus=C,this.emit(k.streamSuccess),this.player.emit(k.websocketOpen),this.startStreamRateInterval()})),a=i(this.socket,"message",(t=>{this.streamRate&&this.streamRate(t.data.byteLength),this._handleMessage(t.data)})),n=i(this.socket,"close",(t=>{if(e.log("WebsocketStream",`socket close and code is ${t.code}`),1006===t.code&&e.error("WebsocketStream",`socket close abnormally and code is ${t.code}`),qt(this.requestAbort))return this.requestAbort=!1,void e.log("WebsocketStream","socket close and requestAbort is true");s.close(),this.socketStatus=D,this.player.emit(k.websocketClose),this.emit(k.streamEnd)})),o=i(this.socket,"error",(t=>{e.error("WebsocketStream","socket error",t),this.socketStatus=P,this.emit(L.websocketError,t),s.close(),e.log("WebsocketStream","socket error:",t.isTrusted?"websocket user aborted":"websocket error")}));this.socketDestroyFnList.push(r,a,n,o)}_closeWebSocket(){this.socketDestroyFnList.forEach((t=>t())),!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=I,this.streamRate=null}_handleMessage(t){const{demux:e}=this.player;e?e.dispatch(t):this.player.debug.warn("WebsocketStream","websocket handle message demux is null")}fetchStream(t,e){this.wsUrl=t,this._createWebSocket()}sendMessage(t){this.socket?this.socketStatus===C?this.socket.send(t):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 o}}class re extends t{constructor(t){super(),this.player=t,this.transport=null,this.wtUrl=null,this.streamRate=Mt((e=>{t.emit(k.kBps,(e/1024).toFixed(2))})),this.streamRateInterval=null,t.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 t=this.player,{debug:e,events:{proxy:i},demux:s}=t;try{this.transport=new WebTransport(this.wtUrl),this.transport.ready.then((()=>{this.emit(k.streamSuccess),this.startStreamRateInterval(),this.transport.createBidirectionalStream().then((t=>{t.readable.pipeTo(new WritableStream(s.input))}))})).catch((t=>{this.player.debug.warn("WebTransportLoader","_createWebTransport-ready",t)}))}catch(t){this.player.debug.warn("WebTransportLoader","_createWebTransport",t)}}fetchStream(t){this.wtUrl=t.replace(/^wt:/,"https:"),this._createWebTransport()}abort(){if(this.transport)try{this.transport.close(),this.transport=null}catch(t){this.transport=null}}getStreamType(){return h}}class ae extends t{constructor(t){super(),this.player=t,t.debug.log("HlsStream","init")}destroy(){this.off(),this.player.debug.log("HlsStream","destroy")}fetchStream(t){const{hlsDecoder:e}=this.player;e.loadSource(t).then((()=>{this.player.debug.log("HlsStream","loadSource success"),this.emit(k.streamSuccess)})).catch((t=>{this.emit(L.hlsError,t)}))}getStreamType(){return n}}class ne{constructor(t){return new(ne.getLoaderFactory(t._opt))(t)}static getLoaderFactory(t){const{protocol:a}=t;return a===i?ie:a===e?se:a===s?ae:a===r?re:void 0}}class oe{constructor(t){this._buffer=t,this._buffer_index=0,this._total_bytes=t.byteLength,this._total_bits=8*t.byteLength,this._current_word=0,this._current_word_bits_left=0}destroy(){this._buffer=null}_fillCurrentWord(){let t=this._total_bytes-this._buffer_index;if(t<=0)return void console.error("ExpGolomb: _fillCurrentWord() but no bytes available",this._total_bytes,this._buffer_index);let e=Math.min(4,t),i=new Uint8Array(4);i.set(this._buffer.subarray(this._buffer_index,this._buffer_index+e)),this._current_word=new DataView(i.buffer).getUint32(0,!1),this._buffer_index+=e,this._current_word_bits_left=8*e}readBits(t){if(t>32&&console.error("ExpGolomb: readBits() bits exceeded max 32bits!"),t<=this._current_word_bits_left){let e=this._current_word>>>32-t;return this._current_word<<=t,this._current_word_bits_left-=t,e}let e=this._current_word_bits_left?this._current_word:0;e>>>=32-this._current_word_bits_left;let i=t-this._current_word_bits_left;this._fillCurrentWord();let s=Math.min(i,this._current_word_bits_left),r=this._current_word>>>32-s;return this._current_word<<=s,this._current_word_bits_left-=s,e=e<<s|r,e}readBool(){return 1===this.readBits(1)}readByte(){return this.readBits(8)}_skipLeadingZero(){let t;for(t=0;t<this._current_word_bits_left;t++)if(0!=(this._current_word&2147483648>>>t))return this._current_word<<=t,this._current_word_bits_left-=t,t;return this._fillCurrentWord(),t+this._skipLeadingZero()}readUEG(){let t=this._skipLeadingZero();return this.readBits(t+1)-1}readSEG(){let t=this.readUEG();return 1&t?t+1>>>1:-1*(t>>>1)}}class he{static _ebsp2rbsp(t){let e=t,i=e.byteLength,s=new Uint8Array(i),r=0;for(let t=0;t<i;t++)t>=2&&3===e[t]&&0===e[t-1]&&0===e[t-2]||(s[r]=e[t],r++);return new Uint8Array(s.buffer,0,r)}static parseSPS(t){let e=he._ebsp2rbsp(t),i=new oe(e);i.readByte();let s=i.readByte();i.readByte();let r=i.readByte();i.readUEG();let a=he.getProfileString(s),n=he.getLevelString(r),o=1,h=420,l=[0,420,422,444],d=8;if((100===s||110===s||122===s||244===s||44===s||83===s||86===s||118===s||128===s||138===s||144===s)&&(o=i.readUEG(),3===o&&i.readBits(1),o<=3&&(h=l[o]),d=i.readUEG()+8,i.readUEG(),i.readBits(1),i.readBool())){let t=3!==o?8:12;for(let e=0;e<t;e++)i.readBool()&&(e<6?he._skipScalingList(i,16):he._skipScalingList(i,64))}i.readUEG();let u=i.readUEG();if(0===u)i.readUEG();else if(1===u){i.readBits(1),i.readSEG(),i.readSEG();let t=i.readUEG();for(let e=0;e<t;e++)i.readSEG()}let p=i.readUEG();i.readBits(1);let c=i.readUEG(),f=i.readUEG(),_=i.readBits(1);0===_&&i.readBits(1),i.readBits(1);let m=0,g=0,y=0,b=0;i.readBool()&&(m=i.readUEG(),g=i.readUEG(),y=i.readUEG(),b=i.readUEG());let S=1,v=1,w=0,x=!0,U=0,A=0;if(i.readBool()){if(i.readBool()){let t=i.readByte();t>0&&t<16?(S=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][t-1],v=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][t-1]):255===t&&(S=i.readByte()<<8|i.readByte(),v=i.readByte()<<8|i.readByte())}if(i.readBool()&&i.readBool(),i.readBool()&&(i.readBits(4),i.readBool()&&i.readBits(24)),i.readBool()&&(i.readUEG(),i.readUEG()),i.readBool()){let t=i.readBits(32),e=i.readBits(32);x=i.readBool(),U=e,A=2*t,w=U/A}}let T=1;1===S&&1===v||(T=S/v);let E=0,B=0;if(0===o)E=1,B=2-_;else{E=3===o?1:2,B=(1===o?2:1)*(2-_)}let k=16*(c+1),L=16*(f+1)*(2-_);k-=(m+g)*E,L-=(y+b)*B;let I=Math.ceil(k*T);return i.destroy(),i=null,{profile_string:a,level_string:n,bit_depth:d,ref_frames:p,chroma_format:h,chroma_format_string:he.getChromaFormatString(h),frame_rate:{fixed:x,fps:w,fps_den:A,fps_num:U},sar_ratio:{width:S,height:v},codec_size:{width:k,height:L},present_size:{width:I,height:L}}}static parseSPS$2(t){let e=t.subarray(1,4),i="avc1.";for(let t=0;t<3;t++){let s=e[t].toString(16);s.length<2&&(s="0"+s),i+=s}let s=he._ebsp2rbsp(t),r=new oe(s);r.readByte();let a=r.readByte();r.readByte();let n=r.readByte();r.readUEG();let o=he.getProfileString(a),h=he.getLevelString(n),l=1,d=420,u=[0,420,422,444],p=8,c=8;if((100===a||110===a||122===a||244===a||44===a||83===a||86===a||118===a||128===a||138===a||144===a)&&(l=r.readUEG(),3===l&&r.readBits(1),l<=3&&(d=u[l]),p=r.readUEG()+8,c=r.readUEG()+8,r.readBits(1),r.readBool())){let t=3!==l?8:12;for(let e=0;e<t;e++)r.readBool()&&(e<6?he._skipScalingList(r,16):he._skipScalingList(r,64))}r.readUEG();let f=r.readUEG();if(0===f)r.readUEG();else if(1===f){r.readBits(1),r.readSEG(),r.readSEG();let t=r.readUEG();for(let e=0;e<t;e++)r.readSEG()}let _=r.readUEG();r.readBits(1);let m=r.readUEG(),g=r.readUEG(),y=r.readBits(1);0===y&&r.readBits(1),r.readBits(1);let b=0,S=0,v=0,w=0;r.readBool()&&(b=r.readUEG(),S=r.readUEG(),v=r.readUEG(),w=r.readUEG());let x=1,U=1,A=0,T=!0,E=0,B=0;if(r.readBool()){if(r.readBool()){let t=r.readByte();t>0&&t<16?(x=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][t-1],U=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][t-1]):255===t&&(x=r.readByte()<<8|r.readByte(),U=r.readByte()<<8|r.readByte())}if(r.readBool()&&r.readBool(),r.readBool()&&(r.readBits(4),r.readBool()&&r.readBits(24)),r.readBool()&&(r.readUEG(),r.readUEG()),r.readBool()){let t=r.readBits(32),e=r.readBits(32);T=r.readBool(),E=e,B=2*t,A=E/B}}let k=1;1===x&&1===U||(k=x/U);let L=0,I=0;if(0===l)L=1,I=2-y;else{L=3===l?1:2,I=(1===l?2:1)*(2-y)}let C=16*(m+1),D=16*(g+1)*(2-y);C-=(b+S)*L,D-=(v+w)*I;let P=Math.ceil(C*k);return r.destroy(),r=null,{codec_mimetype:i,profile_idc:a,level_idc:n,profile_string:o,level_string:h,chroma_format_idc:l,bit_depth:p,bit_depth_luma:p,bit_depth_chroma:c,ref_frames:_,chroma_format:d,chroma_format_string:he.getChromaFormatString(d),frame_rate:{fixed:T,fps:A,fps_den:B,fps_num:E},sar_ratio:{width:x,height:U},codec_size:{width:C,height:D},present_size:{width:P,height:D}}}static _skipScalingList(t,e){let i=8,s=8,r=0;for(let a=0;a<e;a++)0!==s&&(r=t.readSEG(),s=(i+r+256)%256),i=0===s?i:s}static getProfileString(t){switch(t){case 66:return"Baseline";case 77:return"Main";case 88:return"Extended";case 100:return"High";case 110:return"High10";case 122:return"High422";case 244:return"High444";default:return"Unknown"}}static getLevelString(t){return(t/10).toFixed(1)}static getChromaFormatString(t){switch(t){case 420:return"4:2:0";case 422:return"4:2:2";case 444:return"4:4:4";default:return"Unknown"}}}class le{constructor(t){this.buffer=t,this.buflen=t.length,this.bufpos=0,this.bufoff=0,this.iserro=!1}read(t){let e=0,i=0;for(;t;){if(t<0||this.bufpos>=this.buflen)return this.iserro=!0,0;this.iserro=!1,i=this.bufoff+t>8?8-this.bufoff:t,e<<=i,e+=this.buffer[this.bufpos]>>8-this.bufoff-i&255>>8-i,this.bufoff+=i,t-=i,8==this.bufoff&&(this.bufpos++,this.bufoff=0)}return e}look(t){let e=this.bufpos,i=this.bufoff,s=this.read(t);return this.bufpos=e,this.bufoff=i,s}read_golomb(){let t;for(t=0;0===this.read(1)&&!this.iserro;t++);return(1<<t)+this.read(t)-1}}function de(t){let{sps:e,pps:i}=t,s=8+e.byteLength+1+2+i.byteLength,r=!1;const a=he.parseSPS$2(e);66!==e[3]&&77!==e[3]&&88!==e[3]&&(r=!0,s+=4);let n=new Uint8Array(s);n[0]=1,n[1]=e[1],n[2]=e[2],n[3]=e[3],n[4]=255,n[5]=225;let o=e.byteLength;n[6]=o>>>8,n[7]=255&o;let h=8;n.set(e,8),h+=o,n[h]=1;let l=i.byteLength;n[h+1]=l>>>8,n[h+2]=255&l,n.set(i,h+3),h+=3+l,r&&(n[h]=252|a.chroma_format_idc,n[h+1]=248|a.bit_depth_luma-8,n[h+2]=248|a.bit_depth_chroma-8,n[h+3]=0,h+=4);const d=[23,0,0,0,0],u=new Uint8Array(d.length+n.byteLength);return u.set(d,0),u.set(n,d.length),u}function ue(t,e){let i=[];i[0]=e?23:39,i[1]=1,i[2]=0,i[3]=0,i[4]=0;const s=new Uint8Array(i.length+t.byteLength);return s.set(i,0),s.set(t,i.length),s}function pe(t){return 31&t[0]}function ce(t){return t===j.kSliceSEI}function fe(t){return!function(t){return t===j.sps||t===j.pps}(t)&&!ce(t)}function _e(t){return t===j.iFrame}const me=t=>{let e=t,i=e.byteLength,s=new Uint8Array(i),r=0;for(let t=0;t<i;t++)t>=2&&3===e[t]&&0===e[t-1]&&0===e[t-2]||(s[r]=e[t],r++);return new Uint8Array(s.buffer,0,r)},ge=t=>{switch(t){case 0:return"4:0:0";case 1:return"4:2:0";case 2:return"4:2:2";case 3:return"4:4:4";default:return"Unknown"}};function ye(t){const e=t.byteLength,i=new Uint8Array(4);i[0]=e>>>24&255,i[1]=e>>>16&255,i[2]=e>>>8&255,i[3]=255&e;const s=new Uint8Array(e+4);return s.set(i,0),s.set(t,4),s}function be(t,e){let i={},s=t.length,r=[],a=new le(t);a.read(1),a.read(6),a.read(6),a.read(3);for(let t=2;t<s;t++)t+2<s&&3==a.look(24)?(r.push(a.read(8)),r.push(a.read(8)),t+=2,a.read(8)):r.push(a.read(8));let n=new Uint8Array(r),o=new le(n);if(i.sps_video_parameter_set_id=o.read(4),i.sps_max_sub_layers_minus1=o.read(3),i.sps_temporal_id_nesting_flag=o.read(1),i.profile_tier_level=function(t,e,i){let s={};s.profile_space=t.read(2),s.tier_flag=t.read(1),s.profile_idc=t.read(5),s.profile_compatibility_flags=t.read(32),s.general_progressive_source_flag=t.read(1),s.general_interlaced_source_flag=t.read(1),s.general_non_packed_constraint_flag=t.read(1),s.general_frame_only_constraint_flag=t.read(1),t.read(32),t.read(12),s.level_idc=t.read(8),s.sub_layer_profile_present_flag=[],s.sub_layer_level_present_flag=[];for(let e=0;e<i;e++)s.sub_layer_profile_present_flag[e]=t.read(1),s.sub_layer_level_present_flag[e]=t.read(1);if(i>0)for(let e=i;e<8;e++)t.read(2);s.sub_layer_profile_space=[],s.sub_layer_tier_flag=[],s.sub_layer_profile_idc=[],s.sub_layer_profile_compatibility_flag=[],s.sub_layer_progressive_source_flag=[],s.sub_layer_interlaced_source_flag=[],s.sub_layer_non_packed_constraint_flag=[],s.sub_layer_frame_only_constraint_flag=[],s.sub_layer_level_idc=[];for(let e=0;e<i;e++)s.sub_layer_profile_present_flag[e]&&(s.sub_layer_profile_space[e]=t.read(2),s.sub_layer_tier_flag[e]=t.read(1),s.sub_layer_profile_idc[e]=t.read(5),s.sub_layer_profile_compatibility_flag[e]=t.read(32),s.sub_layer_progressive_source_flag[e]=t.read(1),s.sub_layer_interlaced_source_flag[e]=t.read(1),s.sub_layer_non_packed_constraint_flag[e]=t.read(1),s.sub_layer_frame_only_constraint_flag[e]=t.read(1),t.read(32),t.read(12)),s.sub_layer_level_present_flag[e]?s.sub_layer_level_idc[e]=t.read(8):s.sub_layer_level_idc[e]=1;return s}(o,0,i.sps_max_sub_layers_minus1),i.sps_seq_parameter_set_id=o.read_golomb(),i.chroma_format_idc=o.read_golomb(),3==i.chroma_format_idc?i.separate_colour_plane_flag=o.read(1):i.separate_colour_plane_flag=0,i.pic_width_in_luma_samples=o.read_golomb(),i.pic_height_in_luma_samples=o.read_golomb(),i.conformance_window_flag=o.read(1),i.conformance_window_flag){let t=1+(i.chroma_format_idc<2),e=1+(i.chroma_format_idc<3);i.conf_win_left_offset=o.read_golomb()*e,i.conf_win_right_offset=o.read_golomb()*e,i.conf_win_top_offset=o.read_golomb()*t,i.conf_win_bottom_offset=o.read_golomb()*t}else i.conf_win_left_offset=0,i.conf_win_right_offset=0,i.conf_win_top_offset=0,i.conf_win_bottom_offset=0;return i}function Se(t){let{vps:e,pps:i,sps:s}=t,r={configurationVersion:1};const a=(t=>{let e=me(t),i=new oe(e);return i.readByte(),i.readByte(),i.readBits(4),i.readBits(2),i.readBits(6),{num_temporal_layers:i.readBits(3)+1,temporal_id_nested:i.readBool()}})(e),n=(t=>{let e=me(t),i=new oe(e);i.readByte(),i.readByte();let s=0,r=0,a=0,n=0;i.readBits(4);let o=i.readBits(3);i.readBool();let h=i.readBits(2),l=i.readBool(),d=i.readBits(5),u=i.readByte(),p=i.readByte(),c=i.readByte(),f=i.readByte(),_=i.readByte(),m=i.readByte(),g=i.readByte(),y=i.readByte(),b=i.readByte(),S=i.readByte(),v=i.readByte(),w=[],x=[];for(let t=0;t<o;t++)w.push(i.readBool()),x.push(i.readBool());if(o>0)for(let t=o;t<8;t++)i.readBits(2);for(let t=0;t<o;t++)w[t]&&(i.readByte(),i.readByte(),i.readByte(),i.readByte(),i.readByte(),i.readByte(),i.readByte(),i.readByte(),i.readByte(),i.readByte(),i.readByte()),w[t]&&i.readByte();i.readUEG();let U=i.readUEG();3==U&&i.readBits(1);let A=i.readUEG(),T=i.readUEG();i.readBool()&&(s+=i.readUEG(),r+=i.readUEG(),a+=i.readUEG(),n+=i.readUEG());let E=i.readUEG(),B=i.readUEG(),k=i.readUEG();for(let t=i.readBool()?0:o;t<=o;t++)i.readUEG(),i.readUEG(),i.readUEG();if(i.readUEG(),i.readUEG(),i.readUEG(),i.readUEG(),i.readUEG(),i.readUEG(),i.readBool()&&i.readBool())for(let t=0;t<4;t++)for(let e=0;e<(3===t?2:6);e++)if(i.readBool()){let e=Math.min(64,1<<4+(t<<1));t>1&&i.readSEG();for(let t=0;t<e;t++)i.readSEG()}else i.readUEG();i.readBool(),i.readBool(),i.readBool()&&(i.readByte(),i.readUEG(),i.readUEG(),i.readBool());let L=i.readUEG(),I=0;for(let t=0;t<L;t++){let e=!1;if(0!==t&&(e=i.readBool()),e){t===L&&i.readUEG(),i.readBool(),i.readUEG();let e=0;for(let t=0;t<=I;t++){let t=i.readBool(),s=!1;t||(s=i.readBool()),(t||s)&&e++}I=e}else{let t=i.readUEG(),e=i.readUEG();I=t+e;for(let e=0;e<t;e++)i.readUEG(),i.readBool();for(let t=0;t<e;t++)i.readUEG(),i.readBool()}}if(i.readBool()){let t=i.readUEG();for(let e=0;e<t;e++){for(let t=0;t<k+4;t++)i.readBits(1);i.readBits(1)}}let C=!1,D=0,P=1,F=1,R=!1,N=1,M=1;if(i.readBool(),i.readBool(),i.readBool()){if(i.readBool()){let t=i.readByte();t>0&&t<16?(P=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][t-1],F=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][t-1]):255===t&&(P=i.readBits(16),F=i.readBits(16))}if(i.readBool()&&i.readBool(),i.readBool()&&(i.readBits(3),i.readBool(),i.readBool()&&(i.readByte(),i.readByte(),i.readByte())),i.readBool()&&(i.readUEG(),i.readUEG()),i.readBool(),i.readBool(),i.readBool(),C=i.readBool(),C&&(s+=i.readUEG(),r+=i.readUEG(),a+=i.readUEG(),n+=i.readUEG()),i.readBool()&&(N=i.readBits(32),M=i.readBits(32),i.readBool()&&(i.readUEG(),i.readBool()))){let t=!1,e=!1,s=!1;t=i.readBool(),e=i.readBool(),(t||e)&&(s=i.readBool(),s&&(i.readByte(),i.readBits(5),i.readBool(),i.readBits(5)),i.readBits(4),i.readBits(4),s&&i.readBits(4),i.readBits(5),i.readBits(5),i.readBits(5));for(let r=0;r<=o;r++){let r=i.readBool();R=r;let a=!1,n=1;r||(a=i.readBool());let o=!1;if(a?i.readSEG():o=i.readBool(),o||(cpbcnt=i.readUEG()+1),t)for(let t=0;t<n;t++)i.readUEG(),i.readUEG(),s&&(i.readUEG(),i.readUEG());if(e)for(let t=0;t<n;t++)i.readUEG(),i.readUEG(),s&&(i.readUEG(),i.readUEG())}}i.readBool()&&(i.readBool(),i.readBool(),i.readBool(),D=i.readUEG(),i.readUEG(),i.readUEG(),i.readUEG(),i.readUEG())}i.readBool();let z=`hvc1.${d}.1.L${v}.B0`,G=A,O=T,H=1;return 1!==P&&1!==F&&(H=P/F),i.destroy(),i=null,{codec_mimetype:z,level_string:(V=v,(V/30).toFixed(1)),profile_idc:d,bit_depth:E+8,ref_frames:1,chroma_format:U,chroma_format_string:ge(U),general_level_idc:v,general_profile_space:h,general_tier_flag:l,general_profile_idc:d,general_profile_compatibility_flags_1:u,general_profile_compatibility_flags_2:p,general_profile_compatibility_flags_3:c,general_profile_compatibility_flags_4:f,general_constraint_indicator_flags_1:_,general_constraint_indicator_flags_2:m,general_constraint_indicator_flags_3:g,general_constraint_indicator_flags_4:y,general_constraint_indicator_flags_5:b,general_constraint_indicator_flags_6:S,min_spatial_segmentation_idc:D,constant_frame_rate:0,chroma_format_idc:U,bit_depth_luma_minus8:E,bit_depth_chroma_minus8:B,frame_rate:{fixed:R,fps:M/N,fps_den:N,fps_num:M},sar_ratio:{width:P,height:F},codec_size:{width:G,height:O},present_size:{width:G*H,height:O}};var V})(s),o=(t=>{let e=me(t),i=new oe(e);i.readByte(),i.readByte(),i.readUEG(),i.readUEG(),i.readBool(),i.readBool(),i.readBits(3),i.readBool(),i.readBool(),i.readUEG(),i.readUEG(),i.readSEG(),i.readBool(),i.readBool(),i.readBool()&&i.readUEG(),i.readSEG(),i.readSEG(),i.readBool(),i.readBool(),i.readBool(),i.readBool();let s=i.readBool(),r=i.readBool(),a=1;return r&&s?a=0:r?a=3:s&&(a=2),{parallelismType:a}})(i);r=Object.assign(r,a,n,o);let h=23+(5+e.byteLength)+(5+s.byteLength)+(5+i.byteLength),l=new Uint8Array(h);l[0]=1,l[1]=(3&r.general_profile_space)<<6|(r.general_tier_flag?1:0)<<5|31&r.general_profile_idc,l[2]=r.general_profile_compatibility_flags_1||0,l[3]=r.general_profile_compatibility_flags_2||0,l[4]=r.general_profile_compatibility_flags_3||0,l[5]=r.general_profile_compatibility_flags_4||0,l[6]=r.general_constraint_indicator_flags_1||0,l[7]=r.general_constraint_indicator_flags_2||0,l[8]=r.general_constraint_indicator_flags_3||0,l[9]=r.general_constraint_indicator_flags_4||0,l[10]=r.general_constraint_indicator_flags_5||0,l[11]=r.general_constraint_indicator_flags_6||0,l[12]=60,l[13]=240|(3840&r.min_spatial_segmentation_idc)>>8,l[14]=255&r.min_spatial_segmentation_idc,l[15]=252|3&r.parallelismType,l[16]=252|3&r.chroma_format_idc,l[17]=248|7&r.bit_depth_luma_minus8,l[18]=248|7&r.bit_depth_chroma_minus8,l[19]=0,l[20]=0,l[21]=(3&r.constant_frame_rate)<<6|(7&r.num_temporal_layers)<<3|(r.temporal_id_nested?1:0)<<2|3,l[22]=3,l[23]=128|q,l[24]=0,l[25]=1,l[26]=(65280&e.byteLength)>>8,l[27]=(255&e.byteLength)>>0,l.set(e,28),l[23+(5+e.byteLength)+0]=128|K,l[23+(5+e.byteLength)+1]=0,l[23+(5+e.byteLength)+2]=1,l[23+(5+e.byteLength)+3]=(65280&s.byteLength)>>8,l[23+(5+e.byteLength)+4]=(255&s.byteLength)>>0,l.set(s,23+(5+e.byteLength)+5),l[23+(5+e.byteLength+5+s.byteLength)+0]=128|X,l[23+(5+e.byteLength+5+s.byteLength)+1]=0,l[23+(5+e.byteLength+5+s.byteLength)+2]=1,l[23+(5+e.byteLength+5+s.byteLength)+3]=(65280&i.byteLength)>>8,l[23+(5+e.byteLength+5+s.byteLength)+4]=(255&i.byteLength)>>0,l.set(i,23+(5+e.byteLength+5+s.byteLength)+5);const d=[28,0,0,0,0],u=new Uint8Array(d.length+l.byteLength);return u.set(d,0),u.set(l,d.length),u}function ve(t,e){let i=[];i[0]=e?28:44,i[1]=1,i[2]=0,i[3]=0,i[4]=0;const s=new Uint8Array(i.length+t.byteLength);return s.set(i,0),s.set(t,i.length),s}function we(t){return(126&t[0])>>1}function xe(t){return!function(t){return t>=32&&t<=40}(t)}function Ue(t){return t>=16&&t<=21}class Ae extends t{constructor(t){super(),this.TAG_NAME="recorderCommon",this.player=t,this.fileName="",this._isRecording=!1,this._recordingTimestamp=0,this.recordingInterval=null,this.sps=null,this.pps=null,this.vps=null,this.codecId=null,this.audioCodeId=null,this.metaInfo={codecWidth:0,codecHeight:0,presentWidth:0,presentHeight:0,refSampleDuration:0,timescale:1e3,avcc:null,videoType:"",init:!1},this.audioMetaInfo={timescale:1e3,sampleRate:0,refSampleDuration:0,channelCount:0,codec:"",originalCodec:"",audioType:"",extraData:new Uint8Array(0),init:!1},this.startTimestamp=null}destroy(){this._reset(),this.sps=null,this.pps=null,this.vps=null,this.codecId=null,this.audioCodeId=null,this.metaInfo={},this.audioMetaInfo={}}get isH264(){return this.codecId===M}get isH265(){return this.codecId===z}setFileName(t){this.fileName=t}get isRecording(){return this._isRecording}get recording(){return this._isRecording}get recordTime(){return this._recordingTimestamp}startRecord(){}handleAddNaluTrack(t,e,i,s){}handleAddAudioTrack(t,e){}handleAddTrack(t){}stopRecordAndSave(){}startRecordingInterval(){}isWasmMp4(){return!1}stopRecordingInterval(){this.recordingInterval&&clearInterval(this.recordingInterval),this.recordingInterval=null}getToTalByteLength(){return 0}_reset(){this.fileName="",this._isRecording=!1,this._recordingTimestamp=0,this.stopRecordingInterval()}initMetaData(t,e){if(this.metaInfo.init)return;let i;const s=t.slice(5);if(this.codecId=e,this.metaInfo.avcc=s,e===M)i=function(t){const e={},i=new DataView(t.buffer);let s=i.getUint8(0),r=i.getUint8(1);if(i.getUint8(2),i.getUint8(3),1!==s||0===r)return{};const a=1+(3&i.getUint8(4));if(3!==a&&4!==a)return{};let n=31&i.getUint8(5);if(0===n)return{};let o=6;for(let s=0;s<n;s++){let r=i.getUint16(o,!1);if(o+=2,0===r)continue;let a=new Uint8Array(t.buffer,o,r);o+=r;let n=he.parseSPS(a);if(0!==s)continue;e.sps=a,e.timescale=1e3,e.codecWidth=n.codec_size.width,e.codecHeight=n.codec_size.height,e.presentWidth=n.present_size.width,e.presentHeight=n.present_size.height,e.profile=n.profile_string,e.level=n.level_string,e.bitDepth=n.bit_depth,e.chromaFormat=n.chroma_format,e.sarRatio=n.sar_ratio,e.frameRate=n.frame_rate,!1!==n.frame_rate.fixed&&0!==n.frame_rate.fps_num&&0!==n.frame_rate.fps_den||(e.frameRate={fixed:!0,fps:25,fps_num:25e3,fps_den:1e3});let h=e.frameRate.fps_den,l=e.frameRate.fps_num;e.refSampleDuration=e.timescale*(h/l);let d=a.subarray(1,4),u="avc1.";for(let t=0;t<3;t++){let e=d[t].toString(16);e.length<2&&(e="0"+e),u+=e}e.codec=u}let h=i.getUint8(o);if(0===h)return{};o++;for(let s=0;s<h;s++){let s=i.getUint16(o,!1);if(o+=2,0===s)continue;let r=new Uint8Array(t.buffer,o,s);o+=s,e.pps=r}if(e.videoType="avc",e.sps){const t=e.sps.byteLength,i=new Uint8Array([t>>>24&255,t>>>16&255,t>>>8&255,255&t]),s=new Uint8Array(t+4);s.set(i,0),s.set(e.sps,4),e.sps=s}if(e.pps){const t=e.pps.byteLength,i=new Uint8Array([t>>>24&255,t>>>16&255,t>>>8&255,255&t]),s=new Uint8Array(t+4);s.set(i,0),s.set(e.pps,4),e.pps=s}return e}(s);else if(e===z){i=function(t){let e=23;const i=t[e];if((63&i)!==q)return console.warn(`parseHEVCDecoderVPSAndSPSAndPPS and vpsTag is ${i}`),{};e+=2,e+=1;const s=t[e+1]|t[e]<<8;e+=2;const r=t.slice(e,e+s);e+=s;const a=t[e];if((63&a)!==K)return console.warn(`parseHEVCDecoderVPSAndSPSAndPPS and sps tag is ${a}`),{};e+=2,e+=1;const n=t[e+1]|t[e]<<8;e+=2;const o=t.slice(e,e+n);e+=n;const h=t[e];if((63&h)!==X)return console.warn(`parseHEVCDecoderVPSAndSPSAndPPS and pps tag is ${h}`),{};e+=2,e+=1;const l=t[e+1]|t[e]<<8;e+=2;const d=t.slice(e,e+l),u=new Uint8Array([n>>>24&255,n>>>16&255,n>>>8&255,255&n]),p=new Uint8Array([l>>>24&255,l>>>16&255,l>>>8&255,255&l]),c=new Uint8Array([s>>>24&255,s>>>16&255,s>>>8&255,255&s]),f=new Uint8Array(n+4);f.set(u,0),f.set(o,4);const _=new Uint8Array(l+4);_.set(p,0),_.set(d,4);const m=new Uint8Array(s+4);return m.set(c,0),m.set(r,4),{sps:f,pps:_,vps:m}}(s);const e=function(t){let e={width:0,height:0,profile:0,level:0};t=t.slice(5);do{let i={};if(t.length<23){console.warn("parseHEVCDecoderConfigurationRecord$2",`arrayBuffer.length ${t.length} < 23`);break}if(i.configurationVersion=t[0],1!=i.configurationVersion)break;i.general_profile_space=t[1]>>6&3,i.general_tier_flag=t[1]>>5&1,i.general_profile_idc=31&t[1],i.general_profile_compatibility_flags=t[2]<<24|t[3]<<16|t[4]<<8|t[5],i.general_constraint_indicator_flags=t[6]<<24|t[7]<<16|t[8]<<8|t[9],i.general_constraint_indicator_flags=i.general_constraint_indicator_flags<<16|t[10]<<8|t[11],i.general_level_idc=t[12],i.min_spatial_segmentation_idc=(15&t[13])<<8|t[14],i.parallelismType=3&t[15],i.chromaFormat=3&t[16],i.bitDepthLumaMinus8=7&t[17],i.bitDepthChromaMinus8=7&t[18],i.avgFrameRate=t[19]<<8|t[20],i.constantFrameRate=t[21]>>6&3,i.numTemporalLayers=t[21]>>3&7,i.temporalIdNested=t[21]>>2&1,i.lengthSizeMinusOne=3&t[21];let s=t[22],r=t.slice(23);for(let t=0;t<s&&!(r.length<3);t++){let t=63&r[0],s=r[1]<<8|r[2];r=r.slice(3);for(let a=0;a<s&&!(r.length<2);a++){let s=r[0]<<8|r[1];if(r.length<2+s)break;if(r=r.slice(2),33==t){let t=new Uint8Array(s);t.set(r.slice(0,s),0),i.psps=be(t),e.profile=i.general_profile_idc,e.level=i.general_level_idc/30,e.width=i.psps.pic_width_in_luma_samples-(i.psps.conf_win_left_offset+i.psps.conf_win_right_offset),e.height=i.psps.pic_height_in_luma_samples-(i.psps.conf_win_top_offset+i.psps.conf_win_bottom_offset)}r=r.slice(s)}}}while(0);return e.codecWidth=e.width||1920,e.codecHeight=e.height||1080,e.presentHeight=e.codecHeight,e.presentWidth=e.codecWidth,e.timescale=1e3,e.refSampleDuration=1e3/23976*1e3,e.videoType=Z,e}(t);i=Object.assign(i,e)}i&&(i.vps&&(this.vps=i.vps),i.pps&&(this.pps=i.pps),i.sps&&(this.sps=i.sps),i.presentWidth&&(this.metaInfo.presentWidth=i.presentWidth),i.presentHeight&&(this.metaInfo.presentHeight=i.presentHeight),i.codecWidth&&(this.metaInfo.codecWidth=i.codecWidth),i.codecHeight&&(this.metaInfo.codecHeight=i.codecHeight),i.timescale&&(this.metaInfo.timescale=i.timescale),i.refSampleDuration&&(this.metaInfo.refSampleDuration=i.refSampleDuration),i.videoType&&(this.metaInfo.videoType=i.videoType)),this.player.video.updateVideoInfo({width:this.metaInfo.codecWidth,height:this.metaInfo.codecHeight,encTypeCode:this.codecId}),this.metaInfo.init=!0}initAudioMetaData(t,e){if(this.audioMetaInfo.init)return;this.audioCodeId=e;const i=t[0]>>1&1;let s=null;e===H.AAC?(s=function(t){let e={},i=new It(t);return i.read(16),e.object_type=Ct(i),e.sample_rate=Dt(i,e),e.chan_config=i.read(4),e.chan_config<Ft.length&&(e.channels=Ft[e.chan_config]),e.sbr=-1,e.ps=-1,5!=e.object_type&&29!=e.object_type||(29==e.object_type&&(e.ps=1),e.ext_object_type=5,e.sbr=1,e.sample_rate=Dt(i,e),e.object_type=Ct(i)),{...e,channelCount:e.channels,sampleRate:e.sample_rate}}(t),s&&(s.channelCount&&(this.audioMetaInfo.channelCount=s.channelCount),s.codec&&(this.audioMetaInfo.codec=s.codec),s.originalCodec&&(this.audioMetaInfo.originalCodec=s.originalCodec),s.config&&(this.audioMetaInfo.config=s.config),s.sampleRate&&(this.audioMetaInfo.sampleRate=s.sampleRate),this.audioMetaInfo.sampleRate&&this.audioMetaInfo.timescale&&(this.audioMetaInfo.refSampleDuration=1024/this.audioMetaInfo.sampleRate*this.audioMetaInfo.timescale)),this.audioMetaInfo.extraData=t.slice(2),this.audioMetaInfo.depth=i?16:8):(this.audioMetaInfo.depth=0===i?8:16,this.audioMetaInfo.sampleRate=8e3,this.audioMetaInfo.channelCount=1),this.player.audio.updateAudioInfo({depth:this.audioMetaInfo.depth,sampleRate:this.audioMetaInfo.sampleRate,channels:this.audioMetaInfo.channelCount,encTypeCode:this.audioCodeId}),this.audioMetaInfo.init=!0}initAudioAacExtraData(t){this.audioMetaInfo.extraData=new Uint8Array(t)}handleAddContent(){}}class Te extends Ae{constructor(t){super(t),this.TAG_NAME="FlvRecorderLoader",this.player=t,this._init(),this.player.debug.log(this.TAG_NAME,"init")}destroy(){super.destroy(),this._init(),this.player.debug.log(this.TAG_NAME,"destroy")}_init(){this.hasAudio=!1,this.hasVideo=!1,this.startTime=null,this.currentTime=0,this.prevTimestamp=0,this.totalByteLength=0,this.totalDuration=0,this.flvMetaData=null,this.aacSequenceHeader=null,this.videoSequenceHeader=null,this.bufferList=[]}_reset(){super._reset(),this._init()}startRecord(){const t=this.player.debug;this._isRecording=!0,this.player.emit(k.recording,!0),t.log(this.TAG_NAME,"start recording"),this.player.emit(k.recordStart),this.startRecordingInterval()}startRecordingInterval(){this.stopRecordingInterval(),this.recordingInterval=window.setInterval((()=>{this.player.emit(k.recordingTimestamp,this.getTotalDuration())}),1e3)}addMetaData(t){this.flvMetaData=t}addAACSequenceHeader(t){this.aacSequenceHeader=t}addVideoSequenceHeader(t){this.videoSequenceHeader=t}addVideo(t,e){null===this.startTimestamp&&(this.startTimestamp=Rt());if(Rt()-this.startTimestamp>6e5)return;this._setStartTime(e);const i=this._getBufferTs(e);this.hasVideo=!0,this._createBufferItem(t,v,i)}addAudio(t,e){null===this.startTimestamp&&(this.startTimestamp=Rt());if(Rt()-this.startTimestamp>6e5)return;this._setStartTime(e);const i=this._getBufferTs(e);this.hasAudio=!0,this._createBufferItem(t,S,i)}_setStartTime(t){null===this.startTime&&this._isRecording&&(this.startTime=t,this.player.debug.log(this.TAG_NAME,`_setStartTime is ${t}`))}_getBufferTs(t){t>this.currentTime&&(this.currentTime=t);let e=0;return this.startTime&&t>=this.startTime&&(e=t-this.startTime),e>this.prevTimestamp?this.prevTimestamp=e:e=this.prevTimestamp,e}_createBufferItem(t,e,i){const s=this._createFlvPacket(t,e,i),r=this._createFlvTag(s);this.totalByteLength+=r.byteLength,this.bufferList.push(r)}_createFlvTag(t){let e=11+t.header.length,i=new Uint8Array(e+4);i[0]=t.header.type;let s=new DataView(i.buffer);return i[1]=t.header.length>>16&255,i[2]=t.header.length>>8&255,i[3]=255&t.header.length,i[4]=t.header.timestamp>>16&255,i[5]=t.header.timestamp>>8&255,i[6]=255&t.header.timestamp,i[7]=t.header.timestamp>>24&255,i[8]=0,i[9]=0,i[10]=0,s.setUint32(e,e),i.set(t.payload.subarray(0,t.header.length),11),i}_createFlvPacket(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;return{header:{length:t?t.length:0,timestamp:i,type:e},payload:t}}stopRecordAndSave(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:F,e=arguments.length>1?arguments[1]:void 0;return new Promise(((i,s)=>{if(!this.isRecording)return this.player.debug.error(this.TAG_NAME,"stop recording fail, isRecording is false "),s("stop recording fail, isRecording is false ");if(0===this.bufferList.length)return this.player.debug.error(this.TAG_NAME,"stop recording fail, this.bufferList.length is 0 "),s("stop recording fail, this.bufferList.length is 0 ");e&&this.setFileName(e);const r=new Uint8Array([70,76,86,1,0,0,0,0,9,0,0,0,0]);this.hasVideo&&(r[4]|=1),this.hasAudio&&(r[4]|=4);let a=[r];if(this.flvMetaData){const t=this._createFlvPacket(this.flvMetaData,w),e=this._createFlvTag(t);a.push(e)}if(this.videoSequenceHeader){const t=this._createFlvPacket(this.videoSequenceHeader,v),e=this._createFlvTag(t);a.push(e)}if(this.aacSequenceHeader){const t=this._createFlvPacket(this.aacSequenceHeader,S),e=this._createFlvTag(t);a.push(e)}const n=function(t){const e=t[0].constructor;return t.reduce(((t,i)=>{const s=new e((0|t.byteLength)+(0|i.byteLength));return s.set(t,0),s.set(i,0|t.byteLength),s}),new e)}(a.concat(this.bufferList));this.player.debug.log(this.TAG_NAME,"stop recording");const o=new Blob([n],{type:"application/octet-stream"});if(t===R)i(o),this.player.emit(k.recordBlob,o);else{i();Ht((this.fileName||Rt())+"."+l.flv,o)}this._reset(),this.player.emit(k.recording,!1)}))}getTotalDuration(){let t=0;return null!==this.startTime&&null!==this.currentTime&&(t=this.currentTime-this.startTime),Math.round(t/1e3)}getType(){return l.flv}getToTalByteLength(){return this.totalByteLength}}const Ee={init:0,findFirstStartCode:1,findSecondStartCode:2};class Be extends t{constructor(t){super(),this.player=t,this.isDestroyed=!1,this.reset()}destroy(){this.isDestroyed=!1,this.off(),this.reset()}reset(){this.stats=Ee.init,this.tempBuffer=new Uint8Array(0),this.parsedOffset=0,this.versionLayer=0}dispatch(t,e){let i=new Uint8Array(this.tempBuffer.length+t.length);for(i.set(this.tempBuffer,0),i.set(t,this.tempBuffer.length),this.tempBuffer=i;!this.isDestroyed;){if(this.state==Ee.Init){let t=!1;for(;this.tempBuffer.length-this.parsedOffset>=2&&!this.isDestroyed;)if(255==this.tempBuffer[this.parsedOffset]){if(!(!1&this.tempBuffer[this.parsedOffset+1])){this.versionLayer=this.tempBuffer[this.parsedOffset+1],this.state=Ee.findFirstStartCode,this.fisrtStartCodeOffset=this.parsedOffset,this.parsedOffset+=2,t=!0;break}this.parsedOffset++}else this.parsedOffset++;if(t)continue;break}if(this.state==Ee.findFirstStartCode){let t=!1;for(;this.tempBuffer.length-this.parsedOffset>=2&&!this.isDestroyed;)if(255==this.tempBuffer[this.parsedOffset]){if(this.tempBuffer[this.parsedOffset+1]==this.versionLayer){this.state=Ee.findSecondStartCode,this.secondStartCodeOffset=this.parsedOffset,this.parsedOffset+=2,t=!0;break}this.parsedOffset++}else this.parsedOffset++;if(t)continue;break}if(this.state==Ee.findSecondStartCode){let t=this.tempBuffer.slice(this.fisrtStartCodeOffset,this.secondStartCodeOffset);this.emit("data",t,e),this.tempBuffer=this.tempBuffer.slice(this.secondStartCodeOffset),this.fisrtStartCodeOffset=0,this.parsedOffset=2,this.state=Ee.findFirstStartCode}}}}class ke extends Ae{constructor(t){super(t),this.TAG_NAME="recorderWasmMP4",this._reset(),this.wasmMp4Recorder=new window.JessibucaProMp4Recorder({debug:t._opt.debug,debugLevel:t._opt.debugLevel,debugUuid:t._opt.debugUuid,decoder:t._opt.wasmMp4RecorderDecoder}),this.mp3Demuxer=null,t.debug.log(this.TAG_NAME,"init")}destroy(){super.destroy(),this.mp3Demuxer&&(this.mp3Demuxer.destroy(),this.mp3Demuxer=null),this._reset(),this.player.debug.log(this.TAG_NAME,"destroy")}_reset(){super._reset(),this.cacheTrack={},this.audioCacheTrack={},this.totalDuration=0,this.totalAudioDuration=0,this.totalByteLength=0,this.totalAudioByteLength=0,this.hasAudio=!1,this.hasVideo=!1}getType(){return l.mp4}isWasmMp4(){return!0}getTotalDuration(){return Math.round(this.totalDuration/1e3)}getToTalByteLength(){return this.totalByteLength+this.totalAudioByteLength}startRecord(){const t=this.player.debug,e=this.player.audio.getAudioInfo(),i=this.player.video.getVideoInfo(),s={};if(this.codecId){const t={type:this.codecId,width:i.width,height:i.height,extraData:this.metaInfo.avcc};s.video=t,this.hasVideo=!0}if(e.encTypeCode&&(e.encTypeCode===H.AAC||e.encTypeCode===H.MP3)){const t={type:e.encTypeCode,sampleRate:e.sampleRate,channels:e.channels,extraData:this.audioMetaInfo.extraData,depth:e.depth};this.audioCodeId=e.encTypeCode,s.audio=t,this.hasAudio=!0}this.player.debug.log(this.TAG_NAME,`startRecord(), hasAudio is ${this.hasAudio}, hasVideo is ${this.hasVideo}`),this._isRecording=!0,this.wasmMp4Recorder.startRecord(s).then((()=>{this.player.emit(k.recording,!0),t.log(this.TAG_NAME,"start recording"),this.player.emit(k.recordStart),this.startRecordingInterval()})).catch((e=>{t.error(this.TAG_NAME,"startRecord error",e),this.player._emitError(k.recordCreateError,e)}))}startRecordingInterval(){this.stopRecordingInterval(),this.recordingInterval=window.setInterval((()=>{this.player.emit(k.recordingTimestamp,this.getTotalDuration())}),1e3)}stopRecordAndSave(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:F,e=arguments.length>1?arguments[1]:void 0;return new Promise(((i,s)=>this.isRecording?0===this.totalDuration?(this.player.debug.error(this.TAG_NAME,"stop recording fail, totalDuration is 0 "),s("stop recording fail, totalDuration is 0 ")):(e&&this.setFileName(e),void this.wasmMp4Recorder.stopRecord().then((e=>{if(t===R)i(e),this.player.emit(k.recordBlob,e);else{i();Ht((this.fileName||Rt())+"."+l.mp4,e)}})).catch((t=>{this.player.debug.error(this.TAG_NAME,"stopRecord error",t),s(t)})).finally((()=>{this._reset(),this.player.emit(k.recording,!1)}))):(this.player.debug.error(this.TAG_NAME,"stop recording fail, isRecording is false "),s("stop recording fail, isRecording is false "))))}handleAddAudioTrack(t,e){this.audioCodeId===H.MP3?(this.mp3Demuxer||(this.mp3Demuxer=new Be(this.player),this.mp3Demuxer.on("data",((t,e)=>{this._handleAddAudioTrack(t,e)}))),this.mp3Demuxer.dispatch(t,ts)):this._handleAddAudioTrack(t,e)}_handleAddAudioTrack(t,e){if(Kt(this.hasAudio))return void this.player.debug.warn(this.TAG_NAME,"handleAddAudioTrack fail, hasAudio is false");null===this.startTimestamp&&(this.startTimestamp=Rt());Rt()-this.startTimestamp>6e5||(this.audioCacheTrack.id&&e>=this.audioCacheTrack.dts?(this.audioCacheTrack.duration=e-this.audioCacheTrack.dts,this.totalAudioDuration+=this.audioCacheTrack.duration,this.totalAudioByteLength+=this.audioCacheTrack.payload.byteLength,this.wasmMp4Recorder.sendAudioFrame(this.audioCacheTrack.payload,this.audioCacheTrack.dts)):this.audioCacheTrack={},this.audioCacheTrack={id:2,payload:t,dts:e})}handleAddNaluTrack(t,e,i,s){if(Kt(this.hasVideo))return void this.player.debug.warn(this.TAG_NAME,"handleAddNaluTrack fail, hasVideo is false");null===this.startTimestamp&&(this.startTimestamp=Rt());Rt()-this.startTimestamp>6e5||(this.cacheTrack.id&&i>=this.cacheTrack.dts?(this.cacheTrack.duration=i-this.cacheTrack.dts,this.totalDuration+=this.cacheTrack.duration,this.totalByteLength+=this.cacheTrack.payload.byteLength,this.wasmMp4Recorder.sendVideoFrame(this.cacheTrack.payload,this.cacheTrack.isIFrame,this.cacheTrack.dts)):this.cacheTrack={},this.cacheTrack={id:1,payload:t,isIFrame:e,dts:i,cts:s})}}class Le{constructor(t){return new(Le.getLoaderFactory(t._opt))(t)}static getLoaderFactory(t){if(t.recordType===l.mp4){if(window.JessibucaProMp4Recorder)return ke;throw new Error("JessibucaProMp4Recorder is not defined")}if(t.recordType===l.flv)return Te;throw new Error("recordType is not defined")}}class Ie extends t{constructor(t){super(),this.player=t,this.stopId=null,this.firstTimestamp=null,this.startTimestamp=null,this.preDelayTimestamp=null,this.preLoopTimestamp=null,this.bufferStartDts=null,this.bufferStartLocalTs=null,this.preIframeTs=null,this.preFrameTs=null,this.preTimestamp=null,this.preTimestampDuration=0,this.prevPayloadBufferSize=0,this.isStreamTsMoreThanLocal=!1,this.delay=-1,this.pushLatestDelay=-1,this.bufferList=[],this.historyIntervalDiffTimeList=[],this.playbackStreamFps=null,this.playbackStreamAudioFps=null,this.playbackStreamVideoFps=null,this.dropping=!1,this.isPushDropping=!1,this.player.debug.log("CommonDemux","init")}destroy(){this.bufferList=[],this.historyIntervalDiffTimeList=[],this.playbackStreamFps=null,this.playbackStreamAudioFps=null,this.playbackStreamVideoFps=null,this.firstTimestamp=null,this.startTimestamp=null,this.bufferStartDts=null,this.bufferStartLocalTs=null,this.preDelayTimestamp=null,this.preLoopTimestamp=null,this.preIframeTs=null,this.preTimestamp=null,this.preTimestampDuration=0,this.prevPayloadBufferSize=0,this.isStreamTsMoreThanLocal=!1,this.delay=-1,this.pushLatestDelay=-1,this.dropping=!1,this.isPushDropping=!1,this.off(),this.player.debug.log("CommonDemux","destroy")}_doDecode(t,e,i,s){let r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0;this.player;let a={ts:i,cts:r,type:e,isIFrame:!1};e===b&&(a.isIFrame=s),this.pushBuffer(t,a)}_doDecodeByHls(t,e,i,s){let r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0;this._doDecode(t,e,i,s,r)}_doDecodeByFmp4(t,e,i,s){let r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0;this._doDecode(t,e,i,s,r)}pushBuffer(t,e){if(this.player._updateStats({ts:e.ts}),e.type===y&&function(t){return Tt(t)&&t[1]===Q}(t)){this.player.debug.log("CommonDemux",`pushBuffer audio ts is ${e.ts}, isAacCodecPacket is true`);const i=t[0]>>4;if(this.player.recorder.initAudioMetaData(t,i),this.player.isRecordTypeFlv()){const i=new Uint8Array(t);this.player.recorder.addAACSequenceHeader(i,e.ts)}}else if(e.type===b&&e.isIFrame&&function(t){return t[0]>>4===tt&&t[1]===Q}(t)){this.player.debug.log("CommonDemux",`pushBuffer video ts is ${e.ts}, isVideoSequenceHeader is true`);const i=15&t[0];if(this.player.recorder.initMetaData(t,i),this.player.isRecordTypeFlv()){const i=new Uint8Array(t);this.player.recorder.addVideoSequenceHeader(i,e.ts)}}else if((this.player._hasVideoAndAudioInit()&&this.player.isRecordTypeMp4()||this.player.isRecordTypeFlv())&&Kt(this.player.recorder.isRecording)&&this.player.recorder.startRecord(),this.player.isRecordTypeFlv()){const i=new Uint8Array(t);e.type===b?this.player.recorder.addVideo(i,e.ts):e.type===y&&this.player.recorder.addAudio(i,e.ts)}else if(this.player.isRecordTypeMp4()){const i=new Uint8Array(t);if(e.type===b)this.player.recorder.handleAddNaluTrack(i.slice(5),e.isIFrame,e.ts,e.cts);else if(e.type===y){const i=new Uint8Array(t);this.player.recorder.handleAddAudioTrack(Tt(i)?i.slice(2):i.slice(1),e.ts)}}}close(){}reset(){}calcIframeIntervalTimestamp(){}}var Ce=function(t,e,i,s){return new(i||(i=Promise))((function(r,a){function n(t){try{h(s.next(t))}catch(t){a(t)}}function o(t){try{h(s.throw(t))}catch(t){a(t)}}function h(t){var e;t.done?r(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(n,o)}h((s=s.apply(t,e||[])).next())}))};const De=Symbol(32),Pe=Symbol(16),Fe=Symbol(8);class Re{constructor(t){this.g=t,this.consumed=0,t&&(this.need=t.next().value)}setG(t){this.g=t,this.demand(t.next().value,!0)}consume(){this.buffer&&this.consumed&&(this.buffer.copyWithin(0,this.consumed),this.buffer=this.buffer.subarray(0,this.buffer.length-this.consumed),this.consumed=0)}demand(t,e){return e&&this.consume(),this.need=t,this.flush()}read(t){return Ce(this,void 0,void 0,(function*(){return this.lastReadPromise&&(yield this.lastReadPromise),this.lastReadPromise=new Promise(((e,i)=>{var s;this.reject=i,this.resolve=t=>{delete this.lastReadPromise,delete this.resolve,delete this.need,e(t)};this.demand(t,!0)||null===(s=this.pull)||void 0===s||s.call(this,t)}))}))}readU32(){return this.read(De)}readU16(){return this.read(Pe)}readU8(){return this.read(Fe)}close(){var t;this.g&&this.g.return(),this.buffer&&this.buffer.subarray(0,0),null===(t=this.reject)||void 0===t||t.call(this,new Error("EOF")),delete this.lastReadPromise}flush(){if(!this.buffer||!this.need)return;let t=null;const e=this.buffer.subarray(this.consumed);let i=0;const s=t=>e.length<(i=t);if("number"==typeof this.need){if(s(this.need))return;t=e.subarray(0,i)}else if(this.need===De){if(s(4))return;t=e[0]<<24|e[1]<<16|e[2]<<8|e[3]}else if(this.need===Pe){if(s(2))return;t=e[0]<<8|e[1]}else if(this.need===Fe){if(s(1))return;t=e[0]}else if("buffer"in this.need){if("byteOffset"in this.need){if(s(this.need.byteLength-this.need.byteOffset))return;new Uint8Array(this.need.buffer,this.need.byteOffset).set(e.subarray(0,i)),t=this.need}else if(this.g)return void this.g.throw(new Error("Unsupported type"))}else{if(s(this.need.byteLength))return;new Uint8Array(this.need).set(e.subarray(0,i)),t=this.need}return this.consumed+=i,this.g?this.demand(this.g.next(t).value,!0):this.resolve&&this.resolve(t),t}write(t){if(t instanceof Uint8Array?this.malloc(t.length).set(t):"buffer"in t?this.malloc(t.byteLength).set(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)):this.malloc(t.byteLength).set(new Uint8Array(t)),!this.g&&!this.resolve)return new Promise((t=>this.pull=t));this.flush()}writeU32(t){this.malloc(4).set([t>>24&255,t>>16&255,t>>8&255,255&t]),this.flush()}writeU16(t){this.malloc(2).set([t>>8&255,255&t]),this.flush()}writeU8(t){this.malloc(1)[0]=t,this.flush()}malloc(t){if(this.buffer){const e=this.buffer.length,i=e+t;if(i<=this.buffer.buffer.byteLength-this.buffer.byteOffset)this.buffer=new Uint8Array(this.buffer.buffer,this.buffer.byteOffset,i);else{const t=new Uint8Array(i);t.set(this.buffer),this.buffer=t}return this.buffer.subarray(e,i)}return this.buffer=new Uint8Array(t),this.buffer}}Re.U32=De,Re.U16=Pe,Re.U8=Fe;class Ne extends Ie{constructor(t){super(t),this.input=new Re(this.demux()),t.debug.log("FlvDemux","init")}destroy(){super.destroy(),this.input=null,this.player.debug.log("FlvDemux","destroy")}dispatch(t){this.input?this.input.write(t):this.player&&this.player.debug.warn("FlvDemux","dispatch() this.input is null")}*demux(){yield 9;const t=new ArrayBuffer(4),e=new Uint8Array(t),i=new Uint32Array(t),s=this.player;for(;;){if(!this.input)return;e[3]=0;const t=yield 15,r=t[4];e[0]=t[7],e[1]=t[6],e[2]=t[5];const a=i[0];e[0]=t[10],e[1]=t[9],e[2]=t[8],e[3]=t[11];let n=i[0];const o=(yield a).slice();if(!s)return;switch(r){case S:s._opt.hasAudio&&(s._updateStats({abps:o.byteLength}),o.byteLength>0&&this._doDecode(o,y,n));break;case v:if(s._opt.hasVideo){let t=n;s._updateStats({vbps:o.byteLength,dts:t});const e=o[0]>>4&15;o[0];const r=o[1];let a=e===et;a&&this.calcIframeIntervalTimestamp(n);if(e===et&&r===st||(e===et&&r===rt||e===it&&r===rt))if(o.byteLength>0){i[0]=o[4],i[1]=o[3],i[2]=o[2],i[3]=0;let t=i[0],e=o;this._doDecode(e,b,n,a,t)}else this.player.debug.log("FlvDemux",`payload.byteLength is ${o.byteLength} is not > 0`);else this.player.debug.log("FlvDemux",`frameType is ${e} and packageType is ${r} is not sequenceHeader or nalu`)}break;case w:break;default:s.debug.log("FlvDemux",`demux() type is ${r}`)}}}close(){this.input=null}}class Me extends Ie{constructor(t){super(t),t.debug.log("M7sDemux","init")}destroy(){super.destroy(),this.player.debug.log("M7sDemux","destroy")}dispatch(t){const e=this.player,i=new DataView(t),s=i.getUint8(0),r=i.getUint32(1,!1);switch(s){case y:if(e._opt.hasAudio){const i=new Uint8Array(t,5);e._updateStats({abps:i.byteLength}),i.byteLength>0&&this._doDecode(i,s,r)}break;case b:if(e._opt.hasVideo)if(i.byteLength>5){const a=new Uint8Array(t,5),n=i.getUint8(5)>>4==1;let o=r;e._updateStats({vbps:a.byteLength,dts:o}),a.byteLength>0&&(n&&this.calcIframeIntervalTimestamp(r),this._doDecode(a,s,r,n))}else this.player.debug.warn("M7sDemux","dispatch","dv byteLength is",i.byteLength)}}}class ze extends Ne{constructor(t){super(t),t.debug.log("WebTransportDemux","init")}destroy(){this.player.debug.log("WebTransportDemux","destroy"),super.destroy()}}class Ge extends Ie{TAG_NAME="NakedFlowDemux";constructor(t){super(t),this.lastBuf=null,this.vps=null,this.sps=null,this.pps=null,this.streamVideoType=null,this.streamAudioType=null,this.tempNaluBufferList=new Uint8Array(0),this.localDts=0,this.isSendSeqHeader=!1,this.isSendAACSeqHeader=!1,t.debug.log(this.TAG_NAME,"init")}destroy(){super.destroy(),this.lastBuf=null,this.vps=null,this.sps=null,this.pps=null,this.streamVideoType=null,this.streamAudioType=null,this.tempNaluBufferList=new Uint8Array(0),this.localDts=0,this.localAudioDts=0,this.isSendSeqHeader=!1,this.isSendAACSeqHeader=!1,this.player.debug.log(this.TAG_NAME,"destroy")}dispatch(t){this.player;const e=new Uint8Array(t);this.extractNALu$2(e)}addNaluToBuffer(t){const e=t.byteLength+this.tempNaluBufferList.byteLength,i=new Uint8Array(e);i.set(this.tempNaluBufferList,0),i.set(t,this.tempNaluBufferList.byteLength),this.tempNaluBufferList=i}getNaluDts(){const t=this.player._opt.nakedFlowFps;return this.localDts=this.localDts+parseInt(1e3/t),this.localDts}getNaluAudioDts(){return this.localDts+parseInt(1024/48e3*1e3)}extractNALu(t){let e,i,s=0,r=t.byteLength,a=0,n=[];for(;s<r;)switch(e=t[s++],a){case 0:0===e&&(a=1);break;case 1:a=0===e?2:0;break;case 2:case 3:0===e?a=3:1===e&&s<r?(t[s],i&&n.push(t.subarray(i,s-a-1)),i=s,a=0):a=0}return i&&n.push(t.subarray(i,r)),n}extractNALu$2(t){let e=null;if(!t||t.byteLength<1)return;this.lastBuf?(e=new Uint8Array(t.byteLength+this.lastBuf.length),e.set(this.lastBuf),e.set(new Uint8Array(t),this.lastBuf.length)):e=new Uint8Array(t);let i=0,s=-1,r=-2;const a=new Array;for(let t=0;t<e.length;t+=2){const i=e[t],n=e[t+1];0==s&&0==i&&0==n?a.push(t-1):1==n&&0==i&&0==s&&0==r&&a.push(t-2),r=i,s=n}if(a.length>1)for(let t=0;t<a.length-1;++t){const s=e.subarray(a[t],a[t+1]+1);this.handleNALu(s),i=a[t+1]}else i=a[0];if(0!=i&&i<e.length)this.lastBuf=e.subarray(i);else{this.lastBuf||(this.lastBuf=e);const i=new Uint8Array(this.lastBuf.length+t.byteLength);i.set(this.lastBuf),i.set(new Uint8Array(t),this.lastBuf.length),this.lastBuf=i}}handleNALu(t){t.byteLength<4?this.player.debug.warn(this.TAG_NAME,`handleNALu nalu byteLength is ${t.byteLength} <= 4`):(t=t.slice(4),this.handleVideoNalu(t))}handleVideoNalu(t){const e=new Uint8Array(t);if(this.streamVideoType||(this.streamVideoType=function(t){let e=null,i=31&t[0];return i!==j.sps&&i!==j.pps||(e=G),e||(i=(126&t[0])>>1,i!==q&&i!==K&&i!==X||(e=O)),e}(e)),this.streamVideoType===G){const t=this.handleAddNaluStartCode(e),i=this.extractNALu(t);if(0===i.length)return void this.player.debug.warn(this.TAG_NAME,"handleVideoNalu","naluList.length === 0");const s=[];if(i.forEach((t=>{const e=pe(t);e===j.pps||e===j.sps?this.handleVideoH264Nalu(t):fe(e)&&s.push(t)})),1===s.length)this.handleVideoH264Nalu(s[0]);else{const t=function(t){if(0===t.length)return!1;const e=pe(t[0]);for(let i=1;i<t.length;i++)if(e!==pe(t[i]))return!1;return!0}(s);if(t){const t=pe(s[0]),e=_e(t);this.handleVideoH264NaluList(s,e,t)}else s.forEach((t=>{this.handleVideoH264Nalu(t)}))}}else if(this.streamVideoType===O){const t=this.handleAddNaluStartCode(e),i=this.extractNALu(t);if(0===i.length)return void this.player.debug.warn(this.TAG_NAME,"handleVideoNalu","h265 naluList.length === 0");const s=[];if(i.forEach((t=>{const e=we(t);e===X||e===K||e===q?this.handleVideoH265Nalu(t):xe(e)&&s.push(t)})),1===s.length)this.handleVideoH265Nalu(s[0]);else{const t=function(t){if(0===t.length)return!1;const e=we(t[0]);for(let i=1;i<t.length;i++)if(e!==we(t[i]))return!1;return!0}(s);if(t){const t=we(s[0]),e=Ue(t);this.handleVideoH265NaluList(s,e,t)}else s.forEach((t=>{this.handleVideoH265Nalu(t)}))}}else this.player.debug.error(this.TAG_NAME," this.streamVideoType is null")}extractH264PPS(t){const e=this.handleAddNaluStartCode(t);this.extractNALu(e).forEach((t=>{ce(pe(t))?this.extractH264SEI(t):this.handleVideoH264Nalu(t)}))}extractH265PPS(t){const e=this.handleAddNaluStartCode(t);this.extractNALu(e).forEach((t=>{const e=we(t);e===J?this.extractH265SEI(t):this.handleVideoH265Nalu(t)}))}extractH264SEI(t){const e=this.handleAddNaluStartCode(t);this.extractNALu(e).forEach((t=>{this.handleVideoH264Nalu(t)}))}extractH265SEI(t){const e=this.handleAddNaluStartCode(t);this.extractNALu(e).forEach((t=>{this.handleVideoH265Nalu(t)}))}handleAddNaluStartCode(t){const e=[0,0,0,1],i=new Uint8Array(t.length+e.length);return i.set(e),i.set(t,e.length),i}handleAudioAACNalu(t){if(!t||t.byteLength<1)return;this.streamAudioType||(this.streamAudioType=V);let e=new Uint8Array(t);const i=e.slice(0,7);if(e=e.slice(7),!this.isSendAACSeqHeader){const t=(192&i[2])>>6,e=(60&i[2])>>2,s=(1&i[2])<<2|(192&i[3])>>6,r=new Uint8Array([175,0,t<<3|(14&e)>>1,(1&e)<<7|s<<3]);this.isSendAACSeqHeader=!0,this._doDecode(r,y,0,!1,0)}const s=this.getNaluAudioDts(),r=new Uint8Array(e.length+2);r.set([175,1],0),r.set(e,2),this._doDecode(r,y,s,!1,0)}handleAudioG711ANalu(t){if(!t||t.byteLength<1)return;this.streamAudioType||(this.streamAudioType=W);let e=new Uint8Array(t);const i=this.getNaluAudioDts(),s=new Uint8Array(e.length+1);s.set([114],0),s.set(e,1),this._doDecode(s,y,i,!1,0)}handleAudioG711UNalu(t){if(!t||t.byteLength<1)return;this.streamAudioType||(this.streamAudioType=Y);let e=new Uint8Array(t);const i=this.getNaluAudioDts(),s=new Uint8Array(e.length+1);s.set([130],0),s.set(e,1),this._doDecode(s,y,i,!1,0)}handleVideoH264Nalu(t){const e=pe(t);switch(e){case j.sps:this.sps=t;break;case j.pps:this.pps=t}if(this.isSendSeqHeader){if(this.sps&&this.pps){const t=de({sps:this.sps,pps:this.pps}),e=this.getNaluDts();this._doDecode(t,b,e,!0,0),this.sps=null,this.pps=null}if(fe(e)){const i=_e(e),s=this.getNaluDts(),r=function(t,e){let i=[];i[0]=e?23:39,i[1]=1,i[2]=0,i[3]=0,i[4]=0,i[5]=t.byteLength>>24&255,i[6]=t.byteLength>>16&255,i[7]=t.byteLength>>8&255,i[8]=255&t.byteLength;const s=new Uint8Array(i.length+t.byteLength);return s.set(i,0),s.set(t,i.length),s}(t,i);this._preDoDecode(r,b,s,i,0)}else this.player.debug.warn(this.TAG_NAME,`handleVideoH264Nalu is avc seq head nalType is ${e}`)}else if(this.sps&&this.pps){this.isSendSeqHeader=!0;const t=de({sps:this.sps,pps:this.pps});this._doDecode(t,b,0,!0,0),this.sps=null,this.pps=null}}handleVideoH264NaluList(t,e,i){if(this.isSendSeqHeader){const i=this.getNaluDts(),s=ue(t.reduce(((t,e)=>{const i=ye(t),s=ye(e),r=new Uint8Array(i.byteLength+s.byteLength);return r.set(i,0),r.set(s,i.byteLength),r})),e);this._preDoDecode(s,b,i,e,0)}else this.player.debug.warn(this.TAG_NAME,"handleVideoH264NaluList isSendSeqHeader is false")}handleVideoH265Nalu(t){const e=we(t);switch(e){case q:this.vps=t;break;case K:this.sps=t;break;case X:this.pps=t}if(this.isSendSeqHeader){if(this.vps&&this.sps&&this.pps){const t=Se({vps:this.vps,sps:this.sps,pps:this.pps}),e=this.getNaluDts();this._doDecode(t,b,e,!0,0),this.vps=null,this.sps=null,this.pps=null}if(xe(e)){const i=Ue(e),s=this.getNaluDts(),r=function(t,e){let i=[];i[0]=e?28:44,i[1]=1,i[2]=0,i[3]=0,i[4]=0,i[5]=t.byteLength>>24&255,i[6]=t.byteLength>>16&255,i[7]=t.byteLength>>8&255,i[8]=255&t.byteLength;const s=new Uint8Array(i.length+t.byteLength);return s.set(i,0),s.set(t,i.length),s}(t,i);this._preDoDecode(r,b,s,i,0)}}else if(this.vps&&this.sps&&this.pps){this.isSendSeqHeader=!0;const t=Se({vps:this.vps,sps:this.sps,pps:this.pps});this._doDecode(t,b,0,!0,0),this.vps=null,this.sps=null,this.pps=null}}handleVideoH265NaluList(t,e,i){if(this.isSendSeqHeader){const i=this.getNaluDts(),s=ve(t.reduce(((t,e)=>{const i=ye(t),s=ye(e),r=new Uint8Array(i.byteLength+s.byteLength);return r.set(i,0),r.set(s,i.byteLength),r})),e);this._preDoDecode(s,b,i,e,0)}else this.player.debug.warn(this.TAG_NAME,"handleVideoH265NaluList isSendSeqHeader is false")}_preDoDecode(t,e,i,s,r){this.player._updateStats({vbps:t.byteLength,dts:i}),s&&this.calcIframeIntervalTimestamp(i),this._doDecode(t,b,i,s,r)}getInputByteLength(){let t=0;return this.lastBuf&&(t=this.lastBuf.byteLength),t}}class Oe extends Ie{constructor(t){super(t),this.player=t,t.debug.log("EmptyDemux","init")}destroy(){super.destroy(),this.player.debug.log("EmptyDemux","destroy")}}var He=function(t,e){return t(e={exports:{}},e.exports),e.exports}((function(t,e){var i,s,r,a=(i=new Date,s=4,r={setLogLevel:function(t){s=t==this.debug?1:t==this.info?2:t==this.warn?3:(this.error,4)},debug:function(t,e){void 0===console.debug&&(console.debug=console.log),1>=s&&console.debug("["+a.getDurationString(new Date-i,1e3)+"]","["+t+"]",e)},log:function(t,e){this.debug(t.msg)},info:function(t,e){2>=s&&console.info("["+a.getDurationString(new Date-i,1e3)+"]","["+t+"]",e)},warn:function(t,e){3>=s&&console.warn("["+a.getDurationString(new Date-i,1e3)+"]","["+t+"]",e)},error:function(t,e){4>=s&&console.error("["+a.getDurationString(new Date-i,1e3)+"]","["+t+"]",e)}},r);a.getDurationString=function(t,e){var i;function s(t,e){for(var i=(""+t).split(".");i[0].length<e;)i[0]="0"+i[0];return i.join(".")}t<0?(i=!0,t=-t):i=!1;var r=t/(e||1),a=Math.floor(r/3600);r-=3600*a;var n=Math.floor(r/60),o=1e3*(r-=60*n);return o-=1e3*(r=Math.floor(r)),o=Math.floor(o),(i?"-":"")+a+":"+s(n,2)+":"+s(r,2)+"."+s(o,3)},a.printRanges=function(t){var e=t.length;if(e>0){for(var i="",s=0;s<e;s++)s>0&&(i+=","),i+="["+a.getDurationString(t.start(s))+","+a.getDurationString(t.end(s))+"]";return i}return"(empty)"},e.Log=a;var n=function(t){if(!(t instanceof ArrayBuffer))throw"Needs an array buffer";this.buffer=t,this.dataview=new DataView(t),this.position=0};n.prototype.getPosition=function(){return this.position},n.prototype.getEndPosition=function(){return this.buffer.byteLength},n.prototype.getLength=function(){return this.buffer.byteLength},n.prototype.seek=function(t){var e=Math.max(0,Math.min(this.buffer.byteLength,t));return this.position=isNaN(e)||!isFinite(e)?0:e,!0},n.prototype.isEos=function(){return this.getPosition()>=this.getEndPosition()},n.prototype.readAnyInt=function(t,e){var i=0;if(this.position+t<=this.buffer.byteLength){switch(t){case 1:i=e?this.dataview.getInt8(this.position):this.dataview.getUint8(this.position);break;case 2:i=e?this.dataview.getInt16(this.position):this.dataview.getUint16(this.position);break;case 3:if(e)throw"No method for reading signed 24 bits values";i=this.dataview.getUint8(this.position)<<16,i|=this.dataview.getUint8(this.position+1)<<8,i|=this.dataview.getUint8(this.position+2);break;case 4:i=e?this.dataview.getInt32(this.position):this.dataview.getUint32(this.position);break;case 8:if(e)throw"No method for reading signed 64 bits values";i=this.dataview.getUint32(this.position)<<32,i|=this.dataview.getUint32(this.position+4);break;default:throw"readInt method not implemented for size: "+t}return this.position+=t,i}throw"Not enough bytes in buffer"},n.prototype.readUint8=function(){return this.readAnyInt(1,!1)},n.prototype.readUint16=function(){return this.readAnyInt(2,!1)},n.prototype.readUint24=function(){return this.readAnyInt(3,!1)},n.prototype.readUint32=function(){return this.readAnyInt(4,!1)},n.prototype.readUint64=function(){return this.readAnyInt(8,!1)},n.prototype.readString=function(t){if(this.position+t<=this.buffer.byteLength){for(var e="",i=0;i<t;i++)e+=String.fromCharCode(this.readUint8());return e}throw"Not enough bytes in buffer"},n.prototype.readCString=function(){for(var t=[];;){var e=this.readUint8();if(0===e)break;t.push(e)}return String.fromCharCode.apply(null,t)},n.prototype.readInt8=function(){return this.readAnyInt(1,!0)},n.prototype.readInt16=function(){return this.readAnyInt(2,!0)},n.prototype.readInt32=function(){return this.readAnyInt(4,!0)},n.prototype.readInt64=function(){return this.readAnyInt(8,!1)},n.prototype.readUint8Array=function(t){for(var e=new Uint8Array(t),i=0;i<t;i++)e[i]=this.readUint8();return e},n.prototype.readInt16Array=function(t){for(var e=new Int16Array(t),i=0;i<t;i++)e[i]=this.readInt16();return e},n.prototype.readUint16Array=function(t){for(var e=new Int16Array(t),i=0;i<t;i++)e[i]=this.readUint16();return e},n.prototype.readUint32Array=function(t){for(var e=new Uint32Array(t),i=0;i<t;i++)e[i]=this.readUint32();return e},n.prototype.readInt32Array=function(t){for(var e=new Int32Array(t),i=0;i<t;i++)e[i]=this.readInt32();return e},e.MP4BoxStream=n;var o=function(t,e,i){this._byteOffset=e||0,t instanceof ArrayBuffer?this.buffer=t:"object"==typeof t?(this.dataView=t,e&&(this._byteOffset+=e)):this.buffer=new ArrayBuffer(t||0),this.position=0,this.endianness=null==i?o.LITTLE_ENDIAN:i};o.prototype={},o.prototype.getPosition=function(){return this.position},o.prototype._realloc=function(t){if(this._dynamicSize){var e=this._byteOffset+this.position+t,i=this._buffer.byteLength;if(e<=i)e>this._byteLength&&(this._byteLength=e);else{for(i<1&&(i=1);e>i;)i*=2;var s=new ArrayBuffer(i),r=new Uint8Array(this._buffer);new Uint8Array(s,0,r.length).set(r),this.buffer=s,this._byteLength=e}}},o.prototype._trimAlloc=function(){if(this._byteLength!=this._buffer.byteLength){var t=new ArrayBuffer(this._byteLength),e=new Uint8Array(t),i=new Uint8Array(this._buffer,0,e.length);e.set(i),this.buffer=t}},o.BIG_ENDIAN=!1,o.LITTLE_ENDIAN=!0,o.prototype._byteLength=0,Object.defineProperty(o.prototype,"byteLength",{get:function(){return this._byteLength-this._byteOffset}}),Object.defineProperty(o.prototype,"buffer",{get:function(){return this._trimAlloc(),this._buffer},set:function(t){this._buffer=t,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._buffer.byteLength}}),Object.defineProperty(o.prototype,"byteOffset",{get:function(){return this._byteOffset},set:function(t){this._byteOffset=t,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._buffer.byteLength}}),Object.defineProperty(o.prototype,"dataView",{get:function(){return this._dataView},set:function(t){this._byteOffset=t.byteOffset,this._buffer=t.buffer,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._byteOffset+t.byteLength}}),o.prototype.seek=function(t){var e=Math.max(0,Math.min(this.byteLength,t));this.position=isNaN(e)||!isFinite(e)?0:e},o.prototype.isEof=function(){return this.position>=this._byteLength},o.prototype.mapUint8Array=function(t){this._realloc(1*t);var e=new Uint8Array(this._buffer,this.byteOffset+this.position,t);return this.position+=1*t,e},o.prototype.readInt32Array=function(t,e){t=null==t?this.byteLength-this.position/4:t;var i=new Int32Array(t);return o.memcpy(i.buffer,0,this.buffer,this.byteOffset+this.position,t*i.BYTES_PER_ELEMENT),o.arrayToNative(i,null==e?this.endianness:e),this.position+=i.byteLength,i},o.prototype.readInt16Array=function(t,e){t=null==t?this.byteLength-this.position/2:t;var i=new Int16Array(t);return o.memcpy(i.buffer,0,this.buffer,this.byteOffset+this.position,t*i.BYTES_PER_ELEMENT),o.arrayToNative(i,null==e?this.endianness:e),this.position+=i.byteLength,i},o.prototype.readInt8Array=function(t){t=null==t?this.byteLength-this.position:t;var e=new Int8Array(t);return o.memcpy(e.buffer,0,this.buffer,this.byteOffset+this.position,t*e.BYTES_PER_ELEMENT),this.position+=e.byteLength,e},o.prototype.readUint32Array=function(t,e){t=null==t?this.byteLength-this.position/4:t;var i=new Uint32Array(t);return o.memcpy(i.buffer,0,this.buffer,this.byteOffset+this.position,t*i.BYTES_PER_ELEMENT),o.arrayToNative(i,null==e?this.endianness:e),this.position+=i.byteLength,i},o.prototype.readUint16Array=function(t,e){t=null==t?this.byteLength-this.position/2:t;var i=new Uint16Array(t);return o.memcpy(i.buffer,0,this.buffer,this.byteOffset+this.position,t*i.BYTES_PER_ELEMENT),o.arrayToNative(i,null==e?this.endianness:e),this.position+=i.byteLength,i},o.prototype.readUint8Array=function(t){t=null==t?this.byteLength-this.position:t;var e=new Uint8Array(t);return o.memcpy(e.buffer,0,this.buffer,this.byteOffset+this.position,t*e.BYTES_PER_ELEMENT),this.position+=e.byteLength,e},o.prototype.readFloat64Array=function(t,e){t=null==t?this.byteLength-this.position/8:t;var i=new Float64Array(t);return o.memcpy(i.buffer,0,this.buffer,this.byteOffset+this.position,t*i.BYTES_PER_ELEMENT),o.arrayToNative(i,null==e?this.endianness:e),this.position+=i.byteLength,i},o.prototype.readFloat32Array=function(t,e){t=null==t?this.byteLength-this.position/4:t;var i=new Float32Array(t);return o.memcpy(i.buffer,0,this.buffer,this.byteOffset+this.position,t*i.BYTES_PER_ELEMENT),o.arrayToNative(i,null==e?this.endianness:e),this.position+=i.byteLength,i},o.prototype.readInt32=function(t){var e=this._dataView.getInt32(this.position,null==t?this.endianness:t);return this.position+=4,e},o.prototype.readInt16=function(t){var e=this._dataView.getInt16(this.position,null==t?this.endianness:t);return this.position+=2,e},o.prototype.readInt8=function(){var t=this._dataView.getInt8(this.position);return this.position+=1,t},o.prototype.readUint32=function(t){var e=this._dataView.getUint32(this.position,null==t?this.endianness:t);return this.position+=4,e},o.prototype.readUint16=function(t){var e=this._dataView.getUint16(this.position,null==t?this.endianness:t);return this.position+=2,e},o.prototype.readUint8=function(){var t=this._dataView.getUint8(this.position);return this.position+=1,t},o.prototype.readFloat32=function(t){var e=this._dataView.getFloat32(this.position,null==t?this.endianness:t);return this.position+=4,e},o.prototype.readFloat64=function(t){var e=this._dataView.getFloat64(this.position,null==t?this.endianness:t);return this.position+=8,e},o.endianness=new Int8Array(new Int16Array([1]).buffer)[0]>0,o.memcpy=function(t,e,i,s,r){var a=new Uint8Array(t,e,r),n=new Uint8Array(i,s,r);a.set(n)},o.arrayToNative=function(t,e){return e==this.endianness?t:this.flipArrayEndianness(t)},o.nativeToEndian=function(t,e){return this.endianness==e?t:this.flipArrayEndianness(t)},o.flipArrayEndianness=function(t){for(var e=new Uint8Array(t.buffer,t.byteOffset,t.byteLength),i=0;i<t.byteLength;i+=t.BYTES_PER_ELEMENT)for(var s=i+t.BYTES_PER_ELEMENT-1,r=i;s>r;s--,r++){var a=e[r];e[r]=e[s],e[s]=a}return t},o.prototype.failurePosition=0,String.fromCharCodeUint8=function(t){for(var e=[],i=0;i<t.length;i++)e[i]=t[i];return String.fromCharCode.apply(null,e)},o.prototype.readString=function(t,e){return null==e||"ASCII"==e?String.fromCharCodeUint8.apply(null,[this.mapUint8Array(null==t?this.byteLength-this.position:t)]):new TextDecoder(e).decode(this.mapUint8Array(t))},o.prototype.readCString=function(t){var e=this.byteLength-this.position,i=new Uint8Array(this._buffer,this._byteOffset+this.position),s=e;null!=t&&(s=Math.min(t,e));for(var r=0;r<s&&0!==i[r];r++);var a=String.fromCharCodeUint8.apply(null,[this.mapUint8Array(r)]);return null!=t?this.position+=s-r:r!=e&&(this.position+=1),a};var h=Math.pow(2,32);o.prototype.readInt64=function(){return this.readInt32()*h+this.readUint32()},o.prototype.readUint64=function(){return this.readUint32()*h+this.readUint32()},o.prototype.readInt64=function(){return this.readUint32()*h+this.readUint32()},o.prototype.readUint24=function(){return(this.readUint8()<<16)+(this.readUint8()<<8)+this.readUint8()},e.DataStream=o,o.prototype.save=function(t){var e=new Blob([this.buffer]);if(!window.URL||!URL.createObjectURL)throw"DataStream.save: Can't create object URL.";var i=window.URL.createObjectURL(e),s=document.createElement("a");document.body.appendChild(s),s.setAttribute("href",i),s.setAttribute("download",t),s.setAttribute("target","_self"),s.click(),window.URL.revokeObjectURL(i)},o.prototype._dynamicSize=!0,Object.defineProperty(o.prototype,"dynamicSize",{get:function(){return this._dynamicSize},set:function(t){t||this._trimAlloc(),this._dynamicSize=t}}),o.prototype.shift=function(t){var e=new ArrayBuffer(this._byteLength-t),i=new Uint8Array(e),s=new Uint8Array(this._buffer,t,i.length);i.set(s),this.buffer=e,this.position-=t},o.prototype.writeInt32Array=function(t,e){if(this._realloc(4*t.length),t instanceof Int32Array&&this.byteOffset+this.position%t.BYTES_PER_ELEMENT===0)o.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,0,t.byteLength),this.mapInt32Array(t.length,e);else for(var i=0;i<t.length;i++)this.writeInt32(t[i],e)},o.prototype.writeInt16Array=function(t,e){if(this._realloc(2*t.length),t instanceof Int16Array&&this.byteOffset+this.position%t.BYTES_PER_ELEMENT===0)o.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,0,t.byteLength),this.mapInt16Array(t.length,e);else for(var i=0;i<t.length;i++)this.writeInt16(t[i],e)},o.prototype.writeInt8Array=function(t){if(this._realloc(1*t.length),t instanceof Int8Array&&this.byteOffset+this.position%t.BYTES_PER_ELEMENT===0)o.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,0,t.byteLength),this.mapInt8Array(t.length);else for(var e=0;e<t.length;e++)this.writeInt8(t[e])},o.prototype.writeUint32Array=function(t,e){if(this._realloc(4*t.length),t instanceof Uint32Array&&this.byteOffset+this.position%t.BYTES_PER_ELEMENT===0)o.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,0,t.byteLength),this.mapUint32Array(t.length,e);else for(var i=0;i<t.length;i++)this.writeUint32(t[i],e)},o.prototype.writeUint16Array=function(t,e){if(this._realloc(2*t.length),t instanceof Uint16Array&&this.byteOffset+this.position%t.BYTES_PER_ELEMENT===0)o.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,0,t.byteLength),this.mapUint16Array(t.length,e);else for(var i=0;i<t.length;i++)this.writeUint16(t[i],e)},o.prototype.writeUint8Array=function(t){if(this._realloc(1*t.length),t instanceof Uint8Array&&this.byteOffset+this.position%t.BYTES_PER_ELEMENT===0)o.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,0,t.byteLength),this.mapUint8Array(t.length);else for(var e=0;e<t.length;e++)this.writeUint8(t[e])},o.prototype.writeFloat64Array=function(t,e){if(this._realloc(8*t.length),t instanceof Float64Array&&this.byteOffset+this.position%t.BYTES_PER_ELEMENT===0)o.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,0,t.byteLength),this.mapFloat64Array(t.length,e);else for(var i=0;i<t.length;i++)this.writeFloat64(t[i],e)},o.prototype.writeFloat32Array=function(t,e){if(this._realloc(4*t.length),t instanceof Float32Array&&this.byteOffset+this.position%t.BYTES_PER_ELEMENT===0)o.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,0,t.byteLength),this.mapFloat32Array(t.length,e);else for(var i=0;i<t.length;i++)this.writeFloat32(t[i],e)},o.prototype.writeInt32=function(t,e){this._realloc(4),this._dataView.setInt32(this.position,t,null==e?this.endianness:e),this.position+=4},o.prototype.writeInt16=function(t,e){this._realloc(2),this._dataView.setInt16(this.position,t,null==e?this.endianness:e),this.position+=2},o.prototype.writeInt8=function(t){this._realloc(1),this._dataView.setInt8(this.position,t),this.position+=1},o.prototype.writeUint32=function(t,e){this._realloc(4),this._dataView.setUint32(this.position,t,null==e?this.endianness:e),this.position+=4},o.prototype.writeUint16=function(t,e){this._realloc(2),this._dataView.setUint16(this.position,t,null==e?this.endianness:e),this.position+=2},o.prototype.writeUint8=function(t){this._realloc(1),this._dataView.setUint8(this.position,t),this.position+=1},o.prototype.writeFloat32=function(t,e){this._realloc(4),this._dataView.setFloat32(this.position,t,null==e?this.endianness:e),this.position+=4},o.prototype.writeFloat64=function(t,e){this._realloc(8),this._dataView.setFloat64(this.position,t,null==e?this.endianness:e),this.position+=8},o.prototype.writeUCS2String=function(t,e,i){null==i&&(i=t.length);for(var s=0;s<t.length&&s<i;s++)this.writeUint16(t.charCodeAt(s),e);for(;s<i;s++)this.writeUint16(0)},o.prototype.writeString=function(t,e,i){var s=0;if(null==e||"ASCII"==e)if(null!=i){var r=Math.min(t.length,i);for(s=0;s<r;s++)this.writeUint8(t.charCodeAt(s));for(;s<i;s++)this.writeUint8(0)}else for(s=0;s<t.length;s++)this.writeUint8(t.charCodeAt(s));else this.writeUint8Array(new TextEncoder(e).encode(t.substring(0,i)))},o.prototype.writeCString=function(t,e){var i=0;if(null!=e){var s=Math.min(t.length,e);for(i=0;i<s;i++)this.writeUint8(t.charCodeAt(i));for(;i<e;i++)this.writeUint8(0)}else{for(i=0;i<t.length;i++)this.writeUint8(t.charCodeAt(i));this.writeUint8(0)}},o.prototype.writeStruct=function(t,e){for(var i=0;i<t.length;i+=2){var s=t[i+1];this.writeType(s,e[t[i]],e)}},o.prototype.writeType=function(t,e,i){var s;if("function"==typeof t)return t(this,e);if("object"==typeof t&&!(t instanceof Array))return t.set(this,e,i);var r=null,a="ASCII",n=this.position;switch("string"==typeof t&&/:/.test(t)&&(s=t.split(":"),t=s[0],r=parseInt(s[1])),"string"==typeof t&&/,/.test(t)&&(s=t.split(","),t=s[0],a=parseInt(s[1])),t){case"uint8":this.writeUint8(e);break;case"int8":this.writeInt8(e);break;case"uint16":this.writeUint16(e,this.endianness);break;case"int16":this.writeInt16(e,this.endianness);break;case"uint32":this.writeUint32(e,this.endianness);break;case"int32":this.writeInt32(e,this.endianness);break;case"float32":this.writeFloat32(e,this.endianness);break;case"float64":this.writeFloat64(e,this.endianness);break;case"uint16be":this.writeUint16(e,o.BIG_ENDIAN);break;case"int16be":this.writeInt16(e,o.BIG_ENDIAN);break;case"uint32be":this.writeUint32(e,o.BIG_ENDIAN);break;case"int32be":this.writeInt32(e,o.BIG_ENDIAN);break;case"float32be":this.writeFloat32(e,o.BIG_ENDIAN);break;case"float64be":this.writeFloat64(e,o.BIG_ENDIAN);break;case"uint16le":this.writeUint16(e,o.LITTLE_ENDIAN);break;case"int16le":this.writeInt16(e,o.LITTLE_ENDIAN);break;case"uint32le":this.writeUint32(e,o.LITTLE_ENDIAN);break;case"int32le":this.writeInt32(e,o.LITTLE_ENDIAN);break;case"float32le":this.writeFloat32(e,o.LITTLE_ENDIAN);break;case"float64le":this.writeFloat64(e,o.LITTLE_ENDIAN);break;case"cstring":this.writeCString(e,r);break;case"string":this.writeString(e,a,r);break;case"u16string":this.writeUCS2String(e,this.endianness,r);break;case"u16stringle":this.writeUCS2String(e,o.LITTLE_ENDIAN,r);break;case"u16stringbe":this.writeUCS2String(e,o.BIG_ENDIAN,r);break;default:if(3==t.length){for(var h=t[1],l=0;l<e.length;l++)this.writeType(h,e[l]);break}this.writeStruct(t,e)}null!=r&&(this.position=n,this._realloc(r),this.position=n+r)},o.prototype.writeUint64=function(t){var e=Math.floor(t/h);this.writeUint32(e),this.writeUint32(4294967295&t)},o.prototype.writeUint24=function(t){this.writeUint8((16711680&t)>>16),this.writeUint8((65280&t)>>8),this.writeUint8(255&t)},o.prototype.adjustUint32=function(t,e){var i=this.position;this.seek(t),this.writeUint32(e),this.seek(i)},o.prototype.mapInt32Array=function(t,e){this._realloc(4*t);var i=new Int32Array(this._buffer,this.byteOffset+this.position,t);return o.arrayToNative(i,null==e?this.endianness:e),this.position+=4*t,i},o.prototype.mapInt16Array=function(t,e){this._realloc(2*t);var i=new Int16Array(this._buffer,this.byteOffset+this.position,t);return o.arrayToNative(i,null==e?this.endianness:e),this.position+=2*t,i},o.prototype.mapInt8Array=function(t){this._realloc(1*t);var e=new Int8Array(this._buffer,this.byteOffset+this.position,t);return this.position+=1*t,e},o.prototype.mapUint32Array=function(t,e){this._realloc(4*t);var i=new Uint32Array(this._buffer,this.byteOffset+this.position,t);return o.arrayToNative(i,null==e?this.endianness:e),this.position+=4*t,i},o.prototype.mapUint16Array=function(t,e){this._realloc(2*t);var i=new Uint16Array(this._buffer,this.byteOffset+this.position,t);return o.arrayToNative(i,null==e?this.endianness:e),this.position+=2*t,i},o.prototype.mapFloat64Array=function(t,e){this._realloc(8*t);var i=new Float64Array(this._buffer,this.byteOffset+this.position,t);return o.arrayToNative(i,null==e?this.endianness:e),this.position+=8*t,i},o.prototype.mapFloat32Array=function(t,e){this._realloc(4*t);var i=new Float32Array(this._buffer,this.byteOffset+this.position,t);return o.arrayToNative(i,null==e?this.endianness:e),this.position+=4*t,i};var l=function(t){this.buffers=[],this.bufferIndex=-1,t&&(this.insertBuffer(t),this.bufferIndex=0)};(l.prototype=new o(new ArrayBuffer,0,o.BIG_ENDIAN)).initialized=function(){var t;return this.bufferIndex>-1||(this.buffers.length>0?0===(t=this.buffers[0]).fileStart?(this.buffer=t,this.bufferIndex=0,a.debug("MultiBufferStream","Stream ready for parsing"),!0):(a.warn("MultiBufferStream","The first buffer should have a fileStart of 0"),this.logBufferLevel(),!1):(a.warn("MultiBufferStream","No buffer to start parsing from"),this.logBufferLevel(),!1))},ArrayBuffer.concat=function(t,e){a.debug("ArrayBuffer","Trying to create a new buffer of size: "+(t.byteLength+e.byteLength));var i=new Uint8Array(t.byteLength+e.byteLength);return i.set(new Uint8Array(t),0),i.set(new Uint8Array(e),t.byteLength),i.buffer},l.prototype.reduceBuffer=function(t,e,i){var s;return(s=new Uint8Array(i)).set(new Uint8Array(t,e,i)),s.buffer.fileStart=t.fileStart+e,s.buffer.usedBytes=0,s.buffer},l.prototype.insertBuffer=function(t){for(var e=!0,i=0;i<this.buffers.length;i++){var s=this.buffers[i];if(t.fileStart<=s.fileStart){if(t.fileStart===s.fileStart){if(t.byteLength>s.byteLength){this.buffers.splice(i,1),i--;continue}a.warn("MultiBufferStream","Buffer (fileStart: "+t.fileStart+" - Length: "+t.byteLength+") already appended, ignoring")}else t.fileStart+t.byteLength<=s.fileStart||(t=this.reduceBuffer(t,0,s.fileStart-t.fileStart)),a.debug("MultiBufferStream","Appending new buffer (fileStart: "+t.fileStart+" - Length: "+t.byteLength+")"),this.buffers.splice(i,0,t),0===i&&(this.buffer=t);e=!1;break}if(t.fileStart<s.fileStart+s.byteLength){var r=s.fileStart+s.byteLength-t.fileStart,n=t.byteLength-r;if(!(n>0)){e=!1;break}t=this.reduceBuffer(t,r,n)}}e&&(a.debug("MultiBufferStream","Appending new buffer (fileStart: "+t.fileStart+" - Length: "+t.byteLength+")"),this.buffers.push(t),0===i&&(this.buffer=t))},l.prototype.logBufferLevel=function(t){var e,i,s,r,n,o=[],h="";for(s=0,r=0,e=0;e<this.buffers.length;e++)i=this.buffers[e],0===e?(n={},o.push(n),n.start=i.fileStart,n.end=i.fileStart+i.byteLength,h+="["+n.start+"-"):n.end===i.fileStart?n.end=i.fileStart+i.byteLength:((n={}).start=i.fileStart,h+=o[o.length-1].end-1+"], ["+n.start+"-",n.end=i.fileStart+i.byteLength,o.push(n)),s+=i.usedBytes,r+=i.byteLength;o.length>0&&(h+=n.end-1+"]");var l=t?a.info:a.debug;0===this.buffers.length?l("MultiBufferStream","No more buffer in memory"):l("MultiBufferStream",this.buffers.length+" stored buffer(s) ("+s+"/"+r+" bytes), continuous ranges: "+h)},l.prototype.cleanBuffers=function(){var t,e;for(t=0;t<this.buffers.length;t++)(e=this.buffers[t]).usedBytes===e.byteLength&&(a.debug("MultiBufferStream","Removing buffer #"+t),this.buffers.splice(t,1),t--)},l.prototype.mergeNextBuffer=function(){var t;if(this.bufferIndex+1<this.buffers.length){if((t=this.buffers[this.bufferIndex+1]).fileStart===this.buffer.fileStart+this.buffer.byteLength){var e=this.buffer.byteLength,i=this.buffer.usedBytes,s=this.buffer.fileStart;return this.buffers[this.bufferIndex]=ArrayBuffer.concat(this.buffer,t),this.buffer=this.buffers[this.bufferIndex],this.buffers.splice(this.bufferIndex+1,1),this.buffer.usedBytes=i,this.buffer.fileStart=s,a.debug("ISOFile","Concatenating buffer for box parsing (length: "+e+"->"+this.buffer.byteLength+")"),!0}return!1}return!1},l.prototype.findPosition=function(t,e,i){var s,r=null,n=-1;for(s=!0===t?0:this.bufferIndex;s<this.buffers.length&&(r=this.buffers[s]).fileStart<=e;)n=s,i&&(r.fileStart+r.byteLength<=e?r.usedBytes=r.byteLength:r.usedBytes=e-r.fileStart,this.logBufferLevel()),s++;return-1!==n&&(r=this.buffers[n]).fileStart+r.byteLength>=e?(a.debug("MultiBufferStream","Found position in existing buffer #"+n),n):-1},l.prototype.findEndContiguousBuf=function(t){var e,i,s,r=void 0!==t?t:this.bufferIndex;if(i=this.buffers[r],this.buffers.length>r+1)for(e=r+1;e<this.buffers.length&&(s=this.buffers[e]).fileStart===i.fileStart+i.byteLength;e++)i=s;return i.fileStart+i.byteLength},l.prototype.getEndFilePositionAfter=function(t){var e=this.findPosition(!0,t,!1);return-1!==e?this.findEndContiguousBuf(e):t},l.prototype.addUsedBytes=function(t){this.buffer.usedBytes+=t,this.logBufferLevel()},l.prototype.setAllUsedBytes=function(){this.buffer.usedBytes=this.buffer.byteLength,this.logBufferLevel()},l.prototype.seek=function(t,e,i){var s;return-1!==(s=this.findPosition(e,t,i))?(this.buffer=this.buffers[s],this.bufferIndex=s,this.position=t-this.buffer.fileStart,a.debug("MultiBufferStream","Repositioning parser at buffer position: "+this.position),!0):(a.debug("MultiBufferStream","Position "+t+" not found in buffered data"),!1)},l.prototype.getPosition=function(){if(-1===this.bufferIndex||null===this.buffers[this.bufferIndex])throw"Error accessing position in the MultiBufferStream";return this.buffers[this.bufferIndex].fileStart+this.position},l.prototype.getLength=function(){return this.byteLength},l.prototype.getEndPosition=function(){if(-1===this.bufferIndex||null===this.buffers[this.bufferIndex])throw"Error accessing position in the MultiBufferStream";return this.buffers[this.bufferIndex].fileStart+this.byteLength},e.MultiBufferStream=l;var d=function(){var t=[];t[3]="ES_Descriptor",t[4]="DecoderConfigDescriptor",t[5]="DecoderSpecificInfo",t[6]="SLConfigDescriptor",this.getDescriptorName=function(e){return t[e]};var e=this,i={};return this.parseOneDescriptor=function(e){var s,r,n,o=0;for(s=e.readUint8(),n=e.readUint8();128&n;)o=(127&n)<<7,n=e.readUint8();return o+=127&n,a.debug("MPEG4DescriptorParser","Found "+(t[s]||"Descriptor "+s)+", size "+o+" at position "+e.getPosition()),(r=t[s]?new i[t[s]](o):new i.Descriptor(o)).parse(e),r},i.Descriptor=function(t,e){this.tag=t,this.size=e,this.descs=[]},i.Descriptor.prototype.parse=function(t){this.data=t.readUint8Array(this.size)},i.Descriptor.prototype.findDescriptor=function(t){for(var e=0;e<this.descs.length;e++)if(this.descs[e].tag==t)return this.descs[e];return null},i.Descriptor.prototype.parseRemainingDescriptors=function(t){for(var i=t.position;t.position<i+this.size;){var s=e.parseOneDescriptor(t);this.descs.push(s)}},i.ES_Descriptor=function(t){i.Descriptor.call(this,3,t)},i.ES_Descriptor.prototype=new i.Descriptor,i.ES_Descriptor.prototype.parse=function(t){if(this.ES_ID=t.readUint16(),this.flags=t.readUint8(),this.size-=3,128&this.flags?(this.dependsOn_ES_ID=t.readUint16(),this.size-=2):this.dependsOn_ES_ID=0,64&this.flags){var e=t.readUint8();this.URL=t.readString(e),this.size-=e+1}else this.URL="";32&this.flags?(this.OCR_ES_ID=t.readUint16(),this.size-=2):this.OCR_ES_ID=0,this.parseRemainingDescriptors(t)},i.ES_Descriptor.prototype.getOTI=function(t){var e=this.findDescriptor(4);return e?e.oti:0},i.ES_Descriptor.prototype.getAudioConfig=function(t){var e=this.findDescriptor(4);if(!e)return null;var i=e.findDescriptor(5);if(i&&i.data){var s=(248&i.data[0])>>3;return 31===s&&i.data.length>=2&&(s=32+((7&i.data[0])<<3)+((224&i.data[1])>>5)),s}return null},i.DecoderConfigDescriptor=function(t){i.Descriptor.call(this,4,t)},i.DecoderConfigDescriptor.prototype=new i.Descriptor,i.DecoderConfigDescriptor.prototype.parse=function(t){this.oti=t.readUint8(),this.streamType=t.readUint8(),this.bufferSize=t.readUint24(),this.maxBitrate=t.readUint32(),this.avgBitrate=t.readUint32(),this.size-=13,this.parseRemainingDescriptors(t)},i.DecoderSpecificInfo=function(t){i.Descriptor.call(this,5,t)},i.DecoderSpecificInfo.prototype=new i.Descriptor,i.SLConfigDescriptor=function(t){i.Descriptor.call(this,6,t)},i.SLConfigDescriptor.prototype=new i.Descriptor,this};e.MPEG4DescriptorParser=d;var u={ERR_INVALID_DATA:-1,ERR_NOT_ENOUGH_DATA:0,OK:1,BASIC_BOXES:["mdat","idat","free","skip","meco","strk"],FULL_BOXES:["hmhd","nmhd","iods","xml ","bxml","ipro","mere"],CONTAINER_BOXES:[["moov",["trak","pssh"]],["trak"],["edts"],["mdia"],["minf"],["dinf"],["stbl",["sgpd","sbgp"]],["mvex",["trex"]],["moof",["traf"]],["traf",["trun","sgpd","sbgp"]],["vttc"],["tref"],["iref"],["mfra",["tfra"]],["meco"],["hnti"],["hinf"],["strk"],["strd"],["sinf"],["rinf"],["schi"],["trgr"],["udta",["kind"]],["iprp",["ipma"]],["ipco"]],boxCodes:[],fullBoxCodes:[],containerBoxCodes:[],sampleEntryCodes:{},sampleGroupEntryCodes:[],trackGroupTypes:[],UUIDBoxes:{},UUIDs:[],initialize:function(){u.FullBox.prototype=new u.Box,u.ContainerBox.prototype=new u.Box,u.SampleEntry.prototype=new u.Box,u.TrackGroupTypeBox.prototype=new u.FullBox,u.BASIC_BOXES.forEach((function(t){u.createBoxCtor(t)})),u.FULL_BOXES.forEach((function(t){u.createFullBoxCtor(t)})),u.CONTAINER_BOXES.forEach((function(t){u.createContainerBoxCtor(t[0],null,t[1])}))},Box:function(t,e,i){this.type=t,this.size=e,this.uuid=i},FullBox:function(t,e,i){u.Box.call(this,t,e,i),this.flags=0,this.version=0},ContainerBox:function(t,e,i){u.Box.call(this,t,e,i),this.boxes=[]},SampleEntry:function(t,e,i,s){u.ContainerBox.call(this,t,e),this.hdr_size=i,this.start=s},SampleGroupEntry:function(t){this.grouping_type=t},TrackGroupTypeBox:function(t,e){u.FullBox.call(this,t,e)},createBoxCtor:function(t,e){u.boxCodes.push(t),u[t+"Box"]=function(e){u.Box.call(this,t,e)},u[t+"Box"].prototype=new u.Box,e&&(u[t+"Box"].prototype.parse=e)},createFullBoxCtor:function(t,e){u[t+"Box"]=function(e){u.FullBox.call(this,t,e)},u[t+"Box"].prototype=new u.FullBox,u[t+"Box"].prototype.parse=function(t){this.parseFullHeader(t),e&&e.call(this,t)}},addSubBoxArrays:function(t){if(t){this.subBoxNames=t;for(var e=t.length,i=0;i<e;i++)this[t[i]+"s"]=[]}},createContainerBoxCtor:function(t,e,i){u[t+"Box"]=function(e){u.ContainerBox.call(this,t,e),u.addSubBoxArrays.call(this,i)},u[t+"Box"].prototype=new u.ContainerBox,e&&(u[t+"Box"].prototype.parse=e)},createMediaSampleEntryCtor:function(t,e,i){u.sampleEntryCodes[t]=[],u[t+"SampleEntry"]=function(t,e){u.SampleEntry.call(this,t,e),u.addSubBoxArrays.call(this,i)},u[t+"SampleEntry"].prototype=new u.SampleEntry,e&&(u[t+"SampleEntry"].prototype.parse=e)},createSampleEntryCtor:function(t,e,i,s){u.sampleEntryCodes[t].push(e),u[e+"SampleEntry"]=function(i){u[t+"SampleEntry"].call(this,e,i),u.addSubBoxArrays.call(this,s)},u[e+"SampleEntry"].prototype=new u[t+"SampleEntry"],i&&(u[e+"SampleEntry"].prototype.parse=i)},createEncryptedSampleEntryCtor:function(t,e,i){u.createSampleEntryCtor.call(this,t,e,i,["sinf"])},createSampleGroupCtor:function(t,e){u[t+"SampleGroupEntry"]=function(e){u.SampleGroupEntry.call(this,t,e)},u[t+"SampleGroupEntry"].prototype=new u.SampleGroupEntry,e&&(u[t+"SampleGroupEntry"].prototype.parse=e)},createTrackGroupCtor:function(t,e){u[t+"TrackGroupTypeBox"]=function(e){u.TrackGroupTypeBox.call(this,t,e)},u[t+"TrackGroupTypeBox"].prototype=new u.TrackGroupTypeBox,e&&(u[t+"TrackGroupTypeBox"].prototype.parse=e)},createUUIDBox:function(t,e,i,s){u.UUIDs.push(t),u.UUIDBoxes[t]=function(s){e?u.FullBox.call(this,"uuid",s,t):i?u.ContainerBox.call(this,"uuid",s,t):u.Box.call(this,"uuid",s,t)},u.UUIDBoxes[t].prototype=e?new u.FullBox:i?new u.ContainerBox:new u.Box,s&&(u.UUIDBoxes[t].prototype.parse=e?function(t){this.parseFullHeader(t),s&&s.call(this,t)}:s)}};u.initialize(),u.TKHD_FLAG_ENABLED=1,u.TKHD_FLAG_IN_MOVIE=2,u.TKHD_FLAG_IN_PREVIEW=4,u.TFHD_FLAG_BASE_DATA_OFFSET=1,u.TFHD_FLAG_SAMPLE_DESC=2,u.TFHD_FLAG_SAMPLE_DUR=8,u.TFHD_FLAG_SAMPLE_SIZE=16,u.TFHD_FLAG_SAMPLE_FLAGS=32,u.TFHD_FLAG_DUR_EMPTY=65536,u.TFHD_FLAG_DEFAULT_BASE_IS_MOOF=131072,u.TRUN_FLAGS_DATA_OFFSET=1,u.TRUN_FLAGS_FIRST_FLAG=4,u.TRUN_FLAGS_DURATION=256,u.TRUN_FLAGS_SIZE=512,u.TRUN_FLAGS_FLAGS=1024,u.TRUN_FLAGS_CTS_OFFSET=2048,u.Box.prototype.add=function(t){return this.addBox(new u[t+"Box"])},u.Box.prototype.addBox=function(t){return this.boxes.push(t),this[t.type+"s"]?this[t.type+"s"].push(t):this[t.type]=t,t},u.Box.prototype.set=function(t,e){return this[t]=e,this},u.Box.prototype.addEntry=function(t,e){var i=e||"entries";return this[i]||(this[i]=[]),this[i].push(t),this},e.BoxParser=u,u.parseUUID=function(t){return u.parseHex16(t)},u.parseHex16=function(t){for(var e="",i=0;i<16;i++){var s=t.readUint8().toString(16);e+=1===s.length?"0"+s:s}return e},u.parseOneBox=function(t,e,i){var s,r,n,o=t.getPosition(),h=0;if(t.getEndPosition()-o<8)return a.debug("BoxParser","Not enough data in stream to parse the type and size of the box"),{code:u.ERR_NOT_ENOUGH_DATA};if(i&&i<8)return a.debug("BoxParser","Not enough bytes left in the parent box to parse a new box"),{code:u.ERR_NOT_ENOUGH_DATA};var l=t.readUint32(),d=t.readString(4),p=d;if(a.debug("BoxParser","Found box of type '"+d+"' and size "+l+" at position "+o),h=8,"uuid"==d){if(t.getEndPosition()-t.getPosition()<16||i-h<16)return t.seek(o),a.debug("BoxParser","Not enough bytes left in the parent box to parse a UUID box"),{code:u.ERR_NOT_ENOUGH_DATA};h+=16,p=n=u.parseUUID(t)}if(1==l){if(t.getEndPosition()-t.getPosition()<8||i&&i-h<8)return t.seek(o),a.warn("BoxParser",'Not enough data in stream to parse the extended size of the "'+d+'" box'),{code:u.ERR_NOT_ENOUGH_DATA};l=t.readUint64(),h+=8}else if(0===l)if(i)l=i;else if("mdat"!==d)return a.error("BoxParser","Unlimited box size not supported for type: '"+d+"'"),s=new u.Box(d,l),{code:u.OK,box:s,size:s.size};return 0!==l&&l<h?(a.error("BoxParser","Box of type "+d+" has an invalid size "+l+" (too small to be a box)"),{code:u.ERR_NOT_ENOUGH_DATA,type:d,size:l,hdr_size:h,start:o}):0!==l&&i&&l>i?(a.error("BoxParser","Box of type '"+d+"' has a size "+l+" greater than its container size "+i),{code:u.ERR_NOT_ENOUGH_DATA,type:d,size:l,hdr_size:h,start:o}):0!==l&&o+l>t.getEndPosition()?(t.seek(o),a.info("BoxParser","Not enough data in stream to parse the entire '"+d+"' box"),{code:u.ERR_NOT_ENOUGH_DATA,type:d,size:l,hdr_size:h,start:o}):e?{code:u.OK,type:d,size:l,hdr_size:h,start:o}:(u[d+"Box"]?s=new u[d+"Box"](l):"uuid"!==d?(a.warn("BoxParser","Unknown box type: '"+d+"'"),(s=new u.Box(d,l)).has_unparsed_data=!0):u.UUIDBoxes[n]?s=new u.UUIDBoxes[n](l):(a.warn("BoxParser","Unknown uuid type: '"+n+"'"),(s=new u.Box(d,l)).uuid=n,s.has_unparsed_data=!0),s.hdr_size=h,s.start=o,s.write===u.Box.prototype.write&&"mdat"!==s.type&&(a.info("BoxParser","'"+p+"' box writing not yet implemented, keeping unparsed data in memory for later write"),s.parseDataAndRewind(t)),s.parse(t),(r=t.getPosition()-(s.start+s.size))<0?(a.warn("BoxParser","Parsing of box '"+p+"' did not read the entire indicated box data size (missing "+-r+" bytes), seeking forward"),t.seek(s.start+s.size)):r>0&&(a.error("BoxParser","Parsing of box '"+p+"' read "+r+" more bytes than the indicated box data size, seeking backwards"),0!==s.size&&t.seek(s.start+s.size)),{code:u.OK,box:s,size:s.size})},u.Box.prototype.parse=function(t){"mdat"!=this.type?this.data=t.readUint8Array(this.size-this.hdr_size):0===this.size?t.seek(t.getEndPosition()):t.seek(this.start+this.size)},u.Box.prototype.parseDataAndRewind=function(t){this.data=t.readUint8Array(this.size-this.hdr_size),t.position-=this.size-this.hdr_size},u.FullBox.prototype.parseDataAndRewind=function(t){this.parseFullHeader(t),this.data=t.readUint8Array(this.size-this.hdr_size),this.hdr_size-=4,t.position-=this.size-this.hdr_size},u.FullBox.prototype.parseFullHeader=function(t){this.version=t.readUint8(),this.flags=t.readUint24(),this.hdr_size+=4},u.FullBox.prototype.parse=function(t){this.parseFullHeader(t),this.data=t.readUint8Array(this.size-this.hdr_size)},u.ContainerBox.prototype.parse=function(t){for(var e,i;t.getPosition()<this.start+this.size;){if((e=u.parseOneBox(t,!1,this.size-(t.getPosition()-this.start))).code!==u.OK)return;if(i=e.box,this.boxes.push(i),this.subBoxNames&&-1!=this.subBoxNames.indexOf(i.type))this[this.subBoxNames[this.subBoxNames.indexOf(i.type)]+"s"].push(i);else{var s="uuid"!==i.type?i.type:i.uuid;this[s]?a.warn("Box of type "+s+" already stored in field of this type"):this[s]=i}}},u.Box.prototype.parseLanguage=function(t){this.language=t.readUint16();var e=[];e[0]=this.language>>10&31,e[1]=this.language>>5&31,e[2]=31&this.language,this.languageString=String.fromCharCode(e[0]+96,e[1]+96,e[2]+96)},u.SAMPLE_ENTRY_TYPE_VISUAL="Visual",u.SAMPLE_ENTRY_TYPE_AUDIO="Audio",u.SAMPLE_ENTRY_TYPE_HINT="Hint",u.SAMPLE_ENTRY_TYPE_METADATA="Metadata",u.SAMPLE_ENTRY_TYPE_SUBTITLE="Subtitle",u.SAMPLE_ENTRY_TYPE_SYSTEM="System",u.SAMPLE_ENTRY_TYPE_TEXT="Text",u.SampleEntry.prototype.parseHeader=function(t){t.readUint8Array(6),this.data_reference_index=t.readUint16(),this.hdr_size+=8},u.SampleEntry.prototype.parse=function(t){this.parseHeader(t),this.data=t.readUint8Array(this.size-this.hdr_size)},u.SampleEntry.prototype.parseDataAndRewind=function(t){this.parseHeader(t),this.data=t.readUint8Array(this.size-this.hdr_size),this.hdr_size-=8,t.position-=this.size-this.hdr_size},u.SampleEntry.prototype.parseFooter=function(t){u.ContainerBox.prototype.parse.call(this,t)},u.createMediaSampleEntryCtor(u.SAMPLE_ENTRY_TYPE_HINT),u.createMediaSampleEntryCtor(u.SAMPLE_ENTRY_TYPE_METADATA),u.createMediaSampleEntryCtor(u.SAMPLE_ENTRY_TYPE_SUBTITLE),u.createMediaSampleEntryCtor(u.SAMPLE_ENTRY_TYPE_SYSTEM),u.createMediaSampleEntryCtor(u.SAMPLE_ENTRY_TYPE_TEXT),u.createMediaSampleEntryCtor(u.SAMPLE_ENTRY_TYPE_VISUAL,(function(t){var e;this.parseHeader(t),t.readUint16(),t.readUint16(),t.readUint32Array(3),this.width=t.readUint16(),this.height=t.readUint16(),this.horizresolution=t.readUint32(),this.vertresolution=t.readUint32(),t.readUint32(),this.frame_count=t.readUint16(),e=Math.min(31,t.readUint8()),this.compressorname=t.readString(e),e<31&&t.readString(31-e),this.depth=t.readUint16(),t.readUint16(),this.parseFooter(t)})),u.createMediaSampleEntryCtor(u.SAMPLE_ENTRY_TYPE_AUDIO,(function(t){this.parseHeader(t),t.readUint32Array(2),this.channel_count=t.readUint16(),this.samplesize=t.readUint16(),t.readUint16(),t.readUint16(),this.samplerate=t.readUint32()/65536,this.parseFooter(t)})),u.createSampleEntryCtor(u.SAMPLE_ENTRY_TYPE_VISUAL,"avc1"),u.createSampleEntryCtor(u.SAMPLE_ENTRY_TYPE_VISUAL,"avc2"),u.createSampleEntryCtor(u.SAMPLE_ENTRY_TYPE_VISUAL,"avc3"),u.createSampleEntryCtor(u.SAMPLE_ENTRY_TYPE_VISUAL,"avc4"),u.createSampleEntryCtor(u.SAMPLE_ENTRY_TYPE_VISUAL,"av01"),u.createSampleEntryCtor(u.SAMPLE_ENTRY_TYPE_VISUAL,"hvc1"),u.createSampleEntryCtor(u.SAMPLE_ENTRY_TYPE_VISUAL,"hev1"),u.createSampleEntryCtor(u.SAMPLE_ENTRY_TYPE_VISUAL,"vvc1"),u.createSampleEntryCtor(u.SAMPLE_ENTRY_TYPE_VISUAL,"vvi1"),u.createSampleEntryCtor(u.SAMPLE_ENTRY_TYPE_VISUAL,"vvs1"),u.createSampleEntryCtor(u.SAMPLE_ENTRY_TYPE_VISUAL,"vvcN"),u.createSampleEntryCtor(u.SAMPLE_ENTRY_TYPE_VISUAL,"vp08"),u.createSampleEntryCtor(u.SAMPLE_ENTRY_TYPE_VISUAL,"vp09"),u.createSampleEntryCtor(u.SAMPLE_ENTRY_TYPE_AUDIO,"mp4a"),u.createSampleEntryCtor(u.SAMPLE_ENTRY_TYPE_AUDIO,"ac-3"),u.createSampleEntryCtor(u.SAMPLE_ENTRY_TYPE_AUDIO,"ec-3"),u.createSampleEntryCtor(u.SAMPLE_ENTRY_TYPE_AUDIO,"Opus"),u.createEncryptedSampleEntryCtor(u.SAMPLE_ENTRY_TYPE_VISUAL,"encv"),u.createEncryptedSampleEntryCtor(u.SAMPLE_ENTRY_TYPE_AUDIO,"enca"),u.createEncryptedSampleEntryCtor(u.SAMPLE_ENTRY_TYPE_SUBTITLE,"encu"),u.createEncryptedSampleEntryCtor(u.SAMPLE_ENTRY_TYPE_SYSTEM,"encs"),u.createEncryptedSampleEntryCtor(u.SAMPLE_ENTRY_TYPE_TEXT,"enct"),u.createEncryptedSampleEntryCtor(u.SAMPLE_ENTRY_TYPE_METADATA,"encm"),u.createBoxCtor("a1lx",(function(t){var e=16*(1+(1&(1&t.readUint8())));this.layer_size=[];for(var i=0;i<3;i++)this.layer_size[i]=16==e?t.readUint16():t.readUint32()})),u.createBoxCtor("a1op",(function(t){this.op_index=t.readUint8()})),u.createFullBoxCtor("auxC",(function(t){this.aux_type=t.readCString();var e=this.size-this.hdr_size-(this.aux_type.length+1);this.aux_subtype=t.readUint8Array(e)})),u.createBoxCtor("av1C",(function(t){var e=t.readUint8();if(e>>7&!1)a.error("av1C marker problem");else if(this.version=127&e,1===this.version)if(e=t.readUint8(),this.seq_profile=e>>5&7,this.seq_level_idx_0=31&e,e=t.readUint8(),this.seq_tier_0=e>>7&1,this.high_bitdepth=e>>6&1,this.twelve_bit=e>>5&1,this.monochrome=e>>4&1,this.chroma_subsampling_x=e>>3&1,this.chroma_subsampling_y=e>>2&1,this.chroma_sample_position=3&e,e=t.readUint8(),this.reserved_1=e>>5&7,0===this.reserved_1){if(this.initial_presentation_delay_present=e>>4&1,1===this.initial_presentation_delay_present)this.initial_presentation_delay_minus_one=15&e;else if(this.reserved_2=15&e,0!==this.reserved_2)return void a.error("av1C reserved_2 parsing problem");var i=this.size-this.hdr_size-4;this.configOBUs=t.readUint8Array(i)}else a.error("av1C reserved_1 parsing problem");else a.error("av1C version "+this.version+" not supported")})),u.createBoxCtor("avcC",(function(t){var e,i;for(this.configurationVersion=t.readUint8(),this.AVCProfileIndication=t.readUint8(),this.profile_compatibility=t.readUint8(),this.AVCLevelIndication=t.readUint8(),this.lengthSizeMinusOne=3&t.readUint8(),this.nb_SPS_nalus=31&t.readUint8(),i=this.size-this.hdr_size-6,this.SPS=[],e=0;e<this.nb_SPS_nalus;e++)this.SPS[e]={},this.SPS[e].length=t.readUint16(),this.SPS[e].nalu=t.readUint8Array(this.SPS[e].length),i-=2+this.SPS[e].length;for(this.nb_PPS_nalus=t.readUint8(),i--,this.PPS=[],e=0;e<this.nb_PPS_nalus;e++)this.PPS[e]={},this.PPS[e].length=t.readUint16(),this.PPS[e].nalu=t.readUint8Array(this.PPS[e].length),i-=2+this.PPS[e].length;i>0&&(this.ext=t.readUint8Array(i))})),u.createBoxCtor("btrt",(function(t){this.bufferSizeDB=t.readUint32(),this.maxBitrate=t.readUint32(),this.avgBitrate=t.readUint32()})),u.createBoxCtor("clap",(function(t){this.cleanApertureWidthN=t.readUint32(),this.cleanApertureWidthD=t.readUint32(),this.cleanApertureHeightN=t.readUint32(),this.cleanApertureHeightD=t.readUint32(),this.horizOffN=t.readUint32(),this.horizOffD=t.readUint32(),this.vertOffN=t.readUint32(),this.vertOffD=t.readUint32()})),u.createBoxCtor("clli",(function(t){this.max_content_light_level=t.readUint16(),this.max_pic_average_light_level=t.readUint16()})),u.createFullBoxCtor("co64",(function(t){var e,i;if(e=t.readUint32(),this.chunk_offsets=[],0===this.version)for(i=0;i<e;i++)this.chunk_offsets.push(t.readUint64())})),u.createFullBoxCtor("CoLL",(function(t){this.maxCLL=t.readUint16(),this.maxFALL=t.readUint16()})),u.createBoxCtor("colr",(function(t){if(this.colour_type=t.readString(4),"nclx"===this.colour_type){this.colour_primaries=t.readUint16(),this.transfer_characteristics=t.readUint16(),this.matrix_coefficients=t.readUint16();var e=t.readUint8();this.full_range_flag=e>>7}else("rICC"===this.colour_type||"prof"===this.colour_type)&&(this.ICC_profile=t.readUint8Array(this.size-4))})),u.createFullBoxCtor("cprt",(function(t){this.parseLanguage(t),this.notice=t.readCString()})),u.createFullBoxCtor("cslg",(function(t){0===this.version&&(this.compositionToDTSShift=t.readInt32(),this.leastDecodeToDisplayDelta=t.readInt32(),this.greatestDecodeToDisplayDelta=t.readInt32(),this.compositionStartTime=t.readInt32(),this.compositionEndTime=t.readInt32())})),u.createFullBoxCtor("ctts",(function(t){var e,i;if(e=t.readUint32(),this.sample_counts=[],this.sample_offsets=[],0===this.version)for(i=0;i<e;i++){this.sample_counts.push(t.readUint32());var s=t.readInt32();s<0&&a.warn("BoxParser","ctts box uses negative values without using version 1"),this.sample_offsets.push(s)}else if(1==this.version)for(i=0;i<e;i++)this.sample_counts.push(t.readUint32()),this.sample_offsets.push(t.readInt32())})),u.createBoxCtor("dac3",(function(t){var e=t.readUint8(),i=t.readUint8(),s=t.readUint8();this.fscod=e>>6,this.bsid=e>>1&31,this.bsmod=(1&e)<<2|i>>6&3,this.acmod=i>>3&7,this.lfeon=i>>2&1,this.bit_rate_code=3&i|s>>5&7})),u.createBoxCtor("dec3",(function(t){var e=t.readUint16();this.data_rate=e>>3,this.num_ind_sub=7&e,this.ind_subs=[];for(var i=0;i<this.num_ind_sub+1;i++){var s={};this.ind_subs.push(s);var r=t.readUint8(),a=t.readUint8(),n=t.readUint8();s.fscod=r>>6,s.bsid=r>>1&31,s.bsmod=(1&r)<<4|a>>4&15,s.acmod=a>>1&7,s.lfeon=1&a,s.num_dep_sub=n>>1&15,s.num_dep_sub>0&&(s.chan_loc=(1&n)<<8|t.readUint8())}})),u.createFullBoxCtor("dfLa",(function(t){var e=[],i=["STREAMINFO","PADDING","APPLICATION","SEEKTABLE","VORBIS_COMMENT","CUESHEET","PICTURE","RESERVED"];for(this.parseFullHeader(t);;){var s=t.readUint8(),r=Math.min(127&s,i.length-1);if(r?t.readUint8Array(t.readUint24()):(t.readUint8Array(13),this.samplerate=t.readUint32()>>12,t.readUint8Array(20)),e.push(i[r]),128&s)break}this.numMetadataBlocks=e.length+" ("+e.join(", ")+")"})),u.createBoxCtor("dimm",(function(t){this.bytessent=t.readUint64()})),u.createBoxCtor("dmax",(function(t){this.time=t.readUint32()})),u.createBoxCtor("dmed",(function(t){this.bytessent=t.readUint64()})),u.createBoxCtor("dOps",(function(t){if(this.Version=t.readUint8(),this.OutputChannelCount=t.readUint8(),this.PreSkip=t.readUint16(),this.InputSampleRate=t.readUint32(),this.OutputGain=t.readInt16(),this.ChannelMappingFamily=t.readUint8(),0!==this.ChannelMappingFamily){this.StreamCount=t.readUint8(),this.CoupledCount=t.readUint8(),this.ChannelMapping=[];for(var e=0;e<this.OutputChannelCount;e++)this.ChannelMapping[e]=t.readUint8()}})),u.createFullBoxCtor("dref",(function(t){var e,i;this.entries=[];for(var s=t.readUint32(),r=0;r<s;r++){if((e=u.parseOneBox(t,!1,this.size-(t.getPosition()-this.start))).code!==u.OK)return;i=e.box,this.entries.push(i)}})),u.createBoxCtor("drep",(function(t){this.bytessent=t.readUint64()})),u.createFullBoxCtor("elng",(function(t){this.extended_language=t.readString(this.size-this.hdr_size)})),u.createFullBoxCtor("elst",(function(t){this.entries=[];for(var e=t.readUint32(),i=0;i<e;i++){var s={};this.entries.push(s),1===this.version?(s.segment_duration=t.readUint64(),s.media_time=t.readInt64()):(s.segment_duration=t.readUint32(),s.media_time=t.readInt32()),s.media_rate_integer=t.readInt16(),s.media_rate_fraction=t.readInt16()}})),u.createFullBoxCtor("emsg",(function(t){1==this.version?(this.timescale=t.readUint32(),this.presentation_time=t.readUint64(),this.event_duration=t.readUint32(),this.id=t.readUint32(),this.scheme_id_uri=t.readCString(),this.value=t.readCString()):(this.scheme_id_uri=t.readCString(),this.value=t.readCString(),this.timescale=t.readUint32(),this.presentation_time_delta=t.readUint32(),this.event_duration=t.readUint32(),this.id=t.readUint32());var e=this.size-this.hdr_size-(16+(this.scheme_id_uri.length+1)+(this.value.length+1));1==this.version&&(e-=4),this.message_data=t.readUint8Array(e)})),u.createFullBoxCtor("esds",(function(t){var e=t.readUint8Array(this.size-this.hdr_size);if(void 0!==d){var i=new d;this.esd=i.parseOneDescriptor(new o(e.buffer,0,o.BIG_ENDIAN))}})),u.createBoxCtor("fiel",(function(t){this.fieldCount=t.readUint8(),this.fieldOrdering=t.readUint8()})),u.createBoxCtor("frma",(function(t){this.data_format=t.readString(4)})),u.createBoxCtor("ftyp",(function(t){var e=this.size-this.hdr_size;this.major_brand=t.readString(4),this.minor_version=t.readUint32(),e-=8,this.compatible_brands=[];for(var i=0;e>=4;)this.compatible_brands[i]=t.readString(4),e-=4,i++})),u.createFullBoxCtor("hdlr",(function(t){0===this.version&&(t.readUint32(),this.handler=t.readString(4),t.readUint32Array(3),this.name=t.readString(this.size-this.hdr_size-20),"\0"===this.name[this.name.length-1]&&(this.name=this.name.slice(0,-1)))})),u.createBoxCtor("hvcC",(function(t){var e,i,s,r;this.configurationVersion=t.readUint8(),r=t.readUint8(),this.general_profile_space=r>>6,this.general_tier_flag=(32&r)>>5,this.general_profile_idc=31&r,this.general_profile_compatibility=t.readUint32(),this.general_constraint_indicator=t.readUint8Array(6),this.general_level_idc=t.readUint8(),this.min_spatial_segmentation_idc=4095&t.readUint16(),this.parallelismType=3&t.readUint8(),this.chroma_format_idc=3&t.readUint8(),this.bit_depth_luma_minus8=7&t.readUint8(),this.bit_depth_chroma_minus8=7&t.readUint8(),this.avgFrameRate=t.readUint16(),r=t.readUint8(),this.constantFrameRate=r>>6,this.numTemporalLayers=(13&r)>>3,this.temporalIdNested=(4&r)>>2,this.lengthSizeMinusOne=3&r,this.nalu_arrays=[];var a=t.readUint8();for(e=0;e<a;e++){var n=[];this.nalu_arrays.push(n),r=t.readUint8(),n.completeness=(128&r)>>7,n.nalu_type=63&r;var o=t.readUint16();for(i=0;i<o;i++){var h={};n.push(h),s=t.readUint16(),h.data=t.readUint8Array(s)}}})),u.createFullBoxCtor("iinf",(function(t){var e;0===this.version?this.entry_count=t.readUint16():this.entry_count=t.readUint32(),this.item_infos=[];for(var i=0;i<this.entry_count;i++){if((e=u.parseOneBox(t,!1,this.size-(t.getPosition()-this.start))).code!==u.OK)return;"infe"!==e.box.type&&a.error("BoxParser","Expected 'infe' box, got "+e.box.type),this.item_infos[i]=e.box}})),u.createFullBoxCtor("iloc",(function(t){var e;e=t.readUint8(),this.offset_size=e>>4&15,this.length_size=15&e,e=t.readUint8(),this.base_offset_size=e>>4&15,1===this.version||2===this.version?this.index_size=15&e:this.index_size=0,this.items=[];var i=0;if(this.version<2)i=t.readUint16();else{if(2!==this.version)throw"version of iloc box not supported";i=t.readUint32()}for(var s=0;s<i;s++){var r={};if(this.items.push(r),this.version<2)r.item_ID=t.readUint16();else{if(2!==this.version)throw"version of iloc box not supported";r.item_ID=t.readUint16()}switch(1===this.version||2===this.version?r.construction_method=15&t.readUint16():r.construction_method=0,r.data_reference_index=t.readUint16(),this.base_offset_size){case 0:r.base_offset=0;break;case 4:r.base_offset=t.readUint32();break;case 8:r.base_offset=t.readUint64();break;default:throw"Error reading base offset size"}var a=t.readUint16();r.extents=[];for(var n=0;n<a;n++){var o={};if(r.extents.push(o),1===this.version||2===this.version)switch(this.index_size){case 0:o.extent_index=0;break;case 4:o.extent_index=t.readUint32();break;case 8:o.extent_index=t.readUint64();break;default:throw"Error reading extent index"}switch(this.offset_size){case 0:o.extent_offset=0;break;case 4:o.extent_offset=t.readUint32();break;case 8:o.extent_offset=t.readUint64();break;default:throw"Error reading extent index"}switch(this.length_size){case 0:o.extent_length=0;break;case 4:o.extent_length=t.readUint32();break;case 8:o.extent_length=t.readUint64();break;default:throw"Error reading extent index"}}}})),u.createBoxCtor("imir",(function(t){var e=t.readUint8();this.reserved=e>>7,this.axis=1&e})),u.createFullBoxCtor("infe",(function(t){if(0!==this.version&&1!==this.version||(this.item_ID=t.readUint16(),this.item_protection_index=t.readUint16(),this.item_name=t.readCString(),this.content_type=t.readCString(),this.content_encoding=t.readCString()),1===this.version)return this.extension_type=t.readString(4),a.warn("BoxParser","Cannot parse extension type"),void t.seek(this.start+this.size);this.version>=2&&(2===this.version?this.item_ID=t.readUint16():3===this.version&&(this.item_ID=t.readUint32()),this.item_protection_index=t.readUint16(),this.item_type=t.readString(4),this.item_name=t.readCString(),"mime"===this.item_type?(this.content_type=t.readCString(),this.content_encoding=t.readCString()):"uri "===this.item_type&&(this.item_uri_type=t.readCString()))})),u.createFullBoxCtor("ipma",(function(t){var e,i;for(entry_count=t.readUint32(),this.associations=[],e=0;e<entry_count;e++){var s={};this.associations.push(s),this.version<1?s.id=t.readUint16():s.id=t.readUint32();var r=t.readUint8();for(s.props=[],i=0;i<r;i++){var a=t.readUint8(),n={};s.props.push(n),n.essential=(128&a)>>7==1,1&this.flags?n.property_index=(127&a)<<8|t.readUint8():n.property_index=127&a}}})),u.createFullBoxCtor("iref",(function(t){var e,i;for(this.references=[];t.getPosition()<this.start+this.size;){if((e=u.parseOneBox(t,!0,this.size-(t.getPosition()-this.start))).code!==u.OK)return;(i=0===this.version?new u.SingleItemTypeReferenceBox(e.type,e.size,e.hdr_size,e.start):new u.SingleItemTypeReferenceBoxLarge(e.type,e.size,e.hdr_size,e.start)).write===u.Box.prototype.write&&"mdat"!==i.type&&(a.warn("BoxParser",i.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),i.parseDataAndRewind(t)),i.parse(t),this.references.push(i)}})),u.createBoxCtor("irot",(function(t){this.angle=3&t.readUint8()})),u.createFullBoxCtor("ispe",(function(t){this.image_width=t.readUint32(),this.image_height=t.readUint32()})),u.createFullBoxCtor("kind",(function(t){this.schemeURI=t.readCString(),this.value=t.readCString()})),u.createFullBoxCtor("leva",(function(t){var e=t.readUint8();this.levels=[];for(var i=0;i<e;i++){var s={};this.levels[i]=s,s.track_ID=t.readUint32();var r=t.readUint8();switch(s.padding_flag=r>>7,s.assignment_type=127&r,s.assignment_type){case 0:s.grouping_type=t.readString(4);break;case 1:s.grouping_type=t.readString(4),s.grouping_type_parameter=t.readUint32();break;case 2:case 3:break;case 4:s.sub_track_id=t.readUint32();break;default:a.warn("BoxParser","Unknown leva assignement type")}}})),u.createBoxCtor("lsel",(function(t){this.layer_id=t.readUint16()})),u.createBoxCtor("maxr",(function(t){this.period=t.readUint32(),this.bytes=t.readUint32()})),u.createBoxCtor("mdcv",(function(t){this.display_primaries=[],this.display_primaries[0]={},this.display_primaries[0].x=t.readUint16(),this.display_primaries[0].y=t.readUint16(),this.display_primaries[1]={},this.display_primaries[1].x=t.readUint16(),this.display_primaries[1].y=t.readUint16(),this.display_primaries[2]={},this.display_primaries[2].x=t.readUint16(),this.display_primaries[2].y=t.readUint16(),this.white_point={},this.white_point.x=t.readUint16(),this.white_point.y=t.readUint16(),this.max_display_mastering_luminance=t.readUint32(),this.min_display_mastering_luminance=t.readUint32()})),u.createFullBoxCtor("mdhd",(function(t){1==this.version?(this.creation_time=t.readUint64(),this.modification_time=t.readUint64(),this.timescale=t.readUint32(),this.duration=t.readUint64()):(this.creation_time=t.readUint32(),this.modification_time=t.readUint32(),this.timescale=t.readUint32(),this.duration=t.readUint32()),this.parseLanguage(t),t.readUint16()})),u.createFullBoxCtor("mehd",(function(t){1&this.flags&&(a.warn("BoxParser","mehd box incorrectly uses flags set to 1, converting version to 1"),this.version=1),1==this.version?this.fragment_duration=t.readUint64():this.fragment_duration=t.readUint32()})),u.createFullBoxCtor("meta",(function(t){this.boxes=[],u.ContainerBox.prototype.parse.call(this,t)})),u.createFullBoxCtor("mfhd",(function(t){this.sequence_number=t.readUint32()})),u.createFullBoxCtor("mfro",(function(t){this._size=t.readUint32()})),u.createFullBoxCtor("mvhd",(function(t){1==this.version?(this.creation_time=t.readUint64(),this.modification_time=t.readUint64(),this.timescale=t.readUint32(),this.duration=t.readUint64()):(this.creation_time=t.readUint32(),this.modification_time=t.readUint32(),this.timescale=t.readUint32(),this.duration=t.readUint32()),this.rate=t.readUint32(),this.volume=t.readUint16()>>8,t.readUint16(),t.readUint32Array(2),this.matrix=t.readUint32Array(9),t.readUint32Array(6),this.next_track_id=t.readUint32()})),u.createBoxCtor("npck",(function(t){this.packetssent=t.readUint32()})),u.createBoxCtor("nump",(function(t){this.packetssent=t.readUint64()})),u.createFullBoxCtor("padb",(function(t){var e=t.readUint32();this.padbits=[];for(var i=0;i<Math.floor((e+1)/2);i++)this.padbits=t.readUint8()})),u.createBoxCtor("pasp",(function(t){this.hSpacing=t.readUint32(),this.vSpacing=t.readUint32()})),u.createBoxCtor("payl",(function(t){this.text=t.readString(this.size-this.hdr_size)})),u.createBoxCtor("payt",(function(t){this.payloadID=t.readUint32();var e=t.readUint8();this.rtpmap_string=t.readString(e)})),u.createFullBoxCtor("pdin",(function(t){var e=(this.size-this.hdr_size)/8;this.rate=[],this.initial_delay=[];for(var i=0;i<e;i++)this.rate[i]=t.readUint32(),this.initial_delay[i]=t.readUint32()})),u.createFullBoxCtor("pitm",(function(t){0===this.version?this.item_id=t.readUint16():this.item_id=t.readUint32()})),u.createFullBoxCtor("pixi",(function(t){var e;for(this.num_channels=t.readUint8(),this.bits_per_channels=[],e=0;e<this.num_channels;e++)this.bits_per_channels[e]=t.readUint8()})),u.createBoxCtor("pmax",(function(t){this.bytes=t.readUint32()})),u.createFullBoxCtor("prft",(function(t){this.ref_track_id=t.readUint32(),this.ntp_timestamp=t.readUint64(),0===this.version?this.media_time=t.readUint32():this.media_time=t.readUint64()})),u.createFullBoxCtor("pssh",(function(t){if(this.system_id=u.parseHex16(t),this.version>0){var e=t.readUint32();this.kid=[];for(var i=0;i<e;i++)this.kid[i]=u.parseHex16(t)}var s=t.readUint32();s>0&&(this.data=t.readUint8Array(s))})),u.createFullBoxCtor("clef",(function(t){this.width=t.readUint32(),this.height=t.readUint32()})),u.createFullBoxCtor("enof",(function(t){this.width=t.readUint32(),this.height=t.readUint32()})),u.createFullBoxCtor("prof",(function(t){this.width=t.readUint32(),this.height=t.readUint32()})),u.createContainerBoxCtor("tapt",null,["clef","prof","enof"]),u.createBoxCtor("rtp ",(function(t){this.descriptionformat=t.readString(4),this.sdptext=t.readString(this.size-this.hdr_size-4)})),u.createFullBoxCtor("saio",(function(t){1&this.flags&&(this.aux_info_type=t.readUint32(),this.aux_info_type_parameter=t.readUint32());var e=t.readUint32();this.offset=[];for(var i=0;i<e;i++)0===this.version?this.offset[i]=t.readUint32():this.offset[i]=t.readUint64()})),u.createFullBoxCtor("saiz",(function(t){1&this.flags&&(this.aux_info_type=t.readUint32(),this.aux_info_type_parameter=t.readUint32()),this.default_sample_info_size=t.readUint8();var e=t.readUint32();if(this.sample_info_size=[],0===this.default_sample_info_size)for(var i=0;i<e;i++)this.sample_info_size[i]=t.readUint8()})),u.createSampleEntryCtor(u.SAMPLE_ENTRY_TYPE_METADATA,"mett",(function(t){this.parseHeader(t),this.content_encoding=t.readCString(),this.mime_format=t.readCString(),this.parseFooter(t)})),u.createSampleEntryCtor(u.SAMPLE_ENTRY_TYPE_METADATA,"metx",(function(t){this.parseHeader(t),this.content_encoding=t.readCString(),this.namespace=t.readCString(),this.schema_location=t.readCString(),this.parseFooter(t)})),u.createSampleEntryCtor(u.SAMPLE_ENTRY_TYPE_SUBTITLE,"sbtt",(function(t){this.parseHeader(t),this.content_encoding=t.readCString(),this.mime_format=t.readCString(),this.parseFooter(t)})),u.createSampleEntryCtor(u.SAMPLE_ENTRY_TYPE_SUBTITLE,"stpp",(function(t){this.parseHeader(t),this.namespace=t.readCString(),this.schema_location=t.readCString(),this.auxiliary_mime_types=t.readCString(),this.parseFooter(t)})),u.createSampleEntryCtor(u.SAMPLE_ENTRY_TYPE_SUBTITLE,"stxt",(function(t){this.parseHeader(t),this.content_encoding=t.readCString(),this.mime_format=t.readCString(),this.parseFooter(t)})),u.createSampleEntryCtor(u.SAMPLE_ENTRY_TYPE_SUBTITLE,"tx3g",(function(t){this.parseHeader(t),this.displayFlags=t.readUint32(),this.horizontal_justification=t.readInt8(),this.vertical_justification=t.readInt8(),this.bg_color_rgba=t.readUint8Array(4),this.box_record=t.readInt16Array(4),this.style_record=t.readUint8Array(12),this.parseFooter(t)})),u.createSampleEntryCtor(u.SAMPLE_ENTRY_TYPE_METADATA,"wvtt",(function(t){this.parseHeader(t),this.parseFooter(t)})),u.createSampleGroupCtor("alst",(function(t){var e,i=t.readUint16();for(this.first_output_sample=t.readUint16(),this.sample_offset=[],e=0;e<i;e++)this.sample_offset[e]=t.readUint32();var s=this.description_length-4-4*i;for(this.num_output_samples=[],this.num_total_samples=[],e=0;e<s/4;e++)this.num_output_samples[e]=t.readUint16(),this.num_total_samples[e]=t.readUint16()})),u.createSampleGroupCtor("avll",(function(t){this.layerNumber=t.readUint8(),this.accurateStatisticsFlag=t.readUint8(),this.avgBitRate=t.readUint16(),this.avgFrameRate=t.readUint16()})),u.createSampleGroupCtor("avss",(function(t){this.subSequenceIdentifier=t.readUint16(),this.layerNumber=t.readUint8();var e=t.readUint8();this.durationFlag=e>>7,this.avgRateFlag=e>>6&1,this.durationFlag&&(this.duration=t.readUint32()),this.avgRateFlag&&(this.accurateStatisticsFlag=t.readUint8(),this.avgBitRate=t.readUint16(),this.avgFrameRate=t.readUint16()),this.dependency=[];for(var i=t.readUint8(),s=0;s<i;s++){var r={};this.dependency.push(r),r.subSeqDirectionFlag=t.readUint8(),r.layerNumber=t.readUint8(),r.subSequenceIdentifier=t.readUint16()}})),u.createSampleGroupCtor("dtrt",(function(t){a.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")})),u.createSampleGroupCtor("mvif",(function(t){a.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")})),u.createSampleGroupCtor("prol",(function(t){this.roll_distance=t.readInt16()})),u.createSampleGroupCtor("rap ",(function(t){var e=t.readUint8();this.num_leading_samples_known=e>>7,this.num_leading_samples=127&e})),u.createSampleGroupCtor("rash",(function(t){if(this.operation_point_count=t.readUint16(),this.description_length!==2+(1===this.operation_point_count?2:6*this.operation_point_count)+9)a.warn("BoxParser","Mismatch in "+this.grouping_type+" sample group length"),this.data=t.readUint8Array(this.description_length-2);else{if(1===this.operation_point_count)this.target_rate_share=t.readUint16();else{this.target_rate_share=[],this.available_bitrate=[];for(var e=0;e<this.operation_point_count;e++)this.available_bitrate[e]=t.readUint32(),this.target_rate_share[e]=t.readUint16()}this.maximum_bitrate=t.readUint32(),this.minimum_bitrate=t.readUint32(),this.discard_priority=t.readUint8()}})),u.createSampleGroupCtor("roll",(function(t){this.roll_distance=t.readInt16()})),u.SampleGroupEntry.prototype.parse=function(t){a.warn("BoxParser","Unknown Sample Group type: "+this.grouping_type),this.data=t.readUint8Array(this.description_length)},u.createSampleGroupCtor("scif",(function(t){a.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")})),u.createSampleGroupCtor("scnm",(function(t){a.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")})),u.createSampleGroupCtor("seig",(function(t){this.reserved=t.readUint8();var e=t.readUint8();this.crypt_byte_block=e>>4,this.skip_byte_block=15&e,this.isProtected=t.readUint8(),this.Per_Sample_IV_Size=t.readUint8(),this.KID=u.parseHex16(t),this.constant_IV_size=0,this.constant_IV=0,1===this.isProtected&&0===this.Per_Sample_IV_Size&&(this.constant_IV_size=t.readUint8(),this.constant_IV=t.readUint8Array(this.constant_IV_size))})),u.createSampleGroupCtor("stsa",(function(t){a.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")})),u.createSampleGroupCtor("sync",(function(t){var e=t.readUint8();this.NAL_unit_type=63&e})),u.createSampleGroupCtor("tele",(function(t){var e=t.readUint8();this.level_independently_decodable=e>>7})),u.createSampleGroupCtor("tsas",(function(t){a.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")})),u.createSampleGroupCtor("tscl",(function(t){a.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")})),u.createSampleGroupCtor("vipr",(function(t){a.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")})),u.createFullBoxCtor("sbgp",(function(t){this.grouping_type=t.readString(4),1===this.version?this.grouping_type_parameter=t.readUint32():this.grouping_type_parameter=0,this.entries=[];for(var e=t.readUint32(),i=0;i<e;i++){var s={};this.entries.push(s),s.sample_count=t.readInt32(),s.group_description_index=t.readInt32()}})),u.createFullBoxCtor("schm",(function(t){this.scheme_type=t.readString(4),this.scheme_version=t.readUint32(),1&this.flags&&(this.scheme_uri=t.readString(this.size-this.hdr_size-8))})),u.createBoxCtor("sdp ",(function(t){this.sdptext=t.readString(this.size-this.hdr_size)})),u.createFullBoxCtor("sdtp",(function(t){var e,i=this.size-this.hdr_size;this.is_leading=[],this.sample_depends_on=[],this.sample_is_depended_on=[],this.sample_has_redundancy=[];for(var s=0;s<i;s++)e=t.readUint8(),this.is_leading[s]=e>>6,this.sample_depends_on[s]=e>>4&3,this.sample_is_depended_on[s]=e>>2&3,this.sample_has_redundancy[s]=3&e})),u.createFullBoxCtor("senc"),u.createFullBoxCtor("sgpd",(function(t){this.grouping_type=t.readString(4),a.debug("BoxParser","Found Sample Groups of type "+this.grouping_type),1===this.version?this.default_length=t.readUint32():this.default_length=0,this.version>=2&&(this.default_group_description_index=t.readUint32()),this.entries=[];for(var e=t.readUint32(),i=0;i<e;i++){var s;s=u[this.grouping_type+"SampleGroupEntry"]?new u[this.grouping_type+"SampleGroupEntry"](this.grouping_type):new u.SampleGroupEntry(this.grouping_type),this.entries.push(s),1===this.version&&0===this.default_length?s.description_length=t.readUint32():s.description_length=this.default_length,s.write===u.SampleGroupEntry.prototype.write&&(a.info("BoxParser","SampleGroup for type "+this.grouping_type+" writing not yet implemented, keeping unparsed data in memory for later write"),s.data=t.readUint8Array(s.description_length),t.position-=s.description_length),s.parse(t)}})),u.createFullBoxCtor("sidx",(function(t){this.reference_ID=t.readUint32(),this.timescale=t.readUint32(),0===this.version?(this.earliest_presentation_time=t.readUint32(),this.first_offset=t.readUint32()):(this.earliest_presentation_time=t.readUint64(),this.first_offset=t.readUint64()),t.readUint16(),this.references=[];for(var e=t.readUint16(),i=0;i<e;i++){var s={};this.references.push(s);var r=t.readUint32();s.reference_type=r>>31&1,s.referenced_size=2147483647&r,s.subsegment_duration=t.readUint32(),r=t.readUint32(),s.starts_with_SAP=r>>31&1,s.SAP_type=r>>28&7,s.SAP_delta_time=268435455&r}})),u.SingleItemTypeReferenceBox=function(t,e,i,s){u.Box.call(this,t,e),this.hdr_size=i,this.start=s},u.SingleItemTypeReferenceBox.prototype=new u.Box,u.SingleItemTypeReferenceBox.prototype.parse=function(t){this.from_item_ID=t.readUint16();var e=t.readUint16();this.references=[];for(var i=0;i<e;i++)this.references[i]=t.readUint16()},u.SingleItemTypeReferenceBoxLarge=function(t,e,i,s){u.Box.call(this,t,e),this.hdr_size=i,this.start=s},u.SingleItemTypeReferenceBoxLarge.prototype=new u.Box,u.SingleItemTypeReferenceBoxLarge.prototype.parse=function(t){this.from_item_ID=t.readUint32();var e=t.readUint16();this.references=[];for(var i=0;i<e;i++)this.references[i]=t.readUint32()},u.createFullBoxCtor("SmDm",(function(t){this.primaryRChromaticity_x=t.readUint16(),this.primaryRChromaticity_y=t.readUint16(),this.primaryGChromaticity_x=t.readUint16(),this.primaryGChromaticity_y=t.readUint16(),this.primaryBChromaticity_x=t.readUint16(),this.primaryBChromaticity_y=t.readUint16(),this.whitePointChromaticity_x=t.readUint16(),this.whitePointChromaticity_y=t.readUint16(),this.luminanceMax=t.readUint32(),this.luminanceMin=t.readUint32()})),u.createFullBoxCtor("smhd",(function(t){this.balance=t.readUint16(),t.readUint16()})),u.createFullBoxCtor("ssix",(function(t){this.subsegments=[];for(var e=t.readUint32(),i=0;i<e;i++){var s={};this.subsegments.push(s),s.ranges=[];for(var r=t.readUint32(),a=0;a<r;a++){var n={};s.ranges.push(n),n.level=t.readUint8(),n.range_size=t.readUint24()}}})),u.createFullBoxCtor("stco",(function(t){var e;if(e=t.readUint32(),this.chunk_offsets=[],0===this.version)for(var i=0;i<e;i++)this.chunk_offsets.push(t.readUint32())})),u.createFullBoxCtor("stdp",(function(t){var e=(this.size-this.hdr_size)/2;this.priority=[];for(var i=0;i<e;i++)this.priority[i]=t.readUint16()})),u.createFullBoxCtor("sthd"),u.createFullBoxCtor("stri",(function(t){this.switch_group=t.readUint16(),this.alternate_group=t.readUint16(),this.sub_track_id=t.readUint32();var e=(this.size-this.hdr_size-8)/4;this.attribute_list=[];for(var i=0;i<e;i++)this.attribute_list[i]=t.readUint32()})),u.createFullBoxCtor("stsc",(function(t){var e,i;if(e=t.readUint32(),this.first_chunk=[],this.samples_per_chunk=[],this.sample_description_index=[],0===this.version)for(i=0;i<e;i++)this.first_chunk.push(t.readUint32()),this.samples_per_chunk.push(t.readUint32()),this.sample_description_index.push(t.readUint32())})),u.createFullBoxCtor("stsd",(function(t){var e,i,s,r;for(this.entries=[],s=t.readUint32(),e=1;e<=s;e++){if((i=u.parseOneBox(t,!0,this.size-(t.getPosition()-this.start))).code!==u.OK)return;u[i.type+"SampleEntry"]?((r=new u[i.type+"SampleEntry"](i.size)).hdr_size=i.hdr_size,r.start=i.start):(a.warn("BoxParser","Unknown sample entry type: "+i.type),r=new u.SampleEntry(i.type,i.size,i.hdr_size,i.start)),r.write===u.SampleEntry.prototype.write&&(a.info("BoxParser","SampleEntry "+r.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),r.parseDataAndRewind(t)),r.parse(t),this.entries.push(r)}})),u.createFullBoxCtor("stsg",(function(t){this.grouping_type=t.readUint32();var e=t.readUint16();this.group_description_index=[];for(var i=0;i<e;i++)this.group_description_index[i]=t.readUint32()})),u.createFullBoxCtor("stsh",(function(t){var e,i;if(e=t.readUint32(),this.shadowed_sample_numbers=[],this.sync_sample_numbers=[],0===this.version)for(i=0;i<e;i++)this.shadowed_sample_numbers.push(t.readUint32()),this.sync_sample_numbers.push(t.readUint32())})),u.createFullBoxCtor("stss",(function(t){var e,i;if(i=t.readUint32(),0===this.version)for(this.sample_numbers=[],e=0;e<i;e++)this.sample_numbers.push(t.readUint32())})),u.createFullBoxCtor("stsz",(function(t){var e;if(this.sample_sizes=[],0===this.version)for(this.sample_size=t.readUint32(),this.sample_count=t.readUint32(),e=0;e<this.sample_count;e++)0===this.sample_size?this.sample_sizes.push(t.readUint32()):this.sample_sizes[e]=this.sample_size})),u.createFullBoxCtor("stts",(function(t){var e,i,s;if(e=t.readUint32(),this.sample_counts=[],this.sample_deltas=[],0===this.version)for(i=0;i<e;i++)this.sample_counts.push(t.readUint32()),(s=t.readInt32())<0&&(a.warn("BoxParser","File uses negative stts sample delta, using value 1 instead, sync may be lost!"),s=1),this.sample_deltas.push(s)})),u.createFullBoxCtor("stvi",(function(t){var e=t.readUint32();this.single_view_allowed=3&e,this.stereo_scheme=t.readUint32();var i,s,r=t.readUint32();for(this.stereo_indication_type=t.readString(r),this.boxes=[];t.getPosition()<this.start+this.size;){if((i=u.parseOneBox(t,!1,this.size-(t.getPosition()-this.start))).code!==u.OK)return;s=i.box,this.boxes.push(s),this[s.type]=s}})),u.createBoxCtor("styp",(function(t){u.ftypBox.prototype.parse.call(this,t)})),u.createFullBoxCtor("stz2",(function(t){var e,i;if(this.sample_sizes=[],0===this.version)if(this.reserved=t.readUint24(),this.field_size=t.readUint8(),i=t.readUint32(),4===this.field_size)for(e=0;e<i;e+=2){var s=t.readUint8();this.sample_sizes[e]=s>>4&15,this.sample_sizes[e+1]=15&s}else if(8===this.field_size)for(e=0;e<i;e++)this.sample_sizes[e]=t.readUint8();else if(16===this.field_size)for(e=0;e<i;e++)this.sample_sizes[e]=t.readUint16();else a.error("BoxParser","Error in length field in stz2 box")})),u.createFullBoxCtor("subs",(function(t){var e,i,s,r;for(s=t.readUint32(),this.entries=[],e=0;e<s;e++){var a={};if(this.entries[e]=a,a.sample_delta=t.readUint32(),a.subsamples=[],(r=t.readUint16())>0)for(i=0;i<r;i++){var n={};a.subsamples.push(n),1==this.version?n.size=t.readUint32():n.size=t.readUint16(),n.priority=t.readUint8(),n.discardable=t.readUint8(),n.codec_specific_parameters=t.readUint32()}}})),u.createFullBoxCtor("tenc",(function(t){if(t.readUint8(),0===this.version)t.readUint8();else{var e=t.readUint8();this.default_crypt_byte_block=e>>4&15,this.default_skip_byte_block=15&e}this.default_isProtected=t.readUint8(),this.default_Per_Sample_IV_Size=t.readUint8(),this.default_KID=u.parseHex16(t),1===this.default_isProtected&&0===this.default_Per_Sample_IV_Size&&(this.default_constant_IV_size=t.readUint8(),this.default_constant_IV=t.readUint8Array(this.default_constant_IV_size))})),u.createFullBoxCtor("tfdt",(function(t){1==this.version?this.baseMediaDecodeTime=t.readUint64():this.baseMediaDecodeTime=t.readUint32()})),u.createFullBoxCtor("tfhd",(function(t){var e=0;this.track_id=t.readUint32(),this.size-this.hdr_size>e&&this.flags&u.TFHD_FLAG_BASE_DATA_OFFSET?(this.base_data_offset=t.readUint64(),e+=8):this.base_data_offset=0,this.size-this.hdr_size>e&&this.flags&u.TFHD_FLAG_SAMPLE_DESC?(this.default_sample_description_index=t.readUint32(),e+=4):this.default_sample_description_index=0,this.size-this.hdr_size>e&&this.flags&u.TFHD_FLAG_SAMPLE_DUR?(this.default_sample_duration=t.readUint32(),e+=4):this.default_sample_duration=0,this.size-this.hdr_size>e&&this.flags&u.TFHD_FLAG_SAMPLE_SIZE?(this.default_sample_size=t.readUint32(),e+=4):this.default_sample_size=0,this.size-this.hdr_size>e&&this.flags&u.TFHD_FLAG_SAMPLE_FLAGS?(this.default_sample_flags=t.readUint32(),e+=4):this.default_sample_flags=0})),u.createFullBoxCtor("tfra",(function(t){this.track_ID=t.readUint32(),t.readUint24();var e=t.readUint8();this.length_size_of_traf_num=e>>4&3,this.length_size_of_trun_num=e>>2&3,this.length_size_of_sample_num=3&e,this.entries=[];for(var i=t.readUint32(),s=0;s<i;s++)1===this.version?(this.time=t.readUint64(),this.moof_offset=t.readUint64()):(this.time=t.readUint32(),this.moof_offset=t.readUint32()),this.traf_number=t["readUint"+8*(this.length_size_of_traf_num+1)](),this.trun_number=t["readUint"+8*(this.length_size_of_trun_num+1)](),this.sample_number=t["readUint"+8*(this.length_size_of_sample_num+1)]()})),u.createFullBoxCtor("tkhd",(function(t){1==this.version?(this.creation_time=t.readUint64(),this.modification_time=t.readUint64(),this.track_id=t.readUint32(),t.readUint32(),this.duration=t.readUint64()):(this.creation_time=t.readUint32(),this.modification_time=t.readUint32(),this.track_id=t.readUint32(),t.readUint32(),this.duration=t.readUint32()),t.readUint32Array(2),this.layer=t.readInt16(),this.alternate_group=t.readInt16(),this.volume=t.readInt16()>>8,t.readUint16(),this.matrix=t.readInt32Array(9),this.width=t.readUint32(),this.height=t.readUint32()})),u.createBoxCtor("tmax",(function(t){this.time=t.readUint32()})),u.createBoxCtor("tmin",(function(t){this.time=t.readUint32()})),u.createBoxCtor("totl",(function(t){this.bytessent=t.readUint32()})),u.createBoxCtor("tpay",(function(t){this.bytessent=t.readUint32()})),u.createBoxCtor("tpyl",(function(t){this.bytessent=t.readUint64()})),u.TrackGroupTypeBox.prototype.parse=function(t){this.parseFullHeader(t),this.track_group_id=t.readUint32()},u.createTrackGroupCtor("msrc"),u.TrackReferenceTypeBox=function(t,e,i,s){u.Box.call(this,t,e),this.hdr_size=i,this.start=s},u.TrackReferenceTypeBox.prototype=new u.Box,u.TrackReferenceTypeBox.prototype.parse=function(t){this.track_ids=t.readUint32Array((this.size-this.hdr_size)/4)},u.trefBox.prototype.parse=function(t){for(var e,i;t.getPosition()<this.start+this.size;){if((e=u.parseOneBox(t,!0,this.size-(t.getPosition()-this.start))).code!==u.OK)return;(i=new u.TrackReferenceTypeBox(e.type,e.size,e.hdr_size,e.start)).write===u.Box.prototype.write&&"mdat"!==i.type&&(a.info("BoxParser","TrackReference "+i.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),i.parseDataAndRewind(t)),i.parse(t),this.boxes.push(i)}},u.createFullBoxCtor("trep",(function(t){for(this.track_ID=t.readUint32(),this.boxes=[];t.getPosition()<this.start+this.size;){if(ret=u.parseOneBox(t,!1,this.size-(t.getPosition()-this.start)),ret.code!==u.OK)return;box=ret.box,this.boxes.push(box)}})),u.createFullBoxCtor("trex",(function(t){this.track_id=t.readUint32(),this.default_sample_description_index=t.readUint32(),this.default_sample_duration=t.readUint32(),this.default_sample_size=t.readUint32(),this.default_sample_flags=t.readUint32()})),u.createBoxCtor("trpy",(function(t){this.bytessent=t.readUint64()})),u.createFullBoxCtor("trun",(function(t){var e=0;if(this.sample_count=t.readUint32(),e+=4,this.size-this.hdr_size>e&&this.flags&u.TRUN_FLAGS_DATA_OFFSET?(this.data_offset=t.readInt32(),e+=4):this.data_offset=0,this.size-this.hdr_size>e&&this.flags&u.TRUN_FLAGS_FIRST_FLAG?(this.first_sample_flags=t.readUint32(),e+=4):this.first_sample_flags=0,this.sample_duration=[],this.sample_size=[],this.sample_flags=[],this.sample_composition_time_offset=[],this.size-this.hdr_size>e)for(var i=0;i<this.sample_count;i++)this.flags&u.TRUN_FLAGS_DURATION&&(this.sample_duration[i]=t.readUint32()),this.flags&u.TRUN_FLAGS_SIZE&&(this.sample_size[i]=t.readUint32()),this.flags&u.TRUN_FLAGS_FLAGS&&(this.sample_flags[i]=t.readUint32()),this.flags&u.TRUN_FLAGS_CTS_OFFSET&&(0===this.version?this.sample_composition_time_offset[i]=t.readUint32():this.sample_composition_time_offset[i]=t.readInt32())})),u.createFullBoxCtor("tsel",(function(t){this.switch_group=t.readUint32();var e=(this.size-this.hdr_size-4)/4;this.attribute_list=[];for(var i=0;i<e;i++)this.attribute_list[i]=t.readUint32()})),u.createFullBoxCtor("txtC",(function(t){this.config=t.readCString()})),u.createFullBoxCtor("url ",(function(t){1!==this.flags&&(this.location=t.readCString())})),u.createFullBoxCtor("urn ",(function(t){this.name=t.readCString(),this.size-this.hdr_size-this.name.length-1>0&&(this.location=t.readCString())})),u.createUUIDBox("a5d40b30e81411ddba2f0800200c9a66",!0,!1,(function(t){this.LiveServerManifest=t.readString(this.size-this.hdr_size).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")})),u.createUUIDBox("d08a4f1810f34a82b6c832d8aba183d3",!0,!1,(function(t){this.system_id=u.parseHex16(t);var e=t.readUint32();e>0&&(this.data=t.readUint8Array(e))})),u.createUUIDBox("a2394f525a9b4f14a2446c427c648df4",!0,!1),u.createUUIDBox("8974dbce7be74c5184f97148f9882554",!0,!1,(function(t){this.default_AlgorithmID=t.readUint24(),this.default_IV_size=t.readUint8(),this.default_KID=u.parseHex16(t)})),u.createUUIDBox("d4807ef2ca3946958e5426cb9e46a79f",!0,!1,(function(t){this.fragment_count=t.readUint8(),this.entries=[];for(var e=0;e<this.fragment_count;e++){var i={},s=0,r=0;1===this.version?(s=t.readUint64(),r=t.readUint64()):(s=t.readUint32(),r=t.readUint32()),i.absolute_time=s,i.absolute_duration=r,this.entries.push(i)}})),u.createUUIDBox("6d1d9b0542d544e680e2141daff757b2",!0,!1,(function(t){1===this.version?(this.absolute_time=t.readUint64(),this.duration=t.readUint64()):(this.absolute_time=t.readUint32(),this.duration=t.readUint32())})),u.createFullBoxCtor("vmhd",(function(t){this.graphicsmode=t.readUint16(),this.opcolor=t.readUint16Array(3)})),u.createFullBoxCtor("vpcC",(function(t){var e;1===this.version?(this.profile=t.readUint8(),this.level=t.readUint8(),e=t.readUint8(),this.bitDepth=e>>4,this.chromaSubsampling=e>>1&7,this.videoFullRangeFlag=1&e,this.colourPrimaries=t.readUint8(),this.transferCharacteristics=t.readUint8(),this.matrixCoefficients=t.readUint8(),this.codecIntializationDataSize=t.readUint16(),this.codecIntializationData=t.readUint8Array(this.codecIntializationDataSize)):(this.profile=t.readUint8(),this.level=t.readUint8(),e=t.readUint8(),this.bitDepth=e>>4&15,this.colorSpace=15&e,e=t.readUint8(),this.chromaSubsampling=e>>4&15,this.transferFunction=e>>1&7,this.videoFullRangeFlag=1&e,this.codecIntializationDataSize=t.readUint16(),this.codecIntializationData=t.readUint8Array(this.codecIntializationDataSize))})),u.createBoxCtor("vttC",(function(t){this.text=t.readString(this.size-this.hdr_size)})),u.createFullBoxCtor("vvcC",(function(t){var e,i,s={held_bits:void 0,num_held_bits:0,stream_read_1_bytes:function(t){this.held_bits=t.readUint8(),this.num_held_bits=8},stream_read_2_bytes:function(t){this.held_bits=t.readUint16(),this.num_held_bits=16},extract_bits:function(t){var e=this.held_bits>>this.num_held_bits-t&(1<<t)-1;return this.num_held_bits-=t,e}};if(s.stream_read_1_bytes(t),s.extract_bits(5),this.lengthSizeMinusOne=s.extract_bits(2),this.ptl_present_flag=s.extract_bits(1),this.ptl_present_flag){if(s.stream_read_2_bytes(t),this.ols_idx=s.extract_bits(9),this.num_sublayers=s.extract_bits(3),this.constant_frame_rate=s.extract_bits(2),this.chroma_format_idc=s.extract_bits(2),s.stream_read_1_bytes(t),this.bit_depth_minus8=s.extract_bits(3),s.extract_bits(5),s.stream_read_2_bytes(t),s.extract_bits(2),this.num_bytes_constraint_info=s.extract_bits(6),this.general_profile_idc=s.extract_bits(7),this.general_tier_flag=s.extract_bits(1),this.general_level_idc=t.readUint8(),s.stream_read_1_bytes(t),this.ptl_frame_only_constraint_flag=s.extract_bits(1),this.ptl_multilayer_enabled_flag=s.extract_bits(1),this.general_constraint_info=new Uint8Array(this.num_bytes_constraint_info),this.num_bytes_constraint_info){for(e=0;e<this.num_bytes_constraint_info-1;e++){var r=s.extract_bits(6);s.stream_read_1_bytes(t);var a=s.extract_bits(2);this.general_constraint_info[e]=r<<2|a}this.general_constraint_info[this.num_bytes_constraint_info-1]=s.extract_bits(6)}else s.extract_bits(6);for(s.stream_read_1_bytes(t),this.ptl_sublayer_present_mask=0,i=this.num_sublayers-2;i>=0;--i){var n=s.extract_bits(1);this.ptl_sublayer_present_mask|=n<<i}for(i=this.num_sublayers;i<=8&&this.num_sublayers>1;++i)s.extract_bits(1);for(i=this.num_sublayers-2;i>=0;--i)this.ptl_sublayer_present_mask&1<<i&&(this.sublayer_level_idc[i]=t.readUint8());if(this.ptl_num_sub_profiles=t.readUint8(),this.general_sub_profile_idc=[],this.ptl_num_sub_profiles)for(e=0;e<this.ptl_num_sub_profiles;e++)this.general_sub_profile_idc.push(t.readUint32());this.max_picture_width=t.readUint16(),this.max_picture_height=t.readUint16(),this.avg_frame_rate=t.readUint16()}this.nalu_arrays=[];var o=t.readUint8();for(e=0;e<o;e++){var h=[];this.nalu_arrays.push(h),s.stream_read_1_bytes(t),h.completeness=s.extract_bits(1),s.extract_bits(2),h.nalu_type=s.extract_bits(5);var l=1;for(13!=h.nalu_type&&12!=h.nalu_type&&(l=t.readUint16()),i=0;i<l;i++){var d=t.readUint16();h.push({data:t.readUint8Array(d),length:d})}}})),u.createFullBoxCtor("vvnC",(function(t){var e=strm.readUint8();this.lengthSizeMinusOne=3&e})),u.SampleEntry.prototype.isVideo=function(){return!1},u.SampleEntry.prototype.isAudio=function(){return!1},u.SampleEntry.prototype.isSubtitle=function(){return!1},u.SampleEntry.prototype.isMetadata=function(){return!1},u.SampleEntry.prototype.isHint=function(){return!1},u.SampleEntry.prototype.getCodec=function(){return this.type.replace(".","")},u.SampleEntry.prototype.getWidth=function(){return""},u.SampleEntry.prototype.getHeight=function(){return""},u.SampleEntry.prototype.getChannelCount=function(){return""},u.SampleEntry.prototype.getSampleRate=function(){return""},u.SampleEntry.prototype.getSampleSize=function(){return""},u.VisualSampleEntry.prototype.isVideo=function(){return!0},u.VisualSampleEntry.prototype.getWidth=function(){return this.width},u.VisualSampleEntry.prototype.getHeight=function(){return this.height},u.AudioSampleEntry.prototype.isAudio=function(){return!0},u.AudioSampleEntry.prototype.getChannelCount=function(){return this.channel_count},u.AudioSampleEntry.prototype.getSampleRate=function(){return this.samplerate},u.AudioSampleEntry.prototype.getSampleSize=function(){return this.samplesize},u.SubtitleSampleEntry.prototype.isSubtitle=function(){return!0},u.MetadataSampleEntry.prototype.isMetadata=function(){return!0},u.decimalToHex=function(t,e){var i=Number(t).toString(16);for(e=null==e?e=2:e;i.length<e;)i="0"+i;return i},u.avc1SampleEntry.prototype.getCodec=u.avc2SampleEntry.prototype.getCodec=u.avc3SampleEntry.prototype.getCodec=u.avc4SampleEntry.prototype.getCodec=function(){var t=u.SampleEntry.prototype.getCodec.call(this);return this.avcC?t+"."+u.decimalToHex(this.avcC.AVCProfileIndication)+u.decimalToHex(this.avcC.profile_compatibility)+u.decimalToHex(this.avcC.AVCLevelIndication):t},u.hev1SampleEntry.prototype.getCodec=u.hvc1SampleEntry.prototype.getCodec=function(){var t,e=u.SampleEntry.prototype.getCodec.call(this);if(this.hvcC){switch(e+=".",this.hvcC.general_profile_space){case 0:e+="";break;case 1:e+="A";break;case 2:e+="B";break;case 3:e+="C"}e+=this.hvcC.general_profile_idc,e+=".";var i=this.hvcC.general_profile_compatibility,s=0;for(t=0;t<32&&(s|=1&i,31!=t);t++)s<<=1,i>>=1;e+=u.decimalToHex(s,0),e+=".",0===this.hvcC.general_tier_flag?e+="L":e+="H",e+=this.hvcC.general_level_idc;var r=!1,a="";for(t=5;t>=0;t--)(this.hvcC.general_constraint_indicator[t]||r)&&(a="."+u.decimalToHex(this.hvcC.general_constraint_indicator[t],0)+a,r=!0);e+=a}return e},u.vvc1SampleEntry.prototype.getCodec=u.vvi1SampleEntry.prototype.getCodec=function(){var t,e=u.SampleEntry.prototype.getCodec.call(this);if(this.vvcC){e+="."+this.vvcC.general_profile_idc,this.vvcC.general_tier_flag?e+=".H":e+=".L",e+=this.vvcC.general_level_idc;var i="";if(this.vvcC.general_constraint_info){var s,r=[],a=0;for(a|=this.vvcC.ptl_frame_only_constraint<<7,a|=this.vvcC.ptl_multilayer_enabled<<6,t=0;t<this.vvcC.general_constraint_info.length;++t)a|=this.vvcC.general_constraint_info[t]>>2&63,r.push(a),a&&(s=t),a=this.vvcC.general_constraint_info[t]>>2&3;if(void 0===s)i=".CA";else{i=".C";var n="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",o=0,h=0;for(t=0;t<=s;++t)for(o=o<<8|r[t],h+=8;h>=5;){i+=n[o>>h-5&31],o&=(1<<(h-=5))-1}h&&(i+=n[31&(o<<=5-h)])}}e+=i}return e},u.mp4aSampleEntry.prototype.getCodec=function(){var t=u.SampleEntry.prototype.getCodec.call(this);if(this.esds&&this.esds.esd){var e=this.esds.esd.getOTI(),i=this.esds.esd.getAudioConfig();return t+"."+u.decimalToHex(e)+(i?"."+i:"")}return t},u.stxtSampleEntry.prototype.getCodec=function(){var t=u.SampleEntry.prototype.getCodec.call(this);return this.mime_format?t+"."+this.mime_format:t},u.vp08SampleEntry.prototype.getCodec=u.vp09SampleEntry.prototype.getCodec=function(){var t=u.SampleEntry.prototype.getCodec.call(this),e=this.vpcC.level;0==e&&(e="00");var i=this.vpcC.bitDepth;return 8==i&&(i="08"),t+".0"+this.vpcC.profile+"."+e+"."+i},u.av01SampleEntry.prototype.getCodec=function(){var t,e=u.SampleEntry.prototype.getCodec.call(this),i=this.av1C.seq_level_idx_0;return i<10&&(i="0"+i),2===this.av1C.seq_profile&&1===this.av1C.high_bitdepth?t=1===this.av1C.twelve_bit?"12":"10":this.av1C.seq_profile<=2&&(t=1===this.av1C.high_bitdepth?"10":"08"),e+"."+this.av1C.seq_profile+"."+i+(this.av1C.seq_tier_0?"H":"M")+"."+t},u.Box.prototype.writeHeader=function(t,e){this.size+=8,this.size>h&&(this.size+=8),"uuid"===this.type&&(this.size+=16),a.debug("BoxWriter","Writing box "+this.type+" of size: "+this.size+" at position "+t.getPosition()+(e||"")),this.size>h?t.writeUint32(1):(this.sizePosition=t.getPosition(),t.writeUint32(this.size)),t.writeString(this.type,null,4),"uuid"===this.type&&t.writeUint8Array(this.uuid),this.size>h&&t.writeUint64(this.size)},u.FullBox.prototype.writeHeader=function(t){this.size+=4,u.Box.prototype.writeHeader.call(this,t," v="+this.version+" f="+this.flags),t.writeUint8(this.version),t.writeUint24(this.flags)},u.Box.prototype.write=function(t){"mdat"===this.type?this.data&&(this.size=this.data.length,this.writeHeader(t),t.writeUint8Array(this.data)):(this.size=this.data?this.data.length:0,this.writeHeader(t),this.data&&t.writeUint8Array(this.data))},u.ContainerBox.prototype.write=function(t){this.size=0,this.writeHeader(t);for(var e=0;e<this.boxes.length;e++)this.boxes[e]&&(this.boxes[e].write(t),this.size+=this.boxes[e].size);a.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),t.adjustUint32(this.sizePosition,this.size)},u.TrackReferenceTypeBox.prototype.write=function(t){this.size=4*this.track_ids.length,this.writeHeader(t),t.writeUint32Array(this.track_ids)},u.avcCBox.prototype.write=function(t){var e;for(this.size=7,e=0;e<this.SPS.length;e++)this.size+=2+this.SPS[e].length;for(e=0;e<this.PPS.length;e++)this.size+=2+this.PPS[e].length;for(this.ext&&(this.size+=this.ext.length),this.writeHeader(t),t.writeUint8(this.configurationVersion),t.writeUint8(this.AVCProfileIndication),t.writeUint8(this.profile_compatibility),t.writeUint8(this.AVCLevelIndication),t.writeUint8(this.lengthSizeMinusOne+252),t.writeUint8(this.SPS.length+224),e=0;e<this.SPS.length;e++)t.writeUint16(this.SPS[e].length),t.writeUint8Array(this.SPS[e].nalu);for(t.writeUint8(this.PPS.length),e=0;e<this.PPS.length;e++)t.writeUint16(this.PPS[e].length),t.writeUint8Array(this.PPS[e].nalu);this.ext&&t.writeUint8Array(this.ext)},u.co64Box.prototype.write=function(t){var e;for(this.version=0,this.flags=0,this.size=4+8*this.chunk_offsets.length,this.writeHeader(t),t.writeUint32(this.chunk_offsets.length),e=0;e<this.chunk_offsets.length;e++)t.writeUint64(this.chunk_offsets[e])},u.cslgBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=20,this.writeHeader(t),t.writeInt32(this.compositionToDTSShift),t.writeInt32(this.leastDecodeToDisplayDelta),t.writeInt32(this.greatestDecodeToDisplayDelta),t.writeInt32(this.compositionStartTime),t.writeInt32(this.compositionEndTime)},u.cttsBox.prototype.write=function(t){var e;for(this.version=0,this.flags=0,this.size=4+8*this.sample_counts.length,this.writeHeader(t),t.writeUint32(this.sample_counts.length),e=0;e<this.sample_counts.length;e++)t.writeUint32(this.sample_counts[e]),1===this.version?t.writeInt32(this.sample_offsets[e]):t.writeUint32(this.sample_offsets[e])},u.drefBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=4,this.writeHeader(t),t.writeUint32(this.entries.length);for(var e=0;e<this.entries.length;e++)this.entries[e].write(t),this.size+=this.entries[e].size;a.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),t.adjustUint32(this.sizePosition,this.size)},u.elngBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=this.extended_language.length,this.writeHeader(t),t.writeString(this.extended_language)},u.elstBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=4+12*this.entries.length,this.writeHeader(t),t.writeUint32(this.entries.length);for(var e=0;e<this.entries.length;e++){var i=this.entries[e];t.writeUint32(i.segment_duration),t.writeInt32(i.media_time),t.writeInt16(i.media_rate_integer),t.writeInt16(i.media_rate_fraction)}},u.emsgBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=16+this.message_data.length+(this.scheme_id_uri.length+1)+(this.value.length+1),this.writeHeader(t),t.writeCString(this.scheme_id_uri),t.writeCString(this.value),t.writeUint32(this.timescale),t.writeUint32(this.presentation_time_delta),t.writeUint32(this.event_duration),t.writeUint32(this.id),t.writeUint8Array(this.message_data)},u.ftypBox.prototype.write=function(t){this.size=8+4*this.compatible_brands.length,this.writeHeader(t),t.writeString(this.major_brand,null,4),t.writeUint32(this.minor_version);for(var e=0;e<this.compatible_brands.length;e++)t.writeString(this.compatible_brands[e],null,4)},u.hdlrBox.prototype.write=function(t){this.size=20+this.name.length+1,this.version=0,this.flags=0,this.writeHeader(t),t.writeUint32(0),t.writeString(this.handler,null,4),t.writeUint32(0),t.writeUint32(0),t.writeUint32(0),t.writeCString(this.name)},u.kindBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=this.schemeURI.length+1+(this.value.length+1),this.writeHeader(t),t.writeCString(this.schemeURI),t.writeCString(this.value)},u.mdhdBox.prototype.write=function(t){this.size=20,this.flags=0,this.version=0,this.writeHeader(t),t.writeUint32(this.creation_time),t.writeUint32(this.modification_time),t.writeUint32(this.timescale),t.writeUint32(this.duration),t.writeUint16(this.language),t.writeUint16(0)},u.mehdBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=4,this.writeHeader(t),t.writeUint32(this.fragment_duration)},u.mfhdBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=4,this.writeHeader(t),t.writeUint32(this.sequence_number)},u.mvhdBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=96,this.writeHeader(t),t.writeUint32(this.creation_time),t.writeUint32(this.modification_time),t.writeUint32(this.timescale),t.writeUint32(this.duration),t.writeUint32(this.rate),t.writeUint16(this.volume<<8),t.writeUint16(0),t.writeUint32(0),t.writeUint32(0),t.writeUint32Array(this.matrix),t.writeUint32(0),t.writeUint32(0),t.writeUint32(0),t.writeUint32(0),t.writeUint32(0),t.writeUint32(0),t.writeUint32(this.next_track_id)},u.SampleEntry.prototype.writeHeader=function(t){this.size=8,u.Box.prototype.writeHeader.call(this,t),t.writeUint8(0),t.writeUint8(0),t.writeUint8(0),t.writeUint8(0),t.writeUint8(0),t.writeUint8(0),t.writeUint16(this.data_reference_index)},u.SampleEntry.prototype.writeFooter=function(t){for(var e=0;e<this.boxes.length;e++)this.boxes[e].write(t),this.size+=this.boxes[e].size;a.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),t.adjustUint32(this.sizePosition,this.size)},u.SampleEntry.prototype.write=function(t){this.writeHeader(t),t.writeUint8Array(this.data),this.size+=this.data.length,a.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),t.adjustUint32(this.sizePosition,this.size)},u.VisualSampleEntry.prototype.write=function(t){this.writeHeader(t),this.size+=70,t.writeUint16(0),t.writeUint16(0),t.writeUint32(0),t.writeUint32(0),t.writeUint32(0),t.writeUint16(this.width),t.writeUint16(this.height),t.writeUint32(this.horizresolution),t.writeUint32(this.vertresolution),t.writeUint32(0),t.writeUint16(this.frame_count),t.writeUint8(Math.min(31,this.compressorname.length)),t.writeString(this.compressorname,null,31),t.writeUint16(this.depth),t.writeInt16(-1),this.writeFooter(t)},u.AudioSampleEntry.prototype.write=function(t){this.writeHeader(t),this.size+=20,t.writeUint32(0),t.writeUint32(0),t.writeUint16(this.channel_count),t.writeUint16(this.samplesize),t.writeUint16(0),t.writeUint16(0),t.writeUint32(this.samplerate<<16),this.writeFooter(t)},u.stppSampleEntry.prototype.write=function(t){this.writeHeader(t),this.size+=this.namespace.length+1+this.schema_location.length+1+this.auxiliary_mime_types.length+1,t.writeCString(this.namespace),t.writeCString(this.schema_location),t.writeCString(this.auxiliary_mime_types),this.writeFooter(t)},u.SampleGroupEntry.prototype.write=function(t){t.writeUint8Array(this.data)},u.sbgpBox.prototype.write=function(t){this.version=1,this.flags=0,this.size=12+8*this.entries.length,this.writeHeader(t),t.writeString(this.grouping_type,null,4),t.writeUint32(this.grouping_type_parameter),t.writeUint32(this.entries.length);for(var e=0;e<this.entries.length;e++){var i=this.entries[e];t.writeInt32(i.sample_count),t.writeInt32(i.group_description_index)}},u.sgpdBox.prototype.write=function(t){var e,i;for(this.flags=0,this.size=12,e=0;e<this.entries.length;e++)i=this.entries[e],1===this.version&&(0===this.default_length&&(this.size+=4),this.size+=i.data.length);for(this.writeHeader(t),t.writeString(this.grouping_type,null,4),1===this.version&&t.writeUint32(this.default_length),this.version>=2&&t.writeUint32(this.default_sample_description_index),t.writeUint32(this.entries.length),e=0;e<this.entries.length;e++)i=this.entries[e],1===this.version&&0===this.default_length&&t.writeUint32(i.description_length),i.write(t)},u.sidxBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=20+12*this.references.length,this.writeHeader(t),t.writeUint32(this.reference_ID),t.writeUint32(this.timescale),t.writeUint32(this.earliest_presentation_time),t.writeUint32(this.first_offset),t.writeUint16(0),t.writeUint16(this.references.length);for(var e=0;e<this.references.length;e++){var i=this.references[e];t.writeUint32(i.reference_type<<31|i.referenced_size),t.writeUint32(i.subsegment_duration),t.writeUint32(i.starts_with_SAP<<31|i.SAP_type<<28|i.SAP_delta_time)}},u.smhdBox.prototype.write=function(t){this.version=0,this.flags=1,this.size=4,this.writeHeader(t),t.writeUint16(this.balance),t.writeUint16(0)},u.stcoBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=4+4*this.chunk_offsets.length,this.writeHeader(t),t.writeUint32(this.chunk_offsets.length),t.writeUint32Array(this.chunk_offsets)},u.stscBox.prototype.write=function(t){var e;for(this.version=0,this.flags=0,this.size=4+12*this.first_chunk.length,this.writeHeader(t),t.writeUint32(this.first_chunk.length),e=0;e<this.first_chunk.length;e++)t.writeUint32(this.first_chunk[e]),t.writeUint32(this.samples_per_chunk[e]),t.writeUint32(this.sample_description_index[e])},u.stsdBox.prototype.write=function(t){var e;for(this.version=0,this.flags=0,this.size=0,this.writeHeader(t),t.writeUint32(this.entries.length),this.size+=4,e=0;e<this.entries.length;e++)this.entries[e].write(t),this.size+=this.entries[e].size;a.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),t.adjustUint32(this.sizePosition,this.size)},u.stshBox.prototype.write=function(t){var e;for(this.version=0,this.flags=0,this.size=4+8*this.shadowed_sample_numbers.length,this.writeHeader(t),t.writeUint32(this.shadowed_sample_numbers.length),e=0;e<this.shadowed_sample_numbers.length;e++)t.writeUint32(this.shadowed_sample_numbers[e]),t.writeUint32(this.sync_sample_numbers[e])},u.stssBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=4+4*this.sample_numbers.length,this.writeHeader(t),t.writeUint32(this.sample_numbers.length),t.writeUint32Array(this.sample_numbers)},u.stszBox.prototype.write=function(t){var e,i=!0;if(this.version=0,this.flags=0,this.sample_sizes.length>0)for(e=0;e+1<this.sample_sizes.length;){if(this.sample_sizes[e+1]!==this.sample_sizes[0]){i=!1;break}e++}else i=!1;this.size=8,i||(this.size+=4*this.sample_sizes.length),this.writeHeader(t),i?t.writeUint32(this.sample_sizes[0]):t.writeUint32(0),t.writeUint32(this.sample_sizes.length),i||t.writeUint32Array(this.sample_sizes)},u.sttsBox.prototype.write=function(t){var e;for(this.version=0,this.flags=0,this.size=4+8*this.sample_counts.length,this.writeHeader(t),t.writeUint32(this.sample_counts.length),e=0;e<this.sample_counts.length;e++)t.writeUint32(this.sample_counts[e]),t.writeUint32(this.sample_deltas[e])},u.tfdtBox.prototype.write=function(t){var e=Math.pow(2,32)-1;this.version=this.baseMediaDecodeTime>e?1:0,this.flags=0,this.size=4,1===this.version&&(this.size+=4),this.writeHeader(t),1===this.version?t.writeUint64(this.baseMediaDecodeTime):t.writeUint32(this.baseMediaDecodeTime)},u.tfhdBox.prototype.write=function(t){this.version=0,this.size=4,this.flags&u.TFHD_FLAG_BASE_DATA_OFFSET&&(this.size+=8),this.flags&u.TFHD_FLAG_SAMPLE_DESC&&(this.size+=4),this.flags&u.TFHD_FLAG_SAMPLE_DUR&&(this.size+=4),this.flags&u.TFHD_FLAG_SAMPLE_SIZE&&(this.size+=4),this.flags&u.TFHD_FLAG_SAMPLE_FLAGS&&(this.size+=4),this.writeHeader(t),t.writeUint32(this.track_id),this.flags&u.TFHD_FLAG_BASE_DATA_OFFSET&&t.writeUint64(this.base_data_offset),this.flags&u.TFHD_FLAG_SAMPLE_DESC&&t.writeUint32(this.default_sample_description_index),this.flags&u.TFHD_FLAG_SAMPLE_DUR&&t.writeUint32(this.default_sample_duration),this.flags&u.TFHD_FLAG_SAMPLE_SIZE&&t.writeUint32(this.default_sample_size),this.flags&u.TFHD_FLAG_SAMPLE_FLAGS&&t.writeUint32(this.default_sample_flags)},u.tkhdBox.prototype.write=function(t){this.version=0,this.size=80,this.writeHeader(t),t.writeUint32(this.creation_time),t.writeUint32(this.modification_time),t.writeUint32(this.track_id),t.writeUint32(0),t.writeUint32(this.duration),t.writeUint32(0),t.writeUint32(0),t.writeInt16(this.layer),t.writeInt16(this.alternate_group),t.writeInt16(this.volume<<8),t.writeUint16(0),t.writeInt32Array(this.matrix),t.writeUint32(this.width),t.writeUint32(this.height)},u.trexBox.prototype.write=function(t){this.version=0,this.flags=0,this.size=20,this.writeHeader(t),t.writeUint32(this.track_id),t.writeUint32(this.default_sample_description_index),t.writeUint32(this.default_sample_duration),t.writeUint32(this.default_sample_size),t.writeUint32(this.default_sample_flags)},u.trunBox.prototype.write=function(t){this.version=0,this.size=4,this.flags&u.TRUN_FLAGS_DATA_OFFSET&&(this.size+=4),this.flags&u.TRUN_FLAGS_FIRST_FLAG&&(this.size+=4),this.flags&u.TRUN_FLAGS_DURATION&&(this.size+=4*this.sample_duration.length),this.flags&u.TRUN_FLAGS_SIZE&&(this.size+=4*this.sample_size.length),this.flags&u.TRUN_FLAGS_FLAGS&&(this.size+=4*this.sample_flags.length),this.flags&u.TRUN_FLAGS_CTS_OFFSET&&(this.size+=4*this.sample_composition_time_offset.length),this.writeHeader(t),t.writeUint32(this.sample_count),this.flags&u.TRUN_FLAGS_DATA_OFFSET&&(this.data_offset_position=t.getPosition(),t.writeInt32(this.data_offset)),this.flags&u.TRUN_FLAGS_FIRST_FLAG&&t.writeUint32(this.first_sample_flags);for(var e=0;e<this.sample_count;e++)this.flags&u.TRUN_FLAGS_DURATION&&t.writeUint32(this.sample_duration[e]),this.flags&u.TRUN_FLAGS_SIZE&&t.writeUint32(this.sample_size[e]),this.flags&u.TRUN_FLAGS_FLAGS&&t.writeUint32(this.sample_flags[e]),this.flags&u.TRUN_FLAGS_CTS_OFFSET&&(0===this.version?t.writeUint32(this.sample_composition_time_offset[e]):t.writeInt32(this.sample_composition_time_offset[e]))},u["url Box"].prototype.write=function(t){this.version=0,this.location?(this.flags=0,this.size=this.location.length+1):(this.flags=1,this.size=0),this.writeHeader(t),this.location&&t.writeCString(this.location)},u["urn Box"].prototype.write=function(t){this.version=0,this.flags=0,this.size=this.name.length+1+(this.location?this.location.length+1:0),this.writeHeader(t),t.writeCString(this.name),this.location&&t.writeCString(this.location)},u.vmhdBox.prototype.write=function(t){this.version=0,this.flags=1,this.size=8,this.writeHeader(t),t.writeUint16(this.graphicsmode),t.writeUint16Array(this.opcolor)},u.cttsBox.prototype.unpack=function(t){var e,i,s;for(s=0,e=0;e<this.sample_counts.length;e++)for(i=0;i<this.sample_counts[e];i++)t[s].pts=t[s].dts+this.sample_offsets[e],s++},u.sttsBox.prototype.unpack=function(t){var e,i,s;for(s=0,e=0;e<this.sample_counts.length;e++)for(i=0;i<this.sample_counts[e];i++)t[s].dts=0===s?0:t[s-1].dts+this.sample_deltas[e],s++},u.stcoBox.prototype.unpack=function(t){var e;for(e=0;e<this.chunk_offsets.length;e++)t[e].offset=this.chunk_offsets[e]},u.stscBox.prototype.unpack=function(t){var e,i,s,r,a;for(r=0,a=0,e=0;e<this.first_chunk.length;e++)for(i=0;i<(e+1<this.first_chunk.length?this.first_chunk[e+1]:1/0);i++)for(a++,s=0;s<this.samples_per_chunk[e];s++){if(!t[r])return;t[r].description_index=this.sample_description_index[e],t[r].chunk_index=a,r++}},u.stszBox.prototype.unpack=function(t){var e;for(e=0;e<this.sample_sizes.length;e++)t[e].size=this.sample_sizes[e]},u.DIFF_BOXES_PROP_NAMES=["boxes","entries","references","subsamples","items","item_infos","extents","associations","subsegments","ranges","seekLists","seekPoints","esd","levels"],u.DIFF_PRIMITIVE_ARRAY_PROP_NAMES=["compatible_brands","matrix","opcolor","sample_counts","sample_counts","sample_deltas","first_chunk","samples_per_chunk","sample_sizes","chunk_offsets","sample_offsets","sample_description_index","sample_duration"],u.boxEqualFields=function(t,e){if(t&&!e)return!1;var i;for(i in t)if(!(u.DIFF_BOXES_PROP_NAMES.indexOf(i)>-1||t[i]instanceof u.Box||e[i]instanceof u.Box||void 0===t[i]||void 0===e[i]||"function"==typeof t[i]||"function"==typeof e[i]||t.subBoxNames&&t.subBoxNames.indexOf(i.slice(0,4))>-1||e.subBoxNames&&e.subBoxNames.indexOf(i.slice(0,4))>-1||"data"===i||"start"===i||"size"===i||"creation_time"===i||"modification_time"===i||u.DIFF_PRIMITIVE_ARRAY_PROP_NAMES.indexOf(i)>-1||t[i]===e[i]))return!1;return!0},u.boxEqual=function(t,e){if(!u.boxEqualFields(t,e))return!1;for(var i=0;i<u.DIFF_BOXES_PROP_NAMES.length;i++){var s=u.DIFF_BOXES_PROP_NAMES[i];if(t[s]&&e[s]&&!u.boxEqual(t[s],e[s]))return!1}return!0};var p=function(){};p.prototype.parseSample=function(t){var e,i={};i.resources=[];var s=new n(t.data.buffer);if(t.subsamples&&0!==t.subsamples.length){if(i.documentString=s.readString(t.subsamples[0].size),t.subsamples.length>1)for(e=1;e<t.subsamples.length;e++)i.resources[e]=s.readUint8Array(t.subsamples[e].size)}else i.documentString=s.readString(t.data.length);return"undefined"!=typeof DOMParser&&(i.document=(new DOMParser).parseFromString(i.documentString,"application/xml")),i};var c=function(){};c.prototype.parseSample=function(t){return new n(t.data.buffer).readString(t.data.length)},c.prototype.parseConfig=function(t){var e=new n(t.buffer);return e.readUint32(),e.readCString()},e.XMLSubtitlein4Parser=p,e.Textin4Parser=c;var f=function(t){this.stream=t||new l,this.boxes=[],this.mdats=[],this.moofs=[],this.isProgressive=!1,this.moovStartFound=!1,this.onMoovStart=null,this.moovStartSent=!1,this.onReady=null,this.readySent=!1,this.onSegment=null,this.onSamples=null,this.onError=null,this.sampleListBuilt=!1,this.fragmentedTracks=[],this.extractedTracks=[],this.isFragmentationInitialized=!1,this.sampleProcessingStarted=!1,this.nextMoofNumber=0,this.itemListBuilt=!1,this.onSidx=null,this.sidxSent=!1};f.prototype.setSegmentOptions=function(t,e,i){var s=this.getTrackById(t);if(s){var r={};this.fragmentedTracks.push(r),r.id=t,r.user=e,r.trak=s,s.nextSample=0,r.segmentStream=null,r.nb_samples=1e3,r.rapAlignement=!0,i&&(i.nbSamples&&(r.nb_samples=i.nbSamples),i.rapAlignement&&(r.rapAlignement=i.rapAlignement))}},f.prototype.unsetSegmentOptions=function(t){for(var e=-1,i=0;i<this.fragmentedTracks.length;i++){this.fragmentedTracks[i].id==t&&(e=i)}e>-1&&this.fragmentedTracks.splice(e,1)},f.prototype.setExtractionOptions=function(t,e,i){var s=this.getTrackById(t);if(s){var r={};this.extractedTracks.push(r),r.id=t,r.user=e,r.trak=s,s.nextSample=0,r.nb_samples=1e3,r.samples=[],i&&i.nbSamples&&(r.nb_samples=i.nbSamples)}},f.prototype.unsetExtractionOptions=function(t){for(var e=-1,i=0;i<this.extractedTracks.length;i++){this.extractedTracks[i].id==t&&(e=i)}e>-1&&this.extractedTracks.splice(e,1)},f.prototype.parse=function(){var t,e;if(!this.restoreParsePosition||this.restoreParsePosition())for(;;){if(this.hasIncompleteMdat&&this.hasIncompleteMdat()){if(this.processIncompleteMdat())continue;return}if(this.saveParsePosition&&this.saveParsePosition(),(t=u.parseOneBox(this.stream,false)).code===u.ERR_NOT_ENOUGH_DATA){if(this.processIncompleteBox){if(this.processIncompleteBox(t))continue;return}return}var i;switch(i="uuid"!==(e=t.box).type?e.type:e.uuid,this.boxes.push(e),i){case"mdat":this.mdats.push(e);break;case"moof":this.moofs.push(e);break;case"moov":this.moovStartFound=!0,0===this.mdats.length&&(this.isProgressive=!0);default:void 0!==this[i]&&a.warn("ISOFile","Duplicate Box of type: "+i+", overriding previous occurrence"),this[i]=e}this.updateUsedBytes&&this.updateUsedBytes(e,t)}},f.prototype.checkBuffer=function(t){if(null==t)throw"Buffer must be defined and non empty";if(void 0===t.fileStart)throw"Buffer must have a fileStart property";return 0===t.byteLength?(a.warn("ISOFile","Ignoring empty buffer (fileStart: "+t.fileStart+")"),this.stream.logBufferLevel(),!1):(a.info("ISOFile","Processing buffer (fileStart: "+t.fileStart+")"),t.usedBytes=0,this.stream.insertBuffer(t),this.stream.logBufferLevel(),!!this.stream.initialized()||(a.warn("ISOFile","Not ready to start parsing"),!1))},f.prototype.appendBuffer=function(t,e){var i;if(this.checkBuffer(t))return this.parse(),this.moovStartFound&&!this.moovStartSent&&(this.moovStartSent=!0,this.onMoovStart&&this.onMoovStart()),this.moov?(this.sampleListBuilt||(this.buildSampleLists(),this.sampleListBuilt=!0),this.updateSampleLists(),this.onReady&&!this.readySent&&(this.readySent=!0,this.onReady(this.getInfo())),this.processSamples(e),this.nextSeekPosition?(i=this.nextSeekPosition,this.nextSeekPosition=void 0):i=this.nextParsePosition,this.stream.getEndFilePositionAfter&&(i=this.stream.getEndFilePositionAfter(i))):i=this.nextParsePosition?this.nextParsePosition:0,this.sidx&&this.onSidx&&!this.sidxSent&&(this.onSidx(this.sidx),this.sidxSent=!0),this.meta&&(this.flattenItemInfo&&!this.itemListBuilt&&(this.flattenItemInfo(),this.itemListBuilt=!0),this.processItems&&this.processItems(this.onItem)),this.stream.cleanBuffers&&(a.info("ISOFile","Done processing buffer (fileStart: "+t.fileStart+") - next buffer to fetch should have a fileStart position of "+i),this.stream.logBufferLevel(),this.stream.cleanBuffers(),this.stream.logBufferLevel(!0),a.info("ISOFile","Sample data size in memory: "+this.getAllocatedSampleDataSize())),i},f.prototype.getInfo=function(){var t,e,i,s,r,a,n={},o=new Date("1904-01-01T00:00:00Z").getTime();if(this.moov)for(n.hasMoov=!0,n.duration=this.moov.mvhd.duration,n.timescale=this.moov.mvhd.timescale,n.isFragmented=null!=this.moov.mvex,n.isFragmented&&this.moov.mvex.mehd&&(n.fragment_duration=this.moov.mvex.mehd.fragment_duration),n.isProgressive=this.isProgressive,n.hasIOD=null!=this.moov.iods,n.brands=[],n.brands.push(this.ftyp.major_brand),n.brands=n.brands.concat(this.ftyp.compatible_brands),n.created=new Date(o+1e3*this.moov.mvhd.creation_time),n.modified=new Date(o+1e3*this.moov.mvhd.modification_time),n.tracks=[],n.audioTracks=[],n.videoTracks=[],n.subtitleTracks=[],n.metadataTracks=[],n.hintTracks=[],n.otherTracks=[],t=0;t<this.moov.traks.length;t++){if(a=(i=this.moov.traks[t]).mdia.minf.stbl.stsd.entries[0],s={},n.tracks.push(s),s.id=i.tkhd.track_id,s.name=i.mdia.hdlr.name,s.references=[],i.tref)for(e=0;e<i.tref.boxes.length;e++)r={},s.references.push(r),r.type=i.tref.boxes[e].type,r.track_ids=i.tref.boxes[e].track_ids;i.edts&&(s.edits=i.edts.elst.entries),s.created=new Date(o+1e3*i.tkhd.creation_time),s.modified=new Date(o+1e3*i.tkhd.modification_time),s.movie_duration=i.tkhd.duration,s.movie_timescale=n.timescale,s.layer=i.tkhd.layer,s.alternate_group=i.tkhd.alternate_group,s.volume=i.tkhd.volume,s.matrix=i.tkhd.matrix,s.track_width=i.tkhd.width/65536,s.track_height=i.tkhd.height/65536,s.timescale=i.mdia.mdhd.timescale,s.cts_shift=i.mdia.minf.stbl.cslg,s.duration=i.mdia.mdhd.duration,s.samples_duration=i.samples_duration,s.codec=a.getCodec(),s.kind=i.udta&&i.udta.kinds.length?i.udta.kinds[0]:{schemeURI:"",value:""},s.language=i.mdia.elng?i.mdia.elng.extended_language:i.mdia.mdhd.languageString,s.nb_samples=i.samples.length,s.size=i.samples_size,s.bitrate=8*s.size*s.timescale/s.samples_duration,a.isAudio()?(s.type="audio",n.audioTracks.push(s),s.audio={},s.audio.sample_rate=a.getSampleRate(),s.audio.channel_count=a.getChannelCount(),s.audio.sample_size=a.getSampleSize()):a.isVideo()?(s.type="video",n.videoTracks.push(s),s.video={},s.video.width=a.getWidth(),s.video.height=a.getHeight()):a.isSubtitle()?(s.type="subtitles",n.subtitleTracks.push(s)):a.isHint()?(s.type="metadata",n.hintTracks.push(s)):a.isMetadata()?(s.type="metadata",n.metadataTracks.push(s)):(s.type="metadata",n.otherTracks.push(s))}else n.hasMoov=!1;if(n.mime="",n.hasMoov&&n.tracks){for(n.videoTracks&&n.videoTracks.length>0?n.mime+='video/mp4; codecs="':n.audioTracks&&n.audioTracks.length>0?n.mime+='audio/mp4; codecs="':n.mime+='application/mp4; codecs="',t=0;t<n.tracks.length;t++)0!==t&&(n.mime+=","),n.mime+=n.tracks[t].codec;n.mime+='"; profiles="',n.mime+=this.ftyp.compatible_brands.join(),n.mime+='"'}return n},f.prototype.processSamples=function(t){var e,i;if(this.sampleProcessingStarted){if(this.isFragmentationInitialized&&null!==this.onSegment)for(e=0;e<this.fragmentedTracks.length;e++){var s=this.fragmentedTracks[e];for(i=s.trak;i.nextSample<i.samples.length&&this.sampleProcessingStarted;){a.debug("ISOFile","Creating media fragment on track #"+s.id+" for sample "+i.nextSample);var r=this.createFragment(s.id,i.nextSample,s.segmentStream);if(!r)break;if(s.segmentStream=r,i.nextSample++,(i.nextSample%s.nb_samples==0||t||i.nextSample>=i.samples.length)&&(a.info("ISOFile","Sending fragmented data on track #"+s.id+" for samples ["+Math.max(0,i.nextSample-s.nb_samples)+","+(i.nextSample-1)+"]"),a.info("ISOFile","Sample data size in memory: "+this.getAllocatedSampleDataSize()),this.onSegment&&this.onSegment(s.id,s.user,s.segmentStream.buffer,i.nextSample,t||i.nextSample>=i.samples.length),s.segmentStream=null,s!==this.fragmentedTracks[e]))break}}if(null!==this.onSamples)for(e=0;e<this.extractedTracks.length;e++){var n=this.extractedTracks[e];for(i=n.trak;i.nextSample<i.samples.length&&this.sampleProcessingStarted;){a.debug("ISOFile","Exporting on track #"+n.id+" sample #"+i.nextSample);var o=this.getSample(i,i.nextSample);if(!o)break;if(i.nextSample++,n.samples.push(o),(i.nextSample%n.nb_samples==0||i.nextSample>=i.samples.length)&&(a.debug("ISOFile","Sending samples on track #"+n.id+" for sample "+i.nextSample),this.onSamples&&this.onSamples(n.id,n.user,n.samples),n.samples=[],n!==this.extractedTracks[e]))break}}}},f.prototype.getBox=function(t){var e=this.getBoxes(t,!0);return e.length?e[0]:null},f.prototype.getBoxes=function(t,e){var i=[];return f._sweep.call(this,t,i,e),i},f._sweep=function(t,e,i){for(var s in this.type&&this.type==t&&e.push(this),this.boxes){if(e.length&&i)return;f._sweep.call(this.boxes[s],t,e,i)}},f.prototype.getTrackSamplesInfo=function(t){var e=this.getTrackById(t);return e?e.samples:void 0},f.prototype.getTrackSample=function(t,e){var i=this.getTrackById(t);return this.getSample(i,e)},f.prototype.releaseUsedSamples=function(t,e){var i=0,s=this.getTrackById(t);s.lastValidSample||(s.lastValidSample=0);for(var r=s.lastValidSample;r<e;r++)i+=this.releaseSample(s,r);a.info("ISOFile","Track #"+t+" released samples up to "+e+" (released size: "+i+", remaining: "+this.samplesDataSize+")"),s.lastValidSample=e},f.prototype.start=function(){this.sampleProcessingStarted=!0,this.processSamples(!1)},f.prototype.stop=function(){this.sampleProcessingStarted=!1},f.prototype.flush=function(){a.info("ISOFile","Flushing remaining samples"),this.updateSampleLists(),this.processSamples(!0),this.stream.cleanBuffers(),this.stream.logBufferLevel(!0)},f.prototype.seekTrack=function(t,e,i){var s,r,n,o,h=0,l=0;if(0===i.samples.length)return a.info("ISOFile","No sample in track, cannot seek! Using time "+a.getDurationString(0,1)+" and offset: 0"),{offset:0,time:0};for(s=0;s<i.samples.length;s++){if(r=i.samples[s],0===s)l=0,o=r.timescale;else if(r.cts>t*r.timescale){l=s-1;break}e&&r.is_sync&&(h=s)}for(e&&(l=h),t=i.samples[l].cts,i.nextSample=l;i.samples[l].alreadyRead===i.samples[l].size&&i.samples[l+1];)l++;return n=i.samples[l].offset+i.samples[l].alreadyRead,a.info("ISOFile","Seeking to "+(e?"RAP":"")+" sample #"+i.nextSample+" on track "+i.tkhd.track_id+", time "+a.getDurationString(t,o)+" and offset: "+n),{offset:n,time:t/o}},f.prototype.seek=function(t,e){var i,s,r,n=this.moov,o={offset:1/0,time:1/0};if(this.moov){for(r=0;r<n.traks.length;r++)i=n.traks[r],(s=this.seekTrack(t,e,i)).offset<o.offset&&(o.offset=s.offset),s.time<o.time&&(o.time=s.time);return a.info("ISOFile","Seeking at time "+a.getDurationString(o.time,1)+" needs a buffer with a fileStart position of "+o.offset),o.offset===1/0?o={offset:this.nextParsePosition,time:0}:o.offset=this.stream.getEndFilePositionAfter(o.offset),a.info("ISOFile","Adjusted seek position (after checking data already in buffer): "+o.offset),o}throw"Cannot seek: moov not received!"},f.prototype.equal=function(t){for(var e=0;e<this.boxes.length&&e<t.boxes.length;){var i=this.boxes[e],s=t.boxes[e];if(!u.boxEqual(i,s))return!1;e++}return!0},e.ISOFile=f,f.prototype.lastBoxStartPosition=0,f.prototype.parsingMdat=null,f.prototype.nextParsePosition=0,f.prototype.discardMdatData=!1,f.prototype.processIncompleteBox=function(t){var e;return"mdat"===t.type?(e=new u[t.type+"Box"](t.size),this.parsingMdat=e,this.boxes.push(e),this.mdats.push(e),e.start=t.start,e.hdr_size=t.hdr_size,this.stream.addUsedBytes(e.hdr_size),this.lastBoxStartPosition=e.start+e.size,this.stream.seek(e.start+e.size,!1,this.discardMdatData)?(this.parsingMdat=null,!0):(this.moovStartFound?this.nextParsePosition=this.stream.findEndContiguousBuf():this.nextParsePosition=e.start+e.size,!1)):("moov"===t.type&&(this.moovStartFound=!0,0===this.mdats.length&&(this.isProgressive=!0)),!!this.stream.mergeNextBuffer&&this.stream.mergeNextBuffer()?(this.nextParsePosition=this.stream.getEndPosition(),!0):(t.type?this.moovStartFound?this.nextParsePosition=this.stream.getEndPosition():this.nextParsePosition=this.stream.getPosition()+t.size:this.nextParsePosition=this.stream.getEndPosition(),!1))},f.prototype.hasIncompleteMdat=function(){return null!==this.parsingMdat},f.prototype.processIncompleteMdat=function(){var t;return t=this.parsingMdat,this.stream.seek(t.start+t.size,!1,this.discardMdatData)?(a.debug("ISOFile","Found 'mdat' end in buffered data"),this.parsingMdat=null,!0):(this.nextParsePosition=this.stream.findEndContiguousBuf(),!1)},f.prototype.restoreParsePosition=function(){return this.stream.seek(this.lastBoxStartPosition,!0,this.discardMdatData)},f.prototype.saveParsePosition=function(){this.lastBoxStartPosition=this.stream.getPosition()},f.prototype.updateUsedBytes=function(t,e){this.stream.addUsedBytes&&("mdat"===t.type?(this.stream.addUsedBytes(t.hdr_size),this.discardMdatData&&this.stream.addUsedBytes(t.size-t.hdr_size)):this.stream.addUsedBytes(t.size))},f.prototype.add=u.Box.prototype.add,f.prototype.addBox=u.Box.prototype.addBox,f.prototype.init=function(t){var e=t||{};this.add("ftyp").set("major_brand",e.brands&&e.brands[0]||"iso4").set("minor_version",0).set("compatible_brands",e.brands||["iso4"]);var i=this.add("moov");return i.add("mvhd").set("timescale",e.timescale||600).set("rate",e.rate||65536).set("creation_time",0).set("modification_time",0).set("duration",e.duration||0).set("volume",e.width?0:256).set("matrix",[65536,0,0,0,65536,0,0,0,1073741824]).set("next_track_id",1),i.add("mvex"),this},f.prototype.addTrack=function(t){this.moov||this.init(t);var e=t||{};e.width=e.width||320,e.height=e.height||320,e.id=e.id||this.moov.mvhd.next_track_id,e.type=e.type||"avc1";var i=this.moov.add("trak");this.moov.mvhd.next_track_id=e.id+1,i.add("tkhd").set("flags",u.TKHD_FLAG_ENABLED|u.TKHD_FLAG_IN_MOVIE|u.TKHD_FLAG_IN_PREVIEW).set("creation_time",0).set("modification_time",0).set("track_id",e.id).set("duration",e.duration||0).set("layer",e.layer||0).set("alternate_group",0).set("volume",1).set("matrix",[0,0,0,0,0,0,0,0,0]).set("width",e.width<<16).set("height",e.height<<16);var s=i.add("mdia");s.add("mdhd").set("creation_time",0).set("modification_time",0).set("timescale",e.timescale||1).set("duration",e.media_duration||0).set("language",e.language||"und"),s.add("hdlr").set("handler",e.hdlr||"vide").set("name",e.name||"Track created with MP4Box.js"),s.add("elng").set("extended_language",e.language||"fr-FR");var r=s.add("minf");if(void 0!==u[e.type+"SampleEntry"]){var a=new u[e.type+"SampleEntry"];a.data_reference_index=1;var o="";for(var h in u.sampleEntryCodes)for(var l=u.sampleEntryCodes[h],d=0;d<l.length;d++)if(l.indexOf(e.type)>-1){o=h;break}switch(o){case"Visual":if(r.add("vmhd").set("graphicsmode",0).set("opcolor",[0,0,0]),a.set("width",e.width).set("height",e.height).set("horizresolution",72<<16).set("vertresolution",72<<16).set("frame_count",1).set("compressorname",e.type+" Compressor").set("depth",24),e.avcDecoderConfigRecord){var p=new u.avcCBox,c=new n(e.avcDecoderConfigRecord);p.parse(c),a.addBox(p)}break;case"Audio":r.add("smhd").set("balance",e.balance||0),a.set("channel_count",e.channel_count||2).set("samplesize",e.samplesize||16).set("samplerate",e.samplerate||65536);break;case"Hint":r.add("hmhd");break;case"Subtitle":if(r.add("sthd"),"stpp"===e.type)a.set("namespace",e.namespace||"nonamespace").set("schema_location",e.schema_location||"").set("auxiliary_mime_types",e.auxiliary_mime_types||"");break;default:r.add("nmhd")}e.description&&a.addBox(e.description),e.description_boxes&&e.description_boxes.forEach((function(t){a.addBox(t)})),r.add("dinf").add("dref").addEntry((new u["url Box"]).set("flags",1));var f=r.add("stbl");return f.add("stsd").addEntry(a),f.add("stts").set("sample_counts",[]).set("sample_deltas",[]),f.add("stsc").set("first_chunk",[]).set("samples_per_chunk",[]).set("sample_description_index",[]),f.add("stco").set("chunk_offsets",[]),f.add("stsz").set("sample_sizes",[]),this.moov.mvex.add("trex").set("track_id",e.id).set("default_sample_description_index",e.default_sample_description_index||1).set("default_sample_duration",e.default_sample_duration||0).set("default_sample_size",e.default_sample_size||0).set("default_sample_flags",e.default_sample_flags||0),this.buildTrakSampleLists(i),e.id}},u.Box.prototype.computeSize=function(t){var e=t||new o;e.endianness=o.BIG_ENDIAN,this.write(e)},f.prototype.addSample=function(t,e,i){var s=i||{},r={},a=this.getTrackById(t);if(null!==a){r.number=a.samples.length,r.track_id=a.tkhd.track_id,r.timescale=a.mdia.mdhd.timescale,r.description_index=s.sample_description_index?s.sample_description_index-1:0,r.description=a.mdia.minf.stbl.stsd.entries[r.description_index],r.data=e,r.size=e.byteLength,r.alreadyRead=r.size,r.duration=s.duration||1,r.cts=s.cts||0,r.dts=s.dts||0,r.is_sync=s.is_sync||!1,r.is_leading=s.is_leading||0,r.depends_on=s.depends_on||0,r.is_depended_on=s.is_depended_on||0,r.has_redundancy=s.has_redundancy||0,r.degradation_priority=s.degradation_priority||0,r.offset=0,r.subsamples=s.subsamples,a.samples.push(r),a.samples_size+=r.size,a.samples_duration+=r.duration,a.first_dts||(a.first_dts=s.dts),this.processSamples();var n=this.createSingleSampleMoof(r);return this.addBox(n),n.computeSize(),n.trafs[0].truns[0].data_offset=n.size+8,this.add("mdat").data=new Uint8Array(e),r}},f.prototype.createSingleSampleMoof=function(t){var e=0;e=t.is_sync?1<<25:65536;var i=new u.moofBox;i.add("mfhd").set("sequence_number",this.nextMoofNumber),this.nextMoofNumber++;var s=i.add("traf"),r=this.getTrackById(t.track_id);return s.add("tfhd").set("track_id",t.track_id).set("flags",u.TFHD_FLAG_DEFAULT_BASE_IS_MOOF),s.add("tfdt").set("baseMediaDecodeTime",t.dts-(r.first_dts||0)),s.add("trun").set("flags",u.TRUN_FLAGS_DATA_OFFSET|u.TRUN_FLAGS_DURATION|u.TRUN_FLAGS_SIZE|u.TRUN_FLAGS_FLAGS|u.TRUN_FLAGS_CTS_OFFSET).set("data_offset",0).set("first_sample_flags",0).set("sample_count",1).set("sample_duration",[t.duration]).set("sample_size",[t.size]).set("sample_flags",[e]).set("sample_composition_time_offset",[t.cts-t.dts]),i},f.prototype.lastMoofIndex=0,f.prototype.samplesDataSize=0,f.prototype.resetTables=function(){var t,e,i,s,r,a;for(this.initial_duration=this.moov.mvhd.duration,this.moov.mvhd.duration=0,t=0;t<this.moov.traks.length;t++){(e=this.moov.traks[t]).tkhd.duration=0,e.mdia.mdhd.duration=0,(e.mdia.minf.stbl.stco||e.mdia.minf.stbl.co64).chunk_offsets=[],(i=e.mdia.minf.stbl.stsc).first_chunk=[],i.samples_per_chunk=[],i.sample_description_index=[],(e.mdia.minf.stbl.stsz||e.mdia.minf.stbl.stz2).sample_sizes=[],(s=e.mdia.minf.stbl.stts).sample_counts=[],s.sample_deltas=[],(r=e.mdia.minf.stbl.ctts)&&(r.sample_counts=[],r.sample_offsets=[]),a=e.mdia.minf.stbl.stss;var n=e.mdia.minf.stbl.boxes.indexOf(a);-1!=n&&(e.mdia.minf.stbl.boxes[n]=null)}},f.initSampleGroups=function(t,e,i,s,r){var a,n,o,h;function l(t,e,i){this.grouping_type=t,this.grouping_type_parameter=e,this.sbgp=i,this.last_sample_in_run=-1,this.entry_index=-1}for(e&&(e.sample_groups_info=[]),t.sample_groups_info||(t.sample_groups_info=[]),n=0;n<i.length;n++){for(h=i[n].grouping_type+"/"+i[n].grouping_type_parameter,o=new l(i[n].grouping_type,i[n].grouping_type_parameter,i[n]),e&&(e.sample_groups_info[h]=o),t.sample_groups_info[h]||(t.sample_groups_info[h]=o),a=0;a<s.length;a++)s[a].grouping_type===i[n].grouping_type&&(o.description=s[a],o.description.used=!0);if(r)for(a=0;a<r.length;a++)r[a].grouping_type===i[n].grouping_type&&(o.fragment_description=r[a],o.fragment_description.used=!0,o.is_fragment=!0)}if(e){if(r)for(n=0;n<r.length;n++)!r[n].used&&r[n].version>=2&&(h=r[n].grouping_type+"/0",(o=new l(r[n].grouping_type,0)).is_fragment=!0,e.sample_groups_info[h]||(e.sample_groups_info[h]=o))}else for(n=0;n<s.length;n++)!s[n].used&&s[n].version>=2&&(h=s[n].grouping_type+"/0",o=new l(s[n].grouping_type,0),t.sample_groups_info[h]||(t.sample_groups_info[h]=o))},f.setSampleGroupProperties=function(t,e,i,s){var r,a;for(r in e.sample_groups=[],s){var n;if(e.sample_groups[r]={},e.sample_groups[r].grouping_type=s[r].grouping_type,e.sample_groups[r].grouping_type_parameter=s[r].grouping_type_parameter,i>=s[r].last_sample_in_run&&(s[r].last_sample_in_run<0&&(s[r].last_sample_in_run=0),s[r].entry_index++,s[r].entry_index<=s[r].sbgp.entries.length-1&&(s[r].last_sample_in_run+=s[r].sbgp.entries[s[r].entry_index].sample_count)),s[r].entry_index<=s[r].sbgp.entries.length-1?e.sample_groups[r].group_description_index=s[r].sbgp.entries[s[r].entry_index].group_description_index:e.sample_groups[r].group_description_index=-1,0!==e.sample_groups[r].group_description_index)n=s[r].fragment_description?s[r].fragment_description:s[r].description,e.sample_groups[r].group_description_index>0?(a=e.sample_groups[r].group_description_index>65535?(e.sample_groups[r].group_description_index>>16)-1:e.sample_groups[r].group_description_index-1,n&&a>=0&&(e.sample_groups[r].description=n.entries[a])):n&&n.version>=2&&n.default_group_description_index>0&&(e.sample_groups[r].description=n.entries[n.default_group_description_index-1])}},f.process_sdtp=function(t,e,i){e&&(t?(e.is_leading=t.is_leading[i],e.depends_on=t.sample_depends_on[i],e.is_depended_on=t.sample_is_depended_on[i],e.has_redundancy=t.sample_has_redundancy[i]):(e.is_leading=0,e.depends_on=0,e.is_depended_on=0,e.has_redundancy=0))},f.prototype.buildSampleLists=function(){var t,e;for(t=0;t<this.moov.traks.length;t++)e=this.moov.traks[t],this.buildTrakSampleLists(e)},f.prototype.buildTrakSampleLists=function(t){var e,i,s,r,a,n,o,h,l,d,u,p,c,_,m,g,y,b,S,v,w,x,U,A;if(t.samples=[],t.samples_duration=0,t.samples_size=0,i=t.mdia.minf.stbl.stco||t.mdia.minf.stbl.co64,s=t.mdia.minf.stbl.stsc,r=t.mdia.minf.stbl.stsz||t.mdia.minf.stbl.stz2,a=t.mdia.minf.stbl.stts,n=t.mdia.minf.stbl.ctts,o=t.mdia.minf.stbl.stss,h=t.mdia.minf.stbl.stsd,l=t.mdia.minf.stbl.subs,p=t.mdia.minf.stbl.stdp,d=t.mdia.minf.stbl.sbgps,u=t.mdia.minf.stbl.sgpds,b=-1,S=-1,v=-1,w=-1,x=0,U=0,A=0,f.initSampleGroups(t,null,d,u),void 0!==r){for(e=0;e<r.sample_sizes.length;e++){var T={};T.number=e,T.track_id=t.tkhd.track_id,T.timescale=t.mdia.mdhd.timescale,T.alreadyRead=0,t.samples[e]=T,T.size=r.sample_sizes[e],t.samples_size+=T.size,0===e?(_=1,c=0,T.chunk_index=_,T.chunk_run_index=c,y=s.samples_per_chunk[c],g=0,m=c+1<s.first_chunk.length?s.first_chunk[c+1]-1:1/0):e<y?(T.chunk_index=_,T.chunk_run_index=c):(_++,T.chunk_index=_,g=0,_<=m||(m=++c+1<s.first_chunk.length?s.first_chunk[c+1]-1:1/0),T.chunk_run_index=c,y+=s.samples_per_chunk[c]),T.description_index=s.sample_description_index[T.chunk_run_index]-1,T.description=h.entries[T.description_index],T.offset=i.chunk_offsets[T.chunk_index-1]+g,g+=T.size,e>b&&(S++,b<0&&(b=0),b+=a.sample_counts[S]),e>0?(t.samples[e-1].duration=a.sample_deltas[S],t.samples_duration+=t.samples[e-1].duration,T.dts=t.samples[e-1].dts+t.samples[e-1].duration):T.dts=0,n?(e>=v&&(w++,v<0&&(v=0),v+=n.sample_counts[w]),T.cts=t.samples[e].dts+n.sample_offsets[w]):T.cts=T.dts,o?(e==o.sample_numbers[x]-1?(T.is_sync=!0,x++):(T.is_sync=!1,T.degradation_priority=0),l&&l.entries[U].sample_delta+A==e+1&&(T.subsamples=l.entries[U].subsamples,A+=l.entries[U].sample_delta,U++)):T.is_sync=!0,f.process_sdtp(t.mdia.minf.stbl.sdtp,T,T.number),T.degradation_priority=p?p.priority[e]:0,l&&l.entries[U].sample_delta+A==e&&(T.subsamples=l.entries[U].subsamples,A+=l.entries[U].sample_delta),(d.length>0||u.length>0)&&f.setSampleGroupProperties(t,T,e,t.sample_groups_info)}e>0&&(t.samples[e-1].duration=Math.max(t.mdia.mdhd.duration-t.samples[e-1].dts,0),t.samples_duration+=t.samples[e-1].duration)}},f.prototype.updateSampleLists=function(){var t,e,i,s,r,a,n,o,h,l,d,p,c,_,m;if(void 0!==this.moov)for(;this.lastMoofIndex<this.moofs.length;)if(h=this.moofs[this.lastMoofIndex],this.lastMoofIndex++,"moof"==h.type)for(l=h,t=0;t<l.trafs.length;t++){for(d=l.trafs[t],p=this.getTrackById(d.tfhd.track_id),c=this.getTrexById(d.tfhd.track_id),s=d.tfhd.flags&u.TFHD_FLAG_SAMPLE_DESC?d.tfhd.default_sample_description_index:c?c.default_sample_description_index:1,r=d.tfhd.flags&u.TFHD_FLAG_SAMPLE_DUR?d.tfhd.default_sample_duration:c?c.default_sample_duration:0,a=d.tfhd.flags&u.TFHD_FLAG_SAMPLE_SIZE?d.tfhd.default_sample_size:c?c.default_sample_size:0,n=d.tfhd.flags&u.TFHD_FLAG_SAMPLE_FLAGS?d.tfhd.default_sample_flags:c?c.default_sample_flags:0,d.sample_number=0,d.sbgps.length>0&&f.initSampleGroups(p,d,d.sbgps,p.mdia.minf.stbl.sgpds,d.sgpds),e=0;e<d.truns.length;e++){var g=d.truns[e];for(i=0;i<g.sample_count;i++){(_={}).moof_number=this.lastMoofIndex,_.number_in_traf=d.sample_number,d.sample_number++,_.number=p.samples.length,d.first_sample_index=p.samples.length,p.samples.push(_),_.track_id=p.tkhd.track_id,_.timescale=p.mdia.mdhd.timescale,_.description_index=s-1,_.description=p.mdia.minf.stbl.stsd.entries[_.description_index],_.size=a,g.flags&u.TRUN_FLAGS_SIZE&&(_.size=g.sample_size[i]),p.samples_size+=_.size,_.duration=r,g.flags&u.TRUN_FLAGS_DURATION&&(_.duration=g.sample_duration[i]),p.samples_duration+=_.duration,p.first_traf_merged||i>0?_.dts=p.samples[p.samples.length-2].dts+p.samples[p.samples.length-2].duration:(d.tfdt?_.dts=d.tfdt.baseMediaDecodeTime:_.dts=0,p.first_traf_merged=!0),_.cts=_.dts,g.flags&u.TRUN_FLAGS_CTS_OFFSET&&(_.cts=_.dts+g.sample_composition_time_offset[i]),m=n,g.flags&u.TRUN_FLAGS_FLAGS?m=g.sample_flags[i]:0===i&&g.flags&u.TRUN_FLAGS_FIRST_FLAG&&(m=g.first_sample_flags),_.is_sync=!(m>>16&1),_.is_leading=m>>26&3,_.depends_on=m>>24&3,_.is_depended_on=m>>22&3,_.has_redundancy=m>>20&3,_.degradation_priority=65535&m;var y=!!(d.tfhd.flags&u.TFHD_FLAG_BASE_DATA_OFFSET),b=!!(d.tfhd.flags&u.TFHD_FLAG_DEFAULT_BASE_IS_MOOF),S=!!(g.flags&u.TRUN_FLAGS_DATA_OFFSET),v=0;v=y?d.tfhd.base_data_offset:b||0===e?l.start:o,_.offset=0===e&&0===i?S?v+g.data_offset:v:o,o=_.offset+_.size,(d.sbgps.length>0||d.sgpds.length>0||p.mdia.minf.stbl.sbgps.length>0||p.mdia.minf.stbl.sgpds.length>0)&&f.setSampleGroupProperties(p,_,_.number_in_traf,d.sample_groups_info)}}if(d.subs){p.has_fragment_subsamples=!0;var w=d.first_sample_index;for(e=0;e<d.subs.entries.length;e++)w+=d.subs.entries[e].sample_delta,(_=p.samples[w-1]).subsamples=d.subs.entries[e].subsamples}}},f.prototype.getSample=function(t,e){var i,s=t.samples[e];if(!this.moov)return null;if(s.data){if(s.alreadyRead==s.size)return s}else s.data=new Uint8Array(s.size),s.alreadyRead=0,this.samplesDataSize+=s.size,a.debug("ISOFile","Allocating sample #"+e+" on track #"+t.tkhd.track_id+" of size "+s.size+" (total: "+this.samplesDataSize+")");for(;;){var r=this.stream.findPosition(!0,s.offset+s.alreadyRead,!1);if(!(r>-1))return null;var n=(i=this.stream.buffers[r]).byteLength-(s.offset+s.alreadyRead-i.fileStart);if(s.size-s.alreadyRead<=n)return a.debug("ISOFile","Getting sample #"+e+" data (alreadyRead: "+s.alreadyRead+" offset: "+(s.offset+s.alreadyRead-i.fileStart)+" read size: "+(s.size-s.alreadyRead)+" full size: "+s.size+")"),o.memcpy(s.data.buffer,s.alreadyRead,i,s.offset+s.alreadyRead-i.fileStart,s.size-s.alreadyRead),i.usedBytes+=s.size-s.alreadyRead,this.stream.logBufferLevel(),s.alreadyRead=s.size,s;if(0===n)return null;a.debug("ISOFile","Getting sample #"+e+" partial data (alreadyRead: "+s.alreadyRead+" offset: "+(s.offset+s.alreadyRead-i.fileStart)+" read size: "+n+" full size: "+s.size+")"),o.memcpy(s.data.buffer,s.alreadyRead,i,s.offset+s.alreadyRead-i.fileStart,n),s.alreadyRead+=n,i.usedBytes+=n,this.stream.logBufferLevel()}},f.prototype.releaseSample=function(t,e){var i=t.samples[e];return i.data?(this.samplesDataSize-=i.size,i.data=null,i.alreadyRead=0,i.size):0},f.prototype.getAllocatedSampleDataSize=function(){return this.samplesDataSize},f.prototype.getCodecs=function(){var t,e="";for(t=0;t<this.moov.traks.length;t++){t>0&&(e+=","),e+=this.moov.traks[t].mdia.minf.stbl.stsd.entries[0].getCodec()}return e},f.prototype.getTrexById=function(t){var e;if(!this.moov||!this.moov.mvex)return null;for(e=0;e<this.moov.mvex.trexs.length;e++){var i=this.moov.mvex.trexs[e];if(i.track_id==t)return i}return null},f.prototype.getTrackById=function(t){if(void 0===this.moov)return null;for(var e=0;e<this.moov.traks.length;e++){var i=this.moov.traks[e];if(i.tkhd.track_id==t)return i}return null},f.prototype.items=[],f.prototype.itemsDataSize=0,f.prototype.flattenItemInfo=function(){var t,e,i,s=this.items,r=this.meta;if(null!=r&&void 0!==r.hdlr&&void 0!==r.iinf){for(t=0;t<r.iinf.item_infos.length;t++)(i={}).id=r.iinf.item_infos[t].item_ID,s[i.id]=i,i.ref_to=[],i.name=r.iinf.item_infos[t].item_name,r.iinf.item_infos[t].protection_index>0&&(i.protection=r.ipro.protections[r.iinf.item_infos[t].protection_index-1]),r.iinf.item_infos[t].item_type?i.type=r.iinf.item_infos[t].item_type:i.type="mime",i.content_type=r.iinf.item_infos[t].content_type,i.content_encoding=r.iinf.item_infos[t].content_encoding;if(r.iloc)for(t=0;t<r.iloc.items.length;t++){var n=r.iloc.items[t];switch(i=s[n.item_ID],0!==n.data_reference_index&&(a.warn("Item storage with reference to other files: not supported"),i.source=r.dinf.boxes[n.data_reference_index-1]),n.construction_method){case 0:break;case 1:case 2:a.warn("Item storage with construction_method : not supported")}for(i.extents=[],i.size=0,e=0;e<n.extents.length;e++)i.extents[e]={},i.extents[e].offset=n.extents[e].extent_offset+n.base_offset,i.extents[e].length=n.extents[e].extent_length,i.extents[e].alreadyRead=0,i.size+=i.extents[e].length}if(r.pitm&&(s[r.pitm.item_id].primary=!0),r.iref)for(t=0;t<r.iref.references.length;t++){var o=r.iref.references[t];for(e=0;e<o.references.length;e++)s[o.from_item_ID].ref_to.push({type:o.type,id:o.references[e]})}if(r.iprp)for(var h=0;h<r.iprp.ipmas.length;h++){var l=r.iprp.ipmas[h];for(t=0;t<l.associations.length;t++){var d=l.associations[t];for(void 0===(i=s[d.id]).properties&&(i.properties={},i.properties.boxes=[]),e=0;e<d.props.length;e++){var u=d.props[e];if(u.property_index>0&&u.property_index-1<r.iprp.ipco.boxes.length){var p=r.iprp.ipco.boxes[u.property_index-1];i.properties[p.type]=p,i.properties.boxes.push(p)}}}}}},f.prototype.getItem=function(t){var e,i;if(!this.meta)return null;if(!(i=this.items[t]).data&&i.size)i.data=new Uint8Array(i.size),i.alreadyRead=0,this.itemsDataSize+=i.size,a.debug("ISOFile","Allocating item #"+t+" of size "+i.size+" (total: "+this.itemsDataSize+")");else if(i.alreadyRead===i.size)return i;for(var s=0;s<i.extents.length;s++){var r=i.extents[s];if(r.alreadyRead!==r.length){var n=this.stream.findPosition(!0,r.offset+r.alreadyRead,!1);if(!(n>-1))return null;var h=(e=this.stream.buffers[n]).byteLength-(r.offset+r.alreadyRead-e.fileStart);if(!(r.length-r.alreadyRead<=h))return a.debug("ISOFile","Getting item #"+t+" extent #"+s+" partial data (alreadyRead: "+r.alreadyRead+" offset: "+(r.offset+r.alreadyRead-e.fileStart)+" read size: "+h+" full extent size: "+r.length+" full item size: "+i.size+")"),o.memcpy(i.data.buffer,i.alreadyRead,e,r.offset+r.alreadyRead-e.fileStart,h),r.alreadyRead+=h,i.alreadyRead+=h,e.usedBytes+=h,this.stream.logBufferLevel(),null;a.debug("ISOFile","Getting item #"+t+" extent #"+s+" data (alreadyRead: "+r.alreadyRead+" offset: "+(r.offset+r.alreadyRead-e.fileStart)+" read size: "+(r.length-r.alreadyRead)+" full extent size: "+r.length+" full item size: "+i.size+")"),o.memcpy(i.data.buffer,i.alreadyRead,e,r.offset+r.alreadyRead-e.fileStart,r.length-r.alreadyRead),e.usedBytes+=r.length-r.alreadyRead,this.stream.logBufferLevel(),i.alreadyRead+=r.length-r.alreadyRead,r.alreadyRead=r.length}}return i.alreadyRead===i.size?i:null},f.prototype.releaseItem=function(t){var e=this.items[t];if(e.data){this.itemsDataSize-=e.size,e.data=null,e.alreadyRead=0;for(var i=0;i<e.extents.length;i++){e.extents[i].alreadyRead=0}return e.size}return 0},f.prototype.processItems=function(t){for(var e in this.items){var i=this.items[e];this.getItem(i.id),t&&!i.sent&&(t(i),i.sent=!0,i.data=null)}},f.prototype.hasItem=function(t){for(var e in this.items){var i=this.items[e];if(i.name===t)return i.id}return-1},f.prototype.getMetaHandler=function(){return this.meta?this.meta.hdlr.handler:null},f.prototype.getPrimaryItem=function(){return this.meta&&this.meta.pitm?this.getItem(this.meta.pitm.item_id):null},f.prototype.itemToFragmentedTrackFile=function(t){var e=t||{},i=null;if(null==(i=e.itemId?this.getItem(e.itemId):this.getPrimaryItem()))return null;var s=new f;s.discardMdatData=!1;var r={type:i.type,description_boxes:i.properties.boxes};i.properties.ispe&&(r.width=i.properties.ispe.image_width,r.height=i.properties.ispe.image_height);var a=s.addTrack(r);return a?(s.addSample(a,i.data),s):null},f.prototype.write=function(t){for(var e=0;e<this.boxes.length;e++)this.boxes[e].write(t)},f.prototype.createFragment=function(t,e,i){var s=this.getTrackById(t),r=this.getSample(s,e);if(null==r)return r=s.samples[e],this.nextSeekPosition?this.nextSeekPosition=Math.min(r.offset+r.alreadyRead,this.nextSeekPosition):this.nextSeekPosition=s.samples[e].offset+r.alreadyRead,null;var n=i||new o;n.endianness=o.BIG_ENDIAN;var h=this.createSingleSampleMoof(r);h.write(n),h.trafs[0].truns[0].data_offset=h.size+8,a.debug("MP4Box","Adjusting data_offset with new value "+h.trafs[0].truns[0].data_offset),n.adjustUint32(h.trafs[0].truns[0].data_offset_position,h.trafs[0].truns[0].data_offset);var l=new u.mdatBox;return l.data=r.data,l.write(n),n},f.writeInitializationSegment=function(t,e,i,s){var r;a.debug("ISOFile","Generating initialization segment");var n=new o;n.endianness=o.BIG_ENDIAN,t.write(n);var h=e.add("mvex");for(i&&h.add("mehd").set("fragment_duration",i),r=0;r<e.traks.length;r++)h.add("trex").set("track_id",e.traks[r].tkhd.track_id).set("default_sample_description_index",1).set("default_sample_duration",s).set("default_sample_size",0).set("default_sample_flags",65536);return e.write(n),n.buffer},f.prototype.save=function(t){var e=new o;e.endianness=o.BIG_ENDIAN,this.write(e),e.save(t)},f.prototype.getBuffer=function(){var t=new o;return t.endianness=o.BIG_ENDIAN,this.write(t),t.buffer},f.prototype.initializeSegmentation=function(){var t,e,i,s;for(null===this.onSegment&&a.warn("MP4Box","No segmentation callback set!"),this.isFragmentationInitialized||(this.isFragmentationInitialized=!0,this.nextMoofNumber=0,this.resetTables()),e=[],t=0;t<this.fragmentedTracks.length;t++){var r=new u.moovBox;r.mvhd=this.moov.mvhd,r.boxes.push(r.mvhd),i=this.getTrackById(this.fragmentedTracks[t].id),r.boxes.push(i),r.traks.push(i),(s={}).id=i.tkhd.track_id,s.user=this.fragmentedTracks[t].user,s.buffer=f.writeInitializationSegment(this.ftyp,r,this.moov.mvex&&this.moov.mvex.mehd?this.moov.mvex.mehd.fragment_duration:void 0,this.moov.traks[t].samples.length>0?this.moov.traks[t].samples[0].duration:0),e.push(s)}return e},u.Box.prototype.printHeader=function(t){this.size+=8,this.size>h&&(this.size+=8),"uuid"===this.type&&(this.size+=16),t.log(t.indent+"size:"+this.size),t.log(t.indent+"type:"+this.type)},u.FullBox.prototype.printHeader=function(t){this.size+=4,u.Box.prototype.printHeader.call(this,t),t.log(t.indent+"version:"+this.version),t.log(t.indent+"flags:"+this.flags)},u.Box.prototype.print=function(t){this.printHeader(t)},u.ContainerBox.prototype.print=function(t){this.printHeader(t);for(var e=0;e<this.boxes.length;e++)if(this.boxes[e]){var i=t.indent;t.indent+=" ",this.boxes[e].print(t),t.indent=i}},f.prototype.print=function(t){t.indent="";for(var e=0;e<this.boxes.length;e++)this.boxes[e]&&this.boxes[e].print(t)},u.mvhdBox.prototype.print=function(t){u.FullBox.prototype.printHeader.call(this,t),t.log(t.indent+"creation_time: "+this.creation_time),t.log(t.indent+"modification_time: "+this.modification_time),t.log(t.indent+"timescale: "+this.timescale),t.log(t.indent+"duration: "+this.duration),t.log(t.indent+"rate: "+this.rate),t.log(t.indent+"volume: "+(this.volume>>8)),t.log(t.indent+"matrix: "+this.matrix.join(", ")),t.log(t.indent+"next_track_id: "+this.next_track_id)},u.tkhdBox.prototype.print=function(t){u.FullBox.prototype.printHeader.call(this,t),t.log(t.indent+"creation_time: "+this.creation_time),t.log(t.indent+"modification_time: "+this.modification_time),t.log(t.indent+"track_id: "+this.track_id),t.log(t.indent+"duration: "+this.duration),t.log(t.indent+"volume: "+(this.volume>>8)),t.log(t.indent+"matrix: "+this.matrix.join(", ")),t.log(t.indent+"layer: "+this.layer),t.log(t.indent+"alternate_group: "+this.alternate_group),t.log(t.indent+"width: "+this.width),t.log(t.indent+"height: "+this.height)};var _={createFile:function(t,e){var i=void 0===t||t,s=new f(e);return s.discardMdatData=!i,s}};e.createFile=_.createFile}));He.Log,He.MP4BoxStream,He.DataStream,He.MultiBufferStream,He.MPEG4DescriptorParser,He.BoxParser,He.XMLSubtitlein4Parser,He.Textin4Parser,He.ISOFile,He.createFile;class Ve extends Ie{constructor(t){super(t),this.TAG_NAME="Fmp4Loader",this.player=t,this.mp4Box=He.createFile(),this.offset=0,this.videoTrackId=null,this.audioTrackId=null,this.isHevc=!1,this._listenMp4Box(),t.debug.log(this.TAG_NAME,"init")}destroy(){this.mp4Box&&(this.mp4Box.flush(),this.mp4Box=null),this.offset=0,this.videoTrackId=null,this.audioTrackId=null,this.isHevc=!1,this.player.debug.log(this.TAG_NAME,"destroy")}_listenMp4Box(){this.mp4Box.onReady=this.onReady.bind(this),this.mp4Box.onError=this.onError.bind(this),this.mp4Box.onSamples=this.onSamples.bind(this)}onReady(t){this.player.debug.log(this.TAG_NAME,"onReady",t);const e=t.videoTracks[0],i=t.audioTracks[0];if(e){this.videoTrackId=e.id;const t=this.getSeqHeader(e);t&&(this.player.debug.log(this.TAG_NAME,"seqHeader",t),this._doDecodeByFmp4(t,b,0,!0,0)),this.mp4Box.setExtractionOptions(e.id)}if(i){this.audioTrackId=i.id;const t=i.audio||{},e=Bt.indexOf(t.sample_rate),s=i.codec.replace("mp4a.40.","");this.mp4Box.setExtractionOptions(i.id);const r={profile:parseInt(s,10),sampleRate:e,channel:t.channel_count},a=At(r);this.player.debug.log(this.TAG_NAME,"aacADTSHeader",a,"config",r),this._doDecodeByFmp4(a,y,0,!1,0)}this.mp4Box.start()}onError(t){this.player.debug.error(this.TAG_NAME,"mp4Box onError",t)}onSamples(t,e,i){if(t===this.videoTrackId)for(const t of i){const e=t.data,i=t.is_sync,s=1e3*t.cts/t.timescale;t.duration,t.timescale,this.player._updateStats({vbps:e.byteLength,dts:s}),i&&this.calcIframeIntervalTimestamp(s);let r=null;r=this.isHevc?ve(e,i):ue(e,i),this._doDecodeByFmp4(r,b,s,i,0)}else if(t===this.audioTrackId)for(const t of i){const e=t.data;this.player._updateStats({abps:e.byteLength});const i=1e3*t.cts/t.timescale;t.duration,t.timescale;const s=new Uint8Array(e.byteLength+2);s.set([175,1],0),s.set(e,2),this._doDecodeByFmp4(s,y,i,!1,0)}else this.player.debug.warn(this.TAG_NAME,"onSamples() trackId error",t)}getSeqHeader(t){const e=this.mp4Box.getTrackById(t.id);for(const t of e.mdia.minf.stbl.stsd.entries)if(t.avcC||t.hvcC){const e=new He.DataStream(void 0,0,He.DataStream.BIG_ENDIAN);let i=[];t.avcC?(t.avcC.write(e),i=[23,0,0,0,0]):(this.isHevc=!0,t.hvcC.write(e),i=[28,0,0,0,0]);const s=new Uint8Array(e.buffer,8),r=new Uint8Array(i.length+s.length);return r.set(i,0),r.set(s,i.length),r}return null}dispatch(t){let e=new Uint8Array(t);"string"!=typeof t?"object"==typeof t?(e.buffer.fileStart=this.offset,this.offset+=e.byteLength,this.mp4Box.appendBuffer(e.buffer)):this.player.debug.warn(this.TAG_NAME,"dispatch()","data is not object",t):this.player.debug.warn(this.TAG_NAME,"dispatch()","data is string",t)}}class We{constructor(t){return new(We.getLoaderFactory(t))(t)}static getLoaderFactory(t){const e=t._opt.demuxType;return e===u?Me:e===d?Ne:e===c?ze:e===f?Ge:e===_?Ve:Oe}}const Ye=2097152,$e="fetch",je="xhr",qe="arraybuffer",Ke="text",Xe="json",Je="real_time_speed",Ze=Object.prototype.toString;function Qe(t){if("[object Object]"!==Ze.call(t))return!1;const e=Object.getPrototypeOf(t);return null===e||e===Object.prototype}function ti(t){if(!t||null===t[0]||void 0===t[0]||0===t[0]&&(null===t[1]||void 0===t[1]))return;let e="bytes="+t[0]+"-";return t[1]&&(e+=t[1]),e}function ei(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function ii(t,e){if(!t)return;if(!e)return t;let i;const s=Object.keys(e).map((t=>{if(i=e[t],null!=i)return Array.isArray(i)?t+="[]":i=[i],i.map((e=>{var i;return i=e,"[object Date]"===Ze.call(i)?e=e.toISOString():function(t){return null!==t&&"object"==typeof t}(e)&&(e=JSON.stringify(e)),`${ei(t)}=${ei(e)}`})).join("&")})).filter(Boolean).join("&");if(s){const e=t.indexOf("#");-1!==e&&(t=t.slice(0,e)),t+=(-1===t.indexOf("?")?"?":"&")+s}return t}function si(t,e,i,s,r,a,n,o,h,l,d){r=null!=r?parseFloat(r):null,s=parseInt(s||"0",10),Number.isNaN(s)&&(s=0);return{data:t,done:e,option:{range:h,vid:l,index:o,contentLength:s,age:r,startTime:a,firstByteTime:n,endTime:Date.now(),priOptions:d},response:i}}function ri(t,e){return Math.round(8*t*1e3/e/1024)}class ai extends Error{retryCount=0;isTimeout=!1;loaderType=$e;startTime=0;endTime=0;options={};constructor(t,e,i,s){super(s),this.url=t,this.request=e,this.response=i}}class ni extends t{_abortController=null;_timeoutTimer=null;_reader=null;_response=null;_aborted=!1;_index=-1;_range=null;_receivedLength=0;_running=!1;_logger=null;_vid="";_onProcessMinLen=0;_onCancel=null;_priOptions=null;TAG_NAME="FetchLoader";constructor(t){super(),this.player=t}load(t){let{url:e,vid:i,timeout:s,responseType:r,onProgress:a,index:n,onTimeout:o,onCancel:h,range:l,transformResponse:d,request:u,params:p,logger:c,method:f,headers:_,body:m,mode:g,credentials:y,cache:b,redirect:S,referrer:v,referrerPolicy:w,onProcessMinLen:x,priOptions:U}=t;this._aborted=!1,this._onProcessMinLen=x,this._onCancel=h,this._abortController="undefined"!=typeof AbortController&&new AbortController,this._running=!0,this._index=n,this._range=l||[0,0],this._vid=i||e,this._priOptions=U||{};const A={method:f,headers:_,body:m,mode:g,credentials:y,cache:b,redirect:S,referrer:v,referrerPolicy:w,signal:this._abortController?.signal};let T=!1;clearTimeout(this._timeoutTimer),e=ii(e,p);const E=ti(l);E&&(_=u?u.headers:A.headers=A.headers||(Headers?new Headers:{}),Headers&&_ instanceof Headers?_.append("Range",E):_.Range=E),s&&(this._timeoutTimer=setTimeout((()=>{if(T=!0,this.cancel(),o){const t=new ai(e,A,null,"timeout");t.isTimeout=!0,o(t,{index:this._index,range:this._range,vid:this._vid,priOptions:this._priOptions})}}),s));const B=Date.now();return(Wt(n)||Wt(l))&&this.player.debug.log(this.TAG_NAME,"[fetch load start], index,",n,",range,",l),new Promise(((t,i)=>{fetch(u||e,u?void 0:A).then((async s=>{if(clearTimeout(this._timeoutTimer),this._response=s,this._aborted||!this._running)return;if(d&&(s=d(s,e)||s),!s.ok)throw new ai(e,A,s,"bad network response");const o=Date.now();let h;if(r===Ke)h=await s.text(),this._running=!1;else if(r===Xe)h=await s.json(),this._running=!1;else{if(a)return this.resolve=t,this.reject=i,void this._loadChunk(s,a,B,o);{h=await s.arrayBuffer(),h=new Uint8Array(h),this._running=!1;const t=Date.now()-B,e=ri(h.byteLength,t);this.emit(Je,{speed:e,len:h.byteLength,time:t,vid:this._vid,index:this._index,range:this._range,priOptions:this._priOptions})}}(Wt(n)||Wt(l))&&this.player.debug.log(this.TAG_NAME,"[fetch load end], index,",n,",range,",l),t(si(h,!0,s,s.headers.get("Content-Length"),s.headers.get("age"),B,o,n,l,this._vid,this._priOptions))})).catch((t=>{clearTimeout(this._timeoutTimer),this._running=!1,this._aborted&&!T||((t=t instanceof ai?t:new ai(e,A,null,t?.message)).startTime=B,t.endTime=Date.now(),t.isTimeout=T,t.options={index:this._index,range:this._range,vid:this._vid,priOptions:this._priOptions},i(t))}))}))}async cancel(){if(!this._aborted){if(this._aborted=!0,this._running=!1,this._response){try{this._reader&&await this._reader.cancel()}catch(t){}this._response=this._reader=null}if(this._abortController){try{this._abortController.abort()}catch(t){}this._abortController=null}this._onCancel&&this._onCancel({index:this._index,range:this._range,vid:this._vid,priOptions:this._priOptions})}}_loadChunk(t,e,i,s){if(!t.body||!t.body.getReader){this._running=!1;const e=new ai(t.url,"",t,"onProgress of bad response.body.getReader");return e.options={index:this._index,range:this._range,vid:this._vid,priOptions:this._priOptions},void this.reject(e)}this._onProcessMinLen>0&&(this._cache=new Uint8Array(Ye),this._writeIdx=0);const r=this._reader=t.body.getReader();let a,n,o;const h=async()=>{n=Date.now();try{a=await r.read(),o=Date.now()}catch(t){return o=Date.now(),void(this._aborted||(this._running=!1,t.options={index:this._index,range:this._range,vid:this._vid,priOptions:this._priOptions},this.reject(t)))}const l=this._range?.length>0?this._range[0]:0,d=l+this._receivedLength;if(this._aborted)return this._running=!1,void e(void 0,!1,{range:[d,d],vid:this._vid,index:this._index,startTime:n,endTime:o,st:i,firstByteTime:s,priOptions:this._priOptions},t);const u=a.value?a.value.byteLength:0;let p;if(this._receivedLength+=u,this.player.debug.log(this.TAG_NAME,"【fetchLoader,onProgress call】,task,",this._range,", start,",d,", end,",l+this._receivedLength,", done,",a.done),this._onProcessMinLen>0){if(this._writeIdx+u>=this._onProcessMinLen||a.done)p=new Uint8Array(this._writeIdx+u),p.set(this._cache.slice(0,this._writeIdx),0),u>0&&p.set(a.value,this._writeIdx),this._writeIdx=0,this.player.debug.log(this.TAG_NAME,"【fetchLoader,onProgress enough】,done,",a.done,",len,",p.byteLength,", writeIdx,",this._writeIdx);else if(u>0&&this._writeIdx+u<Ye)this._cache.set(a.value,this._writeIdx),this._writeIdx+=u,this.player.debug.log(this.TAG_NAME,"【fetchLoader,onProgress cache】,len,",u,", writeIdx,",this._writeIdx);else if(u>0){const t=new Uint8Array(this._writeIdx+u+2048);this.player.debug.log(this.TAG_NAME,"【fetchLoader,onProgress extra start】,size,",this._writeIdx+u+2048,", datalen,",u,", writeIdx,",this._writeIdx),t.set(this._cache.slice(0,this._writeIdx),0),u>0&&t.set(a.value,this._writeIdx),this._writeIdx+=u,delete this._cache,this._cache=t,this.player.debug.log(this.TAG_NAME,"【fetchLoader,onProgress extra end】,len,",u,", writeIdx,",this._writeIdx)}}else p=a.value;if((p&&p.byteLength>0||a.done)&&e(p,a.done,{range:[this._range[0]+this._receivedLength-(p?p.byteLength:0),this._range[0]+this._receivedLength],vid:this._vid,index:this._index,startTime:n,endTime:o,st:i,firstByteTime:s,priOptions:this._priOptions},t),a.done){const e=Date.now()-i,r=ri(this._receivedLength,e);this.emit(Je,{speed:r,len:this._receivedLength,time:e,vid:this._vid,index:this._index,range:this._range,priOptions:this._priOptions}),this._running=!1,this.player.debug.log(this.TAG_NAME,"[fetchLoader onProgress end],task,",this._range,",done,",a.done),this.resolve(si(a,!0,t,t.headers.get("Content-Length"),t.headers.get("age"),i,s,this._index,this._range,this._vid,this._priOptions))}else h()};h()}get receiveLen(){return this._receivedLength}get running(){return this._running}set running(t){this._running=t}static isSupported(){return!("undefined"==typeof fetch)}}class oi{TAG_NAME="Task";constructor(t,e,i){this.promise=function(){let t,e;const i=new Promise(((i,s)=>{t=i,e=s}));return i.used=!1,i.resolve=function(){return i.used=!0,t(...arguments)},i.reject=function(){return i.used=!0,e(...arguments)},i}(),this.alive=!!e.onProgress,this._loaderType=t,this.player=i,this._loader=t===$e&&window.fetch?new ni(i):new hi(i),this._config=e,this._retryCount=0,this._retryTimer=null,this._canceled=!1,this._retryCheckFunc=e.retryCheckFunc}exec(){const{retry:t,retryDelay:e,onRetryError:i,transformError:s,...r}=this._config,a=async()=>{try{const t=await this._loader.load(r);this.promise.resolve(t)}catch(n){if(this._loader.running=!1,this.player.debug.log(this.TAG_NAME,"[task request catch err]",n),this._canceled)return;n.loaderType=this._loaderType,n.retryCount=this._retryCount;let o=n;s&&(o=s(o)||o),i&&this._retryCount>0&&i(o,this._retryCount,{index:r.index,vid:r.vid,range:r.range,priOptions:r.priOptions}),this._retryCount++;let h=!0;if(this._retryCheckFunc&&(h=this._retryCheckFunc(n)),h&&this._retryCount<=t)return clearTimeout(this._retryTimer),this.player.debug.log(this.TAG_NAME,"[task request setTimeout],retry",this._retryCount,",retry range,",r.range),void(this._retryTimer=setTimeout(a,e));this.promise.reject(o)}};return a(),this.promise}async cancel(){return clearTimeout(this._retryTimer),this._canceled=!0,this._loader.running=!1,this._loader.cancel()}get running(){return this._loader&&this._loader.running}get loader(){return this._loader}}class hi extends t{_xhr=null;_aborted=!1;_timeoutTimer=null;_range=null;_receivedLength=0;_url=null;_onProgress=null;_index=-1;_headers=null;_currentChunkSizeKB=384;_timeout=null;_xhr=null;_withCredentials=null;_startTime=-1;_loadCompleteResolve=null;_loadCompleteReject=null;_runing=!1;_logger=!1;_vid="";_responseType;_credentials;_method;_transformResponse;_firstRtt;_onCancel=null;_priOptions=null;TAG_NAME="XhrLoader";constructor(t){super(),this.player=t}load(t){clearTimeout(this._timeoutTimer),this._range=t.range,this._onProgress=t.onProgress,this._index=t.index,this._headers=t.headers,this._withCredentials="include"===t.credentials||"same-origin"===t.credentials,this._body=t.body||null,t.method&&(this._method=t.method),this._timeout=t.timeout||null,this._runing=!0,this._vid=t.vid||t.url,this._responseType=t.responseType,this._firstRtt=-1,this._onTimeout=t.onTimeout,this._onCancel=t.onCancel,this._request=t.request,this._priOptions=t.priOptions||{},this.player.debug.log(this.TAG_NAME,"【xhrLoader task】, range",this._range),this._url=ii(t.url,t.params);const e=Date.now();return new Promise(((t,e)=>{this._loadCompleteResolve=t,this._loadCompleteReject=e,this._startLoad()})).catch((t=>{if(clearTimeout(this._timeoutTimer),this._runing=!1,!this._aborted)throw(t=t instanceof ai?t:new ai(this._url,this._request)).startTime=e,t.endTime=Date.now(),t.options={index:this._index,vid:this._vid,priOptions:this._priOptions},t}))}_startLoad(){let t=null;if(this._responseType===qe&&this._range&&this._range.length>1)if(this._onProgress){this._firstRtt=-1;const e=1024*this._currentChunkSizeKB,i=this._range[0]+this._receivedLength;let s=this._range[1];e<this._range[1]-i&&(s=i+e),t=[i,s],this.player.debug.log(this.TAG_NAME,"[xhr_loader->],tast :",this._range,", SubRange, ",t)}else t=this._range,this.player.debug.log(this.TAG_NAME,"[xhr_loader->],tast :",this._range,", allRange, ",t);this._internalOpen(t)}_internalOpen(t){try{this._startTime=Date.now();const e=this._xhr=new XMLHttpRequest;e.open(this._method||"GET",this._url,!0),e.responseType=this._responseType,this._timeout&&(e.timeout=this._timeout),e.withCredentials=this._withCredentials,e.onload=this._onLoad.bind(this),e.onreadystatechange=this._onReadyStatechange.bind(this),e.onerror=t=>{this._running=!1;const e=new ai(this._url,this._request,t?.currentTarget?.response,"xhr.onerror.status:"+t?.currentTarget?.status+",statusText,"+t?.currentTarget?.statusText);e.options={index:this._index,range:this._range,vid:this._vid,priOptions:this._priOptions},this._loadCompleteReject(e)},e.ontimeout=t=>{this.cancel();const e=new ai(this._url,this._request,{status:408},"timeout");this._onTimeout&&(e.isTimeout=!0,this._onTimeout(e,{index:this._index,range:this._range,vid:this._vid,priOptions:this._priOptions})),e.options={index:this._index,range:this._range,vid:this._vid,priOptions:this._priOptions},this._loadCompleteReject(e)};const i=this._headers||{},s=ti(t);s&&(i.Range=s),i&&Object.keys(i).forEach((t=>{e.setRequestHeader(t,i[t])})),this.player.debug.log(this.TAG_NAME,"[xhr.send->] tast,",this._range,",load sub range, ",t),e.send(this._body)}catch(e){e.options={index:this._index,range:t,vid:this._vid,priOptions:this._priOptions},this._loadCompleteReject(e)}}_onReadyStatechange(t){2===t.target.readyState&&this._firstRtt<0&&(this._firstRtt=Date.now())}_onLoad(t){const e=t.target.status;if(e<200||e>299){const i=new ai(this._url,null,{...t.target.response,status:e},"bad response,status:"+e);return i.options={index:this._index,range:this._range,vid:this._vid,priOptions:this._priOptions},this._loadCompleteReject(i)}let i,s=null,r=!1;const a=this._range?.length>0?this._range[0]:0;if(this._responseType===qe){const e=new Uint8Array(t.target.response);if(i=a+this._receivedLength,e&&e.byteLength>0){this._receivedLength+=e.byteLength;const t=Date.now()-this._startTime,s=ri(this._receivedLength,t);this.emit(Je,{speed:s,len:this._receivedLength,time:t,vid:this._vid,index:this._index,range:[i,a+this._receivedLength],priOptions:this._priOptions})}s=e,r=!(this._range?.length>1&&this._range[1]&&this._receivedLength<this._range[1]-this._range[0]),this.player.debug.log(this.TAG_NAME,"[xhr load done->], tast :",this._range,", start",i,"end ",a+this._receivedLength,",dataLen,",e?e.byteLength:0,",receivedLength",this._receivedLength,",index,",this._index,", done,",r)}else r=!0,s=t.target.response;let n={ok:e>=200&&e<300,status:e,statusText:this._xhr.statusText,url:this._xhr.responseURL,headers:this._getHeaders(this._xhr),body:this._xhr.response};this._transformResponse&&(n=this._transformResponse(n,this._url)||n),this._onProgress&&this._onProgress(s,r,{index:this._index,vid:this._vid,range:[i,a+this._receivedLength],startTime:this._startTime,endTime:Date.now(),priOptions:this._priOptions},n),r?(this._runing=!1,this._loadCompleteResolve&&this._loadCompleteResolve(si(this._onProgress?null:s,r,n,n.headers["content-length"],n.headers.age,this._startTime,this._firstRtt,this._index,this._range,this._vid,this._priOptions))):this._startLoad()}cancel(){if(!this._aborted)return this._aborted=!0,this._runing=!1,super.removeAllListeners(),this._onCancel&&this._onCancel({index:this._index,range:this._range,vid:this._vid,priOptions:this._priOptions}),this._xhr?this._xhr.abort():void 0}static isSupported(){return"undefined"!=typeof XMLHttpRequest}get receiveLen(){return this._receivedLength}get running(){return this._running}set running(t){this._running=t}_getHeaders(t){const e=t.getAllResponseHeaders().trim().split("\r\n"),i={};for(const t of e){const e=t.split(": ");i[e[0].toLowerCase()]=e.slice(1).join(": ")}return i}}class li extends t{type=$e;_queue=[];_alive=[];_currentTask=null;_config;constructor(t,e){super(),this.player=e,this._config=function(t){return{loaderType:$e,retry:0,retryDelay:0,timeout:0,request:null,onTimeout:void 0,onProgress:void 0,onRetryError:void 0,transformRequest:void 0,transformResponse:void 0,transformError:void 0,responseType:Ke,range:void 0,url:"",params:void 0,method:"GET",headers:{},body:void 0,mode:void 0,credentials:void 0,cache:void 0,redirect:void 0,referrer:void 0,referrerPolicy:void 0,integrity:void 0,onProcessMinLen:0,...t}}(t),this._config.loaderType!==je&&ni.isSupported()||(this.type=je)}destroy(){this._queue=[],this._alive=[],this._currentTask=null}isFetch(){return this.type===$e}static isFetchSupport(){return ni.isSupported()}load(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"string"!=typeof t&&t?e=t:e.url=t||e.url||this._config.url,e=Object.assign({},this._config,e),e.params&&(e.params=Object.assign({},e.params)),e.headers&&Qe(e.headers)&&(e.headers=Object.assign({},e.headers)),e.body&&Qe(e.body)&&(e.body=Object.assign({},e.body)),e.transformRequest&&(e=e.transformRequest(e)||e);const i=new oi(this.type,e,this.player);return i.loader.on(Je,(t=>{this.emit(Je,t)})),this._queue.push(i),1!==this._queue.length||this._currentTask&&this._currentTask.running||this._processTask(),i.promise}async cancel(){const t=this._queue.map((t=>t.cancel())).concat(this._alive.map((t=>t.cancel())));this._currentTask&&t.push(this._currentTask.cancel()),this._queue=[],this._alive=[],await Promise.all(t),await function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return new Promise((e=>setTimeout(e,t)))}()}_processTask(){if(this._currentTask=this._queue.shift(),!this._currentTask)return;this._currentTask.alive&&this._alive.push(this._currentTask);const t=this._currentTask.exec().catch((t=>{}));t&&"function"==typeof t.finally&&t.finally((()=>{this._currentTask?.alive&&this._alive?.length>0&&(this._alive=this._alive.filter((t=>t&&t!==this._currentTask))),this._processTask()}))}}const di="network",ui="network_timeout",pi="other",ci="manifest",fi="hls",_i="demux";class mi extends Error{constructor(t,e,i,s,r){super(r||i?.message),this.errorType=t===ui?di:t,this.originError=i,this.ext=s,this.errorMessage=this.message}static create(t,e,i,s,r){return t instanceof mi?t:(t instanceof Error&&(i=t,t=""),t||(t=pi),new mi(t,e,i,s,r))}static network(t){return new mi(t?.isTimeout?ui:di,null,t instanceof Error?t:null,{url:t?.url,response:t?.response,httpCode:t?.response?.status})}}const gi=/^#(EXT[^:]*)(?::(.*))?$/,yi=/([^=]+)=(?:"([^"]*)"|([^",]*))(?:,|$)/g,bi=/^(?:[a-zA-Z0-9+\-.]+:)?\/\//,Si=/^((?:[a-zA-Z0-9+\-.]+:)?\/\/[^/?#]*)?([^?#]*\/)?/;function vi(t){const e=t.match(gi);if(e&&e[1])return[e[1].replace("EXT-X-",""),e[2]]}function wi(t){const e={};let i=yi.exec(t);for(;i;)e[i[1]]=i[2]||i[3],i=yi.exec(t);return e}function xi(t,e){if(!e||!t||bi.test(t))return t;const i=Si.exec(e);return i?"/"===t[0]?i[1]+t:i[1]+i[2]+t:t}const Ui={audio:[/^mp4a/,/^vorbis$/,/^opus$/,/^flac$/,/^[ae]c-3$/],video:[/^avc/,/^hev/,/^hvc/,/^vp0?[89]/,/^av1$/],text:[/^vtt$/,/^wvtt/,/^stpp/]};function Ai(t,e){const i=Ui[t];if(i&&e&&e.length)for(let t=0;t<i.length;t++)for(let s=0;s<e.length;s++)if(i[t].test(e[s]))return e[s]}class Ti{constructor(){this.version=0,this.streams=[],this.isMaster=!0}}const Ei="AUDIO",Bi="SUBTITLE";class ki{id=0;url="";default=!1;autoSelect=!1;forced=!1;group="";name="";lang="";segments=[];endSN=0}class Li extends ki{mediaType=Ei;channels=0}class Ii extends ki{mediaType=Bi}class Ci{id=0;bitrate=0;width=0;height=0;name="";url="";audioCodec="";videoCodec="";textCodec="";audioGroup="";audioStreams=[];subtitleStreams=[];closedCaptionsStream=[]}class Di{version=0;url="";type="";startCC=0;endCC=0;startSN=0;endSN=0;totalDuration=0;targetDuration=0;live=!0;segments=[]}class Pi{sn=0;cc=0;url="";title="";start=0;duration=0;key=null;byteRange=null;isInitSegment=!1;initSegment=null;isLast=!1;hasAudio=!1;hasVideo=!1;get end(){return this.start+this.duration}setTrackExist(t,e){this.hasVideo=t,this.hasAudio=e}setByteRange(t,e){this.byteRange=[0];const i=t.split("@");1===i.length&&e&&e.byteRange?(this.byteRange[0]=e.byteRange[1]||0,this.byteRange[0]&&(this.byteRange[0]+=1)):this.byteRange[0]=parseInt(i[1]),this.byteRange[1]=this.byteRange[0]+parseInt(i[0])-1}}class Fi{method="";url="";iv=null;keyFormat="";keyFormatVersions="";constructor(t){t instanceof Fi&&(this.method=t.method,this.url=t.url,this.keyFormat=t.keyFormat,this.keyFormatVersions=t.keyFormatVersions,t.iv&&(this.iv=new Uint8Array(t.iv)))}clone(t){const e=new Fi(this);return null!=t&&e.setIVFromSN(t),e}setIVFromSN(t){if(!this.iv&&"AES-128"===this.method&&"number"==typeof t&&this.url){this.iv=new Uint8Array(16);for(let e=12;e<16;e++)this.iv[e]=t>>8*(15-e)&255}}}class Ri{static parse(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",e=arguments.length>1?arguments[1]:void 0;if(!t.includes("#EXTM3U"))throw new Error("Invalid m3u8 file");const i=function(t){return t.split(/[\r\n]/).map((t=>t.trim())).filter(Boolean)}(t);return Ri.isMediaPlaylist(t)?function(t,e){const i=new Di;i.url=e;let s,r=new Pi,a=null,n=null,o=0,h=0,l=0,d=0,u=!1;for(;(s=t[d++])&&!u;){if("#"!==s[0]){r.sn=h,r.cc=l,r.url=xi(s,e),n&&(r.key=n.clone(h)),a&&(r.initSegment=a),i.segments.push(r),r=new Pi,h++;continue}const t=vi(s);if(!t)continue;const[d,p]=t;switch(d){case"VERSION":i.version=parseInt(p);break;case"PLAYLIST-TYPE":i.type=p?.toUpperCase();break;case"TARGETDURATION":i.targetDuration=parseFloat(p);break;case"ENDLIST":{const t=i.segments[i.segments.length-1];t&&(t.isLast=!0),i.live=!1,u=!0}break;case"MEDIA-SEQUENCE":h=i.startSN=parseInt(p);break;case"DISCONTINUITY-SEQUENCE":l=i.startCC=parseInt(p);break;case"DISCONTINUITY":l++;break;case"BYTERANGE":r.setByteRange(p,i.segments[i.segments.length-1]);break;case"EXTINF":{const[t,e]=p.split(",");r.start=o,r.duration=parseFloat(t),o+=r.duration,r.title=e}break;case"KEY":{const t=wi(p);if("NONE"===t.METHOD){n=null;break}if("AES-128"!==t.METHOD)throw new Error(`encrypt ${t.METHOD}/${t.KEYFORMAT} is not supported`);if(n=new Fi,n.method=t.METHOD,n.url=/^blob:/.test(t.URI)?t.URI:xi(t.URI,e),n.keyFormat=t.KEYFORMAT||"identity",n.keyFormatVersions=t.KEYFORMATVERSIONS,t.IV){let e=t.IV.slice(2);e=(1&e.length?"0":"")+e,n.iv=new Uint8Array(e.length/2);for(let t=0,i=e.length/2;t<i;t++)n.iv[t]=parseInt(e.slice(2*t,2*t+2),16)}}break;case"MAP":{const t=wi(p);r.url=xi(t.URI,e),t.BYTERANGE&&r.setByteRange(t.BYTERANGE),r.isInitSegment=!0,r.sn=0,n&&(r.key=n.clone(0)),a=r,r=new Pi}}}const p=i.segments[i.segments.length-1];return p&&(i.endSN=p.sn),i.totalDuration=o,i.endCC=l,i}(i,e):function(t,e){const i=new Ti;let s,r=0;const a=[],n=[];for(;s=t[r++];){const o=vi(s);if(!o)continue;const[h,l]=o;if("VERSION"===h)i.version=parseInt(l);else if("MEDIA"===h&&l){const t=wi(l);let i;switch(t.TYPE){case"AUDIO":i=new Li;break;case"SUBTITLES":i=new Ii;break;default:i=new ki}i.url=xi(t.URI,e),i.default="YES"===t.DEFAULT,i.autoSelect="YES"===t.AUTOSELECT,i.group=t["GROUP-ID"],i.name=t.NAME,i.lang=t.LANGUAGE,t.CHANNELS&&(i.channels=Number(t.CHANNELS.split("/")[0]),Number.isNaN(i.channels)&&(i.channels=0)),"AUDIO"===t.TYPE&&t.URI&&a.push(i),"SUBTITLES"===t.TYPE&&n.push(i)}else if("STREAM-INF"===h&&l){const s=new Ci,a=wi(l);if(s.bitrate=parseInt(a["AVERAGE-BANDWIDTH"]||a.BANDWIDTH),s.name=a.NAME,s.url=xi(t[r++],e),a.RESOLUTION){const[t,e]=a.RESOLUTION.split("x");s.width=parseInt(t),s.height=parseInt(e)}if(a.CODECS){const t=a.CODECS.split(/[ ,]+/).filter(Boolean);s.videoCodec=Ai("video",t),s.audioCodec=Ai("audio",t),s.textCodec=Ai("text",t)}s.audioGroup=a.AUDIO,s.subtitleGroup=a.SUBTITLES,i.streams.push(s)}}return i.streams.forEach(((t,e)=>{t.id=e})),a.length&&(a.forEach(((t,e)=>{t.id=e})),i.streams.forEach((t=>{t.audioGroup&&(t.audioStreams=a.filter((e=>e.group===t.audioGroup)))}))),n.length&&(n.forEach(((t,e)=>{t.id=e})),i.streams.forEach((t=>{t.subtitleGroup&&(t.subtitleStreams=n.filter((e=>e.group===t.subtitleGroup)))}))),i}(i,e)}static isMediaPlaylist(t){return t.includes("#EXTINF:")||t.includes("#EXT-X-TARGETDURATION:")}}class Ni{constructor(t){this.hls=t,this.player=t.player,this.TAG_NAME="HlsManifestLoader",this._timer=null;const{retryCount:e,retryDelay:i,loadTimeout:s,fetchOptions:r}=this.hls.config;this._loader=new li({...r,responseType:"text",retry:e,retryDelay:i,timeout:s,onRetryError:this._onLoaderRetry},this.player),this._audioLoader=new li({...r,responseType:"text",retry:e,retryDelay:i,timeout:s,onRetryError:this._onLoaderRetry},this.player),this._subtitleLoader=new li({...r,responseType:"text",retry:e,retryDelay:i,timeout:s,onRetryError:this._onLoaderRetry},this.player)}async destroy(){await this.stopPoll(),this._audioLoader&&(this._audioLoader.destroy(),this._audioLoader=null),this._subtitleLoader&&(this._subtitleLoader.destroy(),this._subtitleLoader=null),this._loader&&(this._loader.destroy(),this._loader=null)}async load(t,e,i){this.player.debug.log(this.TAG_NAME,"load()",t,e,i);const s=[this._loader.load(t)];let r,a,n,o,h,l;e&&s.push(this._audioLoader.load(e)),i&&s.push(this._subtitleLoader.load(i));try{const[t,i,o]=await Promise.all(s);if(!t)return[];r=t.data,e?(a=i?.data,n=o?.data):n=i?.data}catch(t){throw mi.network(t)}try{if(o=Ri.parse(r,t),!1===o?.live&&o.segments&&!o.segments.length)throw new Error("empty segments list");a&&(h=Ri.parse(a,e)),n&&(l=Ri.parse(n,i))}catch(t){throw new mi(ci,fi,t)}return o&&(o.isMaster?this.hls.emit(nt,{playlist:o}):this.hls.emit(ot,{playlist:o})),[o,h,l]}poll(t,e,i,s,r,a){clearTimeout(this._timer),a=a||3e3;let n=this.hls.config.pollRetryCount;const o=async()=>{clearTimeout(this._timer);try{const r=await this.load(t,e,i);if(!r[0])return;n=this.hls.config.pollRetryCount,s(r[0],r[1],r[2])}catch(t){n--,n<=0&&r(t)}this._timer=setTimeout(o,a)};this._timer=setTimeout(o,a)}stopPoll(){return clearTimeout(this._timer),this.cancel()}cancel(){return Promise.all([this._loader.cancel(),this._audioLoader.cancel()])}_onLoaderRetry=(t,e)=>{this.hls.emit(pt,{error:mi.network(t),retryTime:e})}}class Mi{_chunkSpeeds=[];_speeds=[];addRecord(t,e){t&&e&&(this._speeds.push(8e3*t/e),this._speeds=this._speeds.slice(-3))}addChunkRecord(t,e){t&&e&&(this._chunkSpeeds.push(8e3*t/e),this._chunkSpeeds=this._chunkSpeeds.slice(-100))}getAvgSpeed(){return this._chunkSpeeds.length||this._speeds.length?this._speeds.length?this._speeds.reduce(((t,e)=>t+e))/this._speeds.length:this._chunkSpeeds.reduce(((t,e)=>t+e))/this._chunkSpeeds.length:0}getLatestSpeed(){return this._chunkSpeeds.length||this._speeds.length?this._speeds.length?this._speeds[this._speeds.length-1]:this._chunkSpeeds[this._chunkSpeeds.length-1]:0}reset(){this._chunkSpeeds=[],this._speeds=[]}}class zi{constructor(t){this.hls=t,this.player=t.player,this._bandwidthService=new Mi;const{retryCount:e,retryDelay:i,loadTimeout:s,fetchOptions:r}=this.hls.config;this._segmentLoader=new li({...r,responseType:"arraybuffer",retry:e,retryDelay:i,timeout:s,onRetryError:this._onLoaderRetry},this.player),this._audioSegmentLoader=new li({...r,responseType:"arraybuffer",retry:e,retryDelay:i,timeout:s,onRetryError:this._onLoaderRetry},this.player),this._keyLoader=new li({...r,responseType:"arraybuffer",retry:e,retryDelay:i,timeout:s,onRetryError:this._onLoaderRetry},this.player)}destroy(){this.reset(),this._keyLoader&&(this._keyLoader.destroy(),this._keyLoader=null),this._audioSegmentLoader&&(this._audioSegmentLoader.destroy(),this._audioSegmentLoader=null),this._segmentLoader&&(this._segmentLoader.destroy(),this._segmentLoader=null)}speedInfo(){return{speed:this._bandwidthService.getLatestSpeed(),avgSpeed:this._bandwidthService.getAvgSpeed()}}load(t,e,i){let s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:i;const r=[];return t&&(r[0]=this.loadVideoSegment(t,i)),e&&(r[1]=this.loadAudioSegment(e,s)),Promise.all(r)}loadVideoSegment(t,e){return this._loadSegment(this._segmentLoader,t,e)}loadAudioSegment(t,e){return this._loadSegment(this._audioSegmentLoader,t,e)}async _loadSegment(t,e,i){let s,r,a,n,o;const h=[];if(this.hls.emit(ct,{url:e.url}),h[0]=t.load(e.url),i&&e.initSegment){const i=e.initSegment.url;s=this._mapCache[i],s||(this.hls.emit(ct,{url:i}),h[1]=t.load(i).then((t=>{if(t){Object.keys(this._mapCache)>30&&(this._mapCache={}),s=this._mapCache[i]=t.data,this._emitOnLoaded(t,i)}})));const r=e.initSegment.key?.url;r&&(o=e.initSegment.key.iv,n=this._keyCache[r],n||(this.hls.emit(ct,{url:r}),h[2]=this._keyLoader.load(r).then((t=>{t&&(n=this._keyCache[r]=t.data,this._emitOnLoaded(t,r))}))))}const l=e.key?.url;l&&(a=e.key.iv,r=this._keyCache[l],r||(this.hls.emit(ct,{url:l}),h[3]=this._keyLoader.load(l).then((t=>{t&&(r=this._keyCache[l]=t.data,this._emitOnLoaded(t,l))}))));const[d]=await Promise.all(h);if(!d)return;const u=d.data;return this._emitOnLoaded(d,e.url),{data:u,map:s,key:r,mapKey:n,keyIv:a,mapKeyIv:o}}reset(){this.error=null,this._mapCache={},this._keyCache={},this._bandwidthService.reset()}async cancel(){await Promise.all([this._keyLoader.cancel(),this._segmentLoader.cancel(),this._audioSegmentLoader.cancel()])}_emitOnLoaded=(t,e)=>{const{data:i,response:s,option:r}=t,{firstByteTime:a,startTime:n,endTime:o,contentLength:h}=r||{},l=o-n;this._bandwidthService.addRecord(h||i.byteLength,l),this.hls.emit(ft,{time:l,byteLength:h,url:e}),this.hls.emit(_t,{url:e,elapsed:l||0}),this.hls.emit(ut,{url:e,responseUrl:s.url,elapsed:a-n}),this.hls.emit(mt,{headers:s.headers})};_onLoaderRetry=(t,e)=>{this.hls.emit(pt,{error:mi.network(t),retryTime:e})}}class Gi{constructor(t,e,i){this.live=void 0,this.id=0,this.bitrate=0,this.width=0,this.height=0,this.name="",this.url="",this.audioCodec="",this.videoCodec="",this.textCodec="",this.startCC=0,this.endCC=0,this.startSN=0,this.endSN=-1,this.totalDuration=0,this.targetDuration=0,this.snDiff=null,this.segments=[],this.audioStreams=[],this.subtitleStreams=[],this.closedCaptions=[],this.currentAudioStream=null,this.currentSubtitleStream=null,this.TAG_NAME="HlsStream",this.update(t,e,i)}get lastSegment(){return this.segments.length?this.segments[this.segments.length-1]:null}get segmentDuration(){return this.targetDuration||this.segments[0]?.duration||0}get liveEdge(){return this.endTime}get endTime(){return this.lastSegment?.end||0}get currentSubtitleEndSn(){return this.currentSubtitleStream?.endSN||0}clearOldSegment(t,e){return this._clearSegments(t,e)}getAudioSegment(t){if(!t||!this.currentAudioStream)return;const e=t.sn-this.snDiff;return this.currentAudioStream.segments.find((t=>t.sn===e))}update(t,e){this.url=t.url,Array.isArray(t.segments)?(null!==this.live&&void 0!==this.live||(this.live=t.live),this._updateSegments(t,this),this.startCC=t.startCC,this.endCC=t.endCC,this.startSN=t.startSN,this.endSN=t.endSN||-1,this.totalDuration=t.totalDuration,this.targetDuration=t.targetDuration,this.live=t.live,e&&this.currentAudioStream&&Array.isArray(e.segments)&&(this._updateSegments(e,this.currentAudioStream),(null===this.snDiff||void 0===this.snDiff)&&t.segments.length&&e.segments.length&&(this.snDiff=t.segments[0].sn-e.segments[0].sn))):(this.id=t.id,this.bitrate=t.bitrate,this.width=t.width,this.height=t.height,this.name=t.name,this.audioCodec=t.audioCodec,this.videoCodec=t.videoCodec,this.textCodec=t.textCodec,this.audioStreams=t.audioStreams,this.subtitleStreams=t.subtitleStreams,!this.currentAudioStream&&this.audioStreams.length&&(this.currentAudioStream=this.audioStreams.find((t=>t.default))||this.audioStreams[0]),!this.currentSubtitleStream&&this.subtitleStreams.length&&(this.currentSubtitleStream=this.subtitleStreams.find((t=>t.default))||this.subtitleStreams[0]))}updateSubtitle(t){if(!(t&&this.currentSubtitleStream&&Array.isArray(t.segments)))return;const e=this._updateSegments(t,this.currentSubtitleStream),i=this.currentSubtitleStream.segments;return i.length>100&&(this.currentSubtitleStream.segments=i.slice(100)),e?e.map((t=>({sn:t.sn,url:t.url,duration:t.duration,start:t.start,end:t.end,lang:this.currentSubtitleStream.lang}))):void 0}switchSubtitle(t){const e=this.subtitleStreams.find((e=>e.lang===t)),i=this.currentSubtitleStream;e&&(this.currentSubtitleStream=e,i.segments=[])}_clearSegments(t,e){let i=0;const s=this.segments;for(let e=0,r=s.length;e<r;e++)if(s[e].end>=t){i=e;break}return i>e&&(i=e),i&&(this.segments=this.segments.slice(i),this.currentAudioStream&&(this.currentAudioStream.segments=this.currentAudioStream.segments.slice(i))),e-i}_updateSegments(t,e){const i=e.segments;if(this.live){const s=i[i.length-1],r=s?.sn||-1;if(r<t.endSN&&t.segments.length){const a=t.segments.findIndex((t=>t.sn===r)),n=a<0?t.segments:t.segments.slice(a+1);if(i.length&&n.length){let t=s.end;n.forEach((e=>{e.start=t,t=e.end}));const e=s?.cc||-1;e>n[0].cc&&n.forEach((t=>t.cc+=e))}return e.endSN=t.endSN,e.segments=i.concat(n),n}}else e.segments=t.segments}}class Oi{constructor(t){this.hls=t,this.player=t.player,this.streams=[],this.currentStream=null,this.dvrWindow=0,this._segmentPointer=-1,this.TAG_NAME="HlsPlaylist"}destroy(){this.reset()}get lastSegment(){return this.currentStream?.lastSegment}get currentSegment(){return this.currentSegments?.[this._segmentPointer]}get nextSegment(){return this.currentSegments?.[this._segmentPointer+1]}get currentSegments(){return this.currentStream?.segments}get currentSubtitleEndSn(){return this.currentStream?.currentSubtitleEndSn}get liveEdge(){return this.currentStream?.liveEdge}get totalDuration(){return this.currentStream?.totalDuration||0}get seekRange(){const t=this.currentSegments;if(t&&t.length)return[t[0].start,t[t.length-1].end]}get isEmpty(){return!this.currentSegments?.length}get isLive(){return this.currentStream?.live}get hasSubtitle(){return!!this.currentStream?.currentSubtitleStream}getAudioSegment(t){return this.currentStream?.getAudioSegment(t)}moveSegmentPointer(t){var e,i,s;null==t&&(t=this._segmentPointer+1),this._segmentPointer=(e=t,i=-1,s=this.currentSegments?.length,Math.max(Math.min(e,Math.max(i,s)),Math.min(i,s))),this.player.debug.log(this.TAG_NAME,"moveSegmentPointer()",t,this._segmentPointer)}reset(){this.streams=[],this.currentStream=null,this.dvrWindow=0,this._segmentPointer=-1}getSegmentByIndex(t){return this.currentSegments?.[t]}setNextSegmentByIndex(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this._segmentPointer=t-1,this.player.debug.log(this.TAG_NAME,"setNextSegmentByIndex()",t,this._segmentPointer)}findSegmentIndexByTime(t){const e=this.currentSegments;if(e){for(let i,s=0,r=e.length;s<r;s++)if(i=e[s],t>=i.start&&t<i.end)return s;const i=e[e.length-1];if(Math.abs(t-i.end)<.2)return e.length-1}}upsertPlaylist(t,e,i){if(!t)return void this.player.debug.warn(this.TAG_NAME,"upsertPlaylist() playlist is null");if(t.isMaster)this.streams.length=t.streams.length,t.streams.filter((t=>t.url)).forEach(((t,e)=>{this.streams[e]?this.streams[e].update(t):this.streams[e]=new Gi(t)})),this.currentStream=this.streams[0];else if(Array.isArray(t.segments)){const s=this.currentStream;if(s){s.update(t,e,i);const r=s.updateSubtitle(i);r&&this.hls.emit(at,{list:r})}else this.reset(),this.currentStream=this.streams[0]=new Gi(t,e,i)}this.currentStream&&this.hls.isLive&&!this.dvrWindow&&(this.dvrWindow=this.currentSegments.reduce(((t,e)=>t+=e.duration),0))}switchSubtitle(t){this.currentStream?.switchSubtitle(t)}clearOldSegment(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:50;const e=this.currentStream;if(!this.dvrWindow||!e)return;const i=e.endTime-this.dvrWindow;if(i<=0)return void this.player.debug.log(this.TAG_NAME,`clearOldSegment() stream.endTime:${e.endTime}, this.dvrWindow:${this.dvrWindow} startTime <= 0`);const s=e.segments;if(s.length<=t)return void this.player.debug.log(this.TAG_NAME,`clearOldSegment() segments.length:${s.length} <= maxPlaylistSize:${t}`);const r=this._segmentPointer;this._segmentPointer=e.clearOldSegment(i,r),this.player.debug.log(this.TAG_NAME,"clearOldSegment() update _segmentPointer:",r,this._segmentPointer),this.player.debug.log(this.TAG_NAME,"currentSegments",this.currentSegments)}checkSegmentTrackChange(t,e){const i=this.findSegmentIndexByTime(t),s=this.getSegmentByIndex(i);if(!s)return;if(!s.hasAudio&&!s.hasVideo)return;if(2!==e&&s.hasAudio&&s.hasVideo)return s;if(s.end-t>.3)return;const r=this.getSegmentByIndex(i+1);return r&&(r.hasAudio||r.hasVideo)&&(r.hasAudio!==s.hasAudio||r.hasVideo!==s.hasVideo)?r:void 0}}function Hi(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];if((e=e.filter(Boolean)).length<2)return e[0];const s=new Uint8Array(e.reduce(((t,e)=>t+e.byteLength),0));let r=0;return e.forEach((t=>{s.set(t,r),r+=t.byteLength})),s}class Vi{constructor(){const t=window.crypto||window.msCrypto;this.subtle=t&&(t.subtle||t.webkitSubtle),this.externalDecryptor=null}decrypt(t,e){if(!t&&!e)return;const i=[];return t&&(i[0]=this._decryptSegment(t)),e&&(i[1]=this._decryptSegment(e)),Promise.all(i)}async _decryptSegment(t){let e=t.data;return t.key&&(e=await this._decryptData(t.data,t.key,t.keyIv)),t.map?Hi(t.map,e):e}async _decryptData(t,e,i){if(this.externalDecryptor)return await this.externalDecryptor.decrypt(t,e,i);{if(!this.subtle)throw new Error("crypto is not defined");const s=await this.subtle.importKey("raw",e,{name:"AES-CBC"},!1,["encrypt","decrypt"]);return new Uint8Array(await this.subtle.decrypt({name:"AES-CBC",iv:i},s,t))}}}const Wi=9e4,Yi=45e4,$i=9e4;class ji extends Ie{constructor(t){super(t),this.player=t,this._pmtId=-1,this._remainingPacketData=null,this._videoPesData=[],this._audioPesData=[],this._gopId=0,this._videoPid=-1,this._audioPid=-1,this._codecType=M,this._audioCodecType=H.AAC,this._vps=null,this._sps=null,this._pps=null,this.TAG_NAME="TsLoader",this.videoTrack=ji.initVideoTrack(),this.audioTrack=ji.initAudioTrack(),this._baseDts=-1,this._baseDtsInited=!1,this._basefps=25,this._baseFpsInterval=null,this._tempSampleTsList=[],this._hasAudio=!1,this._hasVideo=!1,this._audioNextPts=void 0,this._videoNextDts=void 0,this._audioTimestampBreak=!1,this._videoTimestampBreak=!1,this._lastAudioExceptionGapDot=0,this._lastAudioExceptionOverlapDot=0,this._lastAudioExceptionLargeGapDot=0,this._isSendAACSeqHeader=!1,this.workerClearTimeout=null,this.workerUrl=null,this.loopWorker=null,this.tempSampleListInfo={},this._initLoopWorker(),this.player.debug.log(this.TAG_NAME,"init")}destroy(){super.destroy(),this.workerUrl&&(URL.revokeObjectURL(this.workerUrl),this.workerUrl=null),this.workerClearTimeout&&(clearTimeout(this.workerClearTimeout),this.workerClearTimeout=null),this.loopWorker&&(this.loopWorker.postMessage({cmd:"destroy"}),this.loopWorker.terminate(),this.loopWorker=null),this._stopDecodeLoopInterval(),this.videoTrack=null,this.audioTrack=null,this.tempSampleListInfo={},this._baseDts=-1,this._baseDtsInited=!1,this._basefps=50,this._hasCalcFps=!1,this._audioNextPts=void 0,this._videoNextDts=void 0,this._audioTimestampBreak=!1,this._videoTimestampBreak=!1,this._lastAudioExceptionGapDot=0,this._lastAudioExceptionOverlapDot=0,this._lastAudioExceptionLargeGapDot=0,this._isSendAACSeqHeader=!1,this.player.debug.log(this.TAG_NAME,"destroy")}static initVideoTrack(){return{samples:[]}}static initAudioTrack(){return{samples:[]}}static probe(t){return!!t.length&&(71===t[0]&&71===t[188]&&71===t[376])}static _parsePES(t){const e=t[8];if(null==e||t.length<e+9)return;if(1!==(t[0]<<16|t[1]<<8|t[2]))return;const i=(t[4]<<8)+t[5];if(i&&i>t.length-6)return;let s,r;const a=t[7];return 192&a&&(s=536870912*(14&t[9])+4194304*(255&t[10])+16384*(254&t[11])+128*(255&t[12])+(254&t[13])/2,64&a?(r=536870912*(14&t[14])+4194304*(255&t[15])+16384*(254&t[16])+128*(255&t[17])+(254&t[18])/2,s-r>54e5&&(s=r)):r=s),{data:t.subarray(9+e),pts:s,dts:r,originalPts:s,originalDts:r}}_demux(t){let e=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];e&&(this._pmtId=-1,this.videoTrack=ji.initVideoTrack(),this.audioTrack=ji.initAudioTrack()),!i||e?(this._remainingPacketData=null,this._videoPesData=[],this._audioPesData=[]):(this.videoTrack.samples=[],this.audioTrack.samples=[],this._remainingPacketData&&(t=Hi(this._remainingPacketData,t),this._remainingPacketData=null));let s=t.length;const r=s%188;r&&(this._remainingPacketData=t.subarray(s-r),s-=r);for(let e=0;e<s;e+=188){if(71!==t[e])throw new Error("TS packet did not start with 0x47");const i=!!(64&t[e+1]),s=((31&t[e+1])<<8)+t[e+2];let r;if((48&t[e+3])>>4>1){if(r=e+5+t[e+4],r===e+188)continue}else r=e+4;switch(s){case 0:i&&(r+=t[r]+1),this._pmtId=(31&t[r+10])<<8|t[r+11];break;case this._pmtId:{i&&(r+=t[r]+1);const e=r+3+((15&t[r+1])<<8|t[r+2])-4;for(r+=12+((15&t[r+10])<<8|t[r+11]);r<e;){const e=(31&t[r+1])<<8|t[r+2];switch(t[r]){case 15:this._audioPid=e,this._audioCodecType=H.AAC;break;case 27:this._videoPid=e,this._codecType=M;break;case 36:this._videoPid=e,this._codecType=z;break;default:console.warn(`Unsupported stream. type: ${t[r]}, pid: ${e}`)}r+=5+((15&t[r+3])<<8|t[r+4])}}break;case this._videoPid:i&&this._videoPesData.length&&this._parseVideoData(),this._videoPesData.push(t.subarray(r,e+188));break;case this._audioPid:i&&this._audioPesData.length&&this._parseAudioData(),this._audioPesData.push(t.subarray(r,e+188));break;case 17:case 8191:break;default:console.warn(`Unknown pid: ${s}`)}}this._parseVideoData(),this._parseAudioData(),this.audioTrack.formatTimescale=this.videoTrack.formatTimescale=this.videoTrack.timescale=9e4,this.audioTrack.timescale=this.audioTrack.sampleRate||0}demuxAndFix(t,e,i,s){this._demux(t,e,i,s),this._fix(s,e,i)}_parseVideoData(){if(!this._videoPesData.length)return void console.log("_parseVideoData","no video pes data");const t=ji._parsePES(Hi(...this._videoPesData));if(!t)return void console.warn("Cannot parse video pes",this._videoPesData);this.player._updateStats({vbps:t.data.byteLength});const e=function(t){const e=t.length;let i=2,s=0;for(;null!==t[i]&&void 0!==t[i]&&1!==t[i];)i++;if(i++,s=i+2,s>=e)return[];const r=[];for(;s<e;)switch(t[s]){case 0:if(0!==t[s-1]){s+=2;break}if(0!==t[s-2]){s++;break}i!==s-2&&r.push(t.subarray(i,s-2));do{s++}while(1!==t[s]&&s<e);i=s+1,s=i+2;break;case 1:if(0!==t[s-1]||0!==t[s-2]){s+=3;break}i!==s-2&&r.push(t.subarray(i,s-2)),i=s+1,s=i+2;break;default:s+=3}return i<e&&r.push(t.subarray(i)),r}(t.data);e?this._createVideoSample(e,t.pts,t.dts):this.player.debug.warn(this.TAG_NAME,"Cannot parse avc units",t),this._videoPesData=[]}_createVideoSample(t,e,i){if(!t.length)return;const s=this._codecType===z,r={isIFrame:!1,type:b,isHevc:s,vps:null,sps:null,pps:null,pts:e,dts:i,payload:null};t.forEach((t=>{const e=s?t[0]>>>1&63:31&t[0];switch(e){case 5:case 16:case 17:case 18:case 19:case 20:case 21:case 22:case 23:if(!s&&5!==e||s&&5===e)break;r.isIFrame=!0,this._gopId++;break;case 6:case 39:case 40:if(!s&&6!==e||s&&6===e)break;return void function(t,e){const i=t.length;let s=e?2:1,r=0,a=0,n="";for(;255===t[s];)r+=255,s++;for(r+=t[s++];255===t[s];)a+=255,s++;if(a+=t[s++],5===r&&i>s+16)for(let e=0;e<16;e++)n+=t[s].toString(16),s++;t.subarray(s)}(function(t){const e=t.byteLength,i=[];let s=1;for(;s<e-2;)0===t[s]&&0===t[s+1]&&3===t[s+2]?(i.push(s+2),s+=2):s++;if(!i.length)return t;const r=e-i.length,a=new Uint8Array(r);let n=0;for(s=0;s<r;n++,s++)n===i[0]&&(n++,i.shift()),a[s]=t[n];return a}(t),s);case 32:if(!s)break;r.vps||(r.vps=t);break;case 7:case 33:if(!s&&7!==e||s&&7===e)break;r.sps||(r.sps=t);break;case 8:case 34:if(!s&&8!==e||s&&8===e)break;r.pps||(r.pps=t)}if(s&&xe(e)||!s&&fe(e)){const e=ye(t);if(r.payload){const t=new Uint8Array(r.payload.byteLength+e.byteLength);t.set(r.payload,0),t.set(e,r.payload.byteLength),r.payload=t}else r.payload=e}}));let a=null;s?r.sps&&r.vps&&r.pps&&(a=Se({vps:r.vps,sps:r.sps,pps:r.pps})):r.sps&&r.pps&&(a=de({sps:r.sps,pps:r.pps})),a&&(this.player.debug.log(this.TAG_NAME,"_createVideoSample","seqHeader"),this._doDecodeByHls(a,b,r.pts,!0,0)),r.isIFrame&&this.calcIframeIntervalTimestamp(r.dts/90),this.videoTrack.samples=this.videoTrack.samples.concat(r)}_parseAudioData(){if(!this._audioPesData.length)return;const t=ji._parsePES(Hi(...this._audioPesData));if(t){if(this.player._opt.hasAudio){if(this.player._updateStats({abps:t.data.byteLength}),this._audioCodecType===H.AAC){const e=function(t,e){const i=t.length;let s=0;for(;s+2<i&&(255!==t[s]||240!=(246&t[s+1]));)s++;if(s>=i)return;const r=s,a=[],n=(60&t[s+2])>>>2,o=Et[n];if(!o)throw new Error(`Invalid sampling index: ${n}`);const h=1+((192&t[s+2])>>>6),l=(1&t[s+2])<<2|(192&t[s+3])>>>6;let d,u,p=0;const c=Lt(o);for(;s+7<i;)if(255===t[s]&&240==(246&t[s+1])){if(u=(3&t[s+3])<<11|t[s+4]<<3|(224&t[s+5])>>5,i-s<u)break;d=2*(1&~t[s+1]),a.push({pts:e+p*c,data:t.subarray(s+7+d,s+u)}),p++,s+=u}else s++;return{skip:r,remaining:s>=i?void 0:t.subarray(s),frames:a,samplingFrequencyIndex:n,sampleRate:o,objectType:h,channelCount:l,originCodec:`mp4a.40.${h}`}}(t.data,t.originalPts);if(e){if(this.audioTrack.codec=e.codec,this.audioTrack.sampleRate=e.sampleRate,this.audioTrack.channelCount=e.channelCount,!this._isSendAACSeqHeader){const t=At({profile:e.objectType,sampleRate:e.samplingFrequencyIndex,channel:e.channelCount});this._isSendAACSeqHeader=!0,this.player.debug.log(this.TAG_NAME,"aac seq header",`profile: ${e.objectType}, sampleRate:${e.sampleRate},sampleRateIndex: ${e.samplingFrequencyIndex}, channel: ${e.channelCount}`),this._doDecodeByHls(t,y,0,!1,0)}if(this._isSendAACSeqHeader){const t=[];e.frames.forEach((e=>{const i=e.pts,s=new Uint8Array(e.data.length+2);s.set([175,1],0),s.set(e.data,2);const r={type:y,pts:i,dts:i,payload:s};t.push(r)})),this.audioTrack.samples=this.audioTrack.samples.concat(t)}else this.player.debug.warn(this.TAG_NAME,"aac seq header not send")}else this.player.debug.warn(this.TAG_NAME,"aac parseADTS error")}this._audioPesData=[]}}else console.warn("Cannot parse audio pes",this._audioPesData)}_fix(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];t=Math.round(9e4*t);const s=this.videoTrack,r=this.audioTrack,a=s.samples,n=r.samples;if(!a.length&&!n.length)return;const o=a[0],h=n[0];let l=0;if(a.length&&n.length&&(l=o.dts-h.pts),this._baseDtsInited||this._calculateBaseDts(),e&&(this._calculateBaseDts(),this._baseDts-=t),!i){this._videoNextDts=l>0?t+l:t,this._audioNextPts=l>0?t:t-l;const e=o?o.dts-this._baseDts-this._videoNextDts:0,i=h?h.pts-this._baseDts-this._audioNextPts:0;Math.abs(e||i)>$i&&(this._calculateBaseDts(this.audioTrack,this.videoTrack),this._baseDts-=t)}this._resetBaseDtsWhenStreamBreaked(),this._fixAudio(r),this._fixVideo(s);let d=s.samples.concat(r.samples);d=d.map((t=>(t.dts=t.dts/90,t.pts=t.pts/90,t.cts=t.pts-t.dts,t))).sort(((t,e)=>t.dts-e.dts)),d.forEach((t=>{const e=new Uint8Array(t.payload);delete t.payload,this.loopWorker.postMessage({...t,payload:e,cmd:"sample"},[e.buffer])})),Kt(this._hasCalcFps)&&(this._hasCalcFps=!0,this._calcDecodeFps(d))}_calculateBaseDts(){const t=this.audioTrack,e=this.videoTrack,i=t.samples,s=e.samples;if(!i.length&&!s.length)return!1;let r=1/0,a=1/0;i.length&&(t.baseDts=r=i[0].pts),s.length&&(e.baseDts=a=s[0].dts),this._baseDts=Math.min(r,a);const n=a-r;return Number.isFinite(n)&&Math.abs(n)>45e3&&this.player.debug.warn(this.TAG_NAME,`large av first frame gap,\n video pts: ${a},\n audio pts: ${r},\n base dts: ${this._baseDts},\n detect is: ${n}`),this._baseDtsInited=!0,!0}_resetBaseDtsWhenStreamBreaked(){if(this._baseDtsInited&&this._videoTimestampBreak&&this._audioTimestampBreak){if(!this._calculateBaseDts(this.audioTrack,this.videoTrack))return;this._baseDts-=Math.min(this._audioNextPts,this._videoNextDts),this._audioLastSample=null,this._videoLastSample=null,this._videoTimestampBreak=!1,this._audioTimestampBreak=!1}}_fixAudio(t){const e=t.samples;e.length&&(e.forEach((t=>{t.pts-=this._baseDts,t.dts=t.pts})),this._doFixAudioInternal(t,e,9e4))}_fixVideo(t){const e=t.samples;if(!e.length)return;if(e.forEach((t=>{t.dts-=this._baseDts,t.pts-=this._baseDts})),void 0===this._videoNextDts){const t=e[0];this._videoNextDts=t.dts}const i=e.length;let s=0;const r=e[0],a=e[1],n=this._videoNextDts-r.dts;let o;Math.abs(n)>45e3&&(r.dts+=n,r.pts+=n,this.player.debug.warn(this.TAG_NAME,`large video gap between chunk,\n next dts is ${this._videoNextDts},\n first dts is ${r.dts},\n next dts is ${a.dts},\n duration is ${n}`),a&&Math.abs(a.dts-r.dts)>$i&&(this._videoTimestampBreak=!0,e.forEach(((t,e)=>{0!==e&&(t.dts+=n,t.pts+=n)}))));const h=t.samples[0],l=t.samples[i-1];o=1===i?9e3:Math.floor((l.dts-h.dts)/(i-1));for(let r=0;r<i;r++){const a=e[r].dts,n=e[r+1];if(s=r<i-1?n.dts-a:e[r-1]?Math.min(a-e[r-1].dts,o):o,s>$i||s<0){this._videoTimestampBreak=!0,s=this._audioTimestampBreak?o:Math.max(s,2700);const i=this._audioNextPts||0;n&&n.dts>i&&(s=o),this.player.debug.warn(this.TAG_NAME,`large video gap between frames,\n time is ${a/t.timescale},\n dts is ${a},\n origin dts is ${e[r].originalDts},\n next dts is ${this._videoNextDts},\n sample Duration is ${s} ,\n ref Sample DurationInt is ${o}`)}e[r].duration=s,this._videoNextDts+=s}}_doFixAudioInternal(t,e,i){t.sampleDuration||(t.sampleDuration=Lt(t.timescale,i));const s=t.sampleDuration;if(void 0===this._audioNextPts){const t=e[0];this._audioNextPts=t.pts}for(let i=0;i<e.length;i++){const r=this._audioNextPts,a=e[i],n=a.pts-r;if(!this._audioTimestampBreak&&n>=3*s&&n<=Wi&&!Gt()){kt(t.codec,t.channelCount)||e[0].data.subarray();const o=Math.floor(n/s);Math.abs(a.pts-this._lastAudioExceptionGapDot)>Yi&&(this._lastAudioExceptionGapDot=a.pts),this.player.debug.warn(this.TAG_NAME,`audio gap detected,\n pts is ${e.pts},\n originPts is ${e.originalPts},\n count is ${o},\n nextPts is ${r},\n ref sample duration is ${s}`);for(let t=0;t<o;t++)this._audioNextPts+=s,i++;i--}else n<=-3*s&&n>=-9e4?(Math.abs(a.pts-this._lastAudioExceptionOverlapDot)>Yi&&(this._lastAudioExceptionOverlapDot=a.pts,this.player.debug.warn(this.TAG_NAME,`audio overlap detected,\n pts is ${a.pts},\n originPts is ${a.originalPts},\n nextPts is ${r},\n ref sample duration is ${s}`)),e.splice(i,1),i--):(Math.abs(n)>=Wi&&(this._audioTimestampBreak=!0,Math.abs(a.pts-this._lastAudioExceptionLargeGapDot)>Yi&&(this._lastAudioExceptionLargeGapDot=a.pts,this.player.debug.warn(this.TAG_NAME,`large audio gap detected,\n time is ${a.pts/1e3}\n pts is ${a.pts},\n originPts is ${a.originalPts},\n nextPts is ${r},\n sample duration is ${n}\n ref sample duration is ${s}`))),a.dts=a.pts=r,this._audioNextPts+=s)}}_calcDecodeFps(t){const e=function(t,e){e&&(t=t.filter((t=>t.type===e)));let i=t[0],s=null,r=1;if(t.length>0){let e=t[1];e&&e.ts-i.ts>1e5&&(i=e,r=2)}if(i)for(let a=r;a<t.length;a++){let r=t[a];e&&r.type!==e&&(r=null),r&&r.ts-i.ts>=1e3&&t[a-1].ts-i.ts<1e3&&(s=a+1)}return s}(t.map((t=>({ts:t.dts||t.pts,type:t.type}))),b);e&&(this._basefps=e,this._postMessageToLoopWorker("updateBaseFps",{baseFps:this._basefps}),this.player.debug.log(this.TAG_NAME,`_calcDecodeFps() video fps is ${e}, update base fps is ${this._basefps}`))}_initLoopWorker(){const t=Xt(function(){const t=1,e=2;let i=new class{constructor(){this.baseFps=0,this.fpsInterval=null,this.preLoopTimestamp=null,this.startBpsTime=null,this.allSampleList=[]}destroy(){this._clearInterval(),this.baseFps=0,this.allSampleList=[],this.preLoopTimestamp=null,this.startBpsTime=null}updateBaseFps(t){this.baseFps=t,this._clearInterval(),this._startInterval()}pushSample(t){delete t.cmd,this.allSampleList.push(t)}_startInterval(){const t=Math.ceil(1e3/this.baseFps);this.fpsInterval=setInterval((()=>{let e=(new Date).getTime();this.preLoopTimestamp||(this.preLoopTimestamp=e),this.startBpsTime||(this.startBpsTime=e);const i=e-this.preLoopTimestamp;if(i>2*t&&console.warn(`JbPro:[TsLoader LoopWorker] loop interval is ${i}ms, more than ${t} * 2ms`),this._loop(),this.preLoopTimestamp=(new Date).getTime(),this.startBpsTime){e-this.startBpsTime>=1e3&&(this._calcSampleList(),this.startBpsTime=e)}}),t)}_clearInterval(){this.fpsInterval&&(clearInterval(this.fpsInterval),this.fpsInterval=null)}_calcSampleList(){const i={buferredDuration:0,allListLength:this.allSampleList.length,audioListLength:0,videoListLength:0};this.allSampleList.forEach((s=>{s.type===e?(i.videoListLength++,s.duration&&(i.buferredDuration+=s.duration/90)):s.type===t&&i.audioListLength++})),postMessage({cmd:"sampleListInfo",...i})}_loop(){let i=null;if(this.allSampleList.length)if(i=this.allSampleList.shift(),i.type===e){postMessage({cmd:"decodeVideo",...i},[i.payload.buffer]);let e=this.allSampleList[0];for(;e&&e.type===t;)i=this.allSampleList.shift(),postMessage({cmd:"decodeAudio",...i},[i.payload.buffer]),e=this.allSampleList[0]}else i.type===t&&(postMessage({cmd:"decodeAudio",...i},[i.payload.buffer]),this.allSampleList.length&&this.allSampleList[0].type===e&&(i=this.allSampleList.shift(),postMessage({cmd:"decodeVideo",...i},[i.payload.buffer])))}};self.onmessage=t=>{const e=t.data;switch(e.cmd){case"updateBaseFps":i.updateBaseFps(e.baseFps);break;case"sample":i.pushSample(e);break;case"destroy":i.destroy(),i=null}}}.toString()),e=new Blob([t],{type:"text/javascript"}),i=URL.createObjectURL(e);let s=new Worker(i);this.workerUrl=i,this.workerClearTimeout=setTimeout((()=>{window.URL.revokeObjectURL(this.workerUrl),this.workerUrl=null,this.workerClearTimeout=null}),1e4),s.onmessage=t=>{const e=t.data;switch(e.cmd){case"decodeVideo":this._doDecodeVideo(e);break;case"decodeAudio":this._doDecodeAudio(e);break;case"sampleListInfo":this.tempSampleListInfo=e}},this.loopWorker=s}_postMessageToLoopWorker(t,e){this.loopWorker?this.loopWorker.postMessage({cmd:t,...e}):this.player.debug.warn(this.TAG_NAME,"loop worker is not init, can not post message")}_doDecodeAudio(t){const e=new Uint8Array(t.payload);this._doDecodeByHls(e,y,t.dts,!1,0)}_doDecodeVideo(t){const e=new Uint8Array(t.payload);let i=null;i=t.isHevc?ve(e,t.isIFrame):ue(e,t.isIFrame),this.player._updateStats({dts:t.dts});const s=t.pts-t.dts;this._doDecodeByHls(i,b,t.dts,t.isIFrame,s)}_stopDecodeLoopInterval(){this._baseFpsInterval&&(clearInterval(this._baseFpsInterval),this._baseFpsInterval=null)}getBuferredDuration(){return this.tempSampleListInfo.buferredDuration||0}getSampleListLength(){return this.tempSampleListInfo.allListLength||0}getSampleAudioListLength(){return this.tempSampleListInfo.audioListLength||0}getSampleVideoListLength(){return this.tempSampleListInfo.videoListLength||0}}class qi extends Ie{constructor(t){super(t),this.player=t,this.TAG_NAME="HlsFmp4Loader",this.tempSampleListInfo={},this.isInitVideo=!1,this.isInitAudio=!1,t.debug.log(this.TAG_NAME,"init")}destroy(){super.destroy(),this.isInitVideo=!1,this.isInitAudio=!1,this.player.debug.log(this.TAG_NAME,"destroy")}dispatch(t){let e=He.createFile();e.onReady=t=>{const i=t.videoTracks[0],s=t.audioTracks[0];if(i&&Kt(this.isInitVideo)){this.videoTrackId=i.id;const t=this.getSeqHeader(e,i);t&&(this.player.debug.log(this.TAG_NAME,"seqHeader",t),this._doDecodeByFmp4(t,b,0,!0,0),this.isInitVideo=!0),e.setExtractionOptions(i.id)}if(s&&Kt(this.isInitAudio)){this.audioTrackId=s.id;const t=s.audio||{},i=Bt.indexOf(t.sample_rate),r=s.codec.replace("mp4a.40.","");e.setExtractionOptions(s.id);const a={profile:parseInt(r,10),sampleRate:i,channel:t.channel_count},n=At(a);this.player.debug.log(this.TAG_NAME,"aacADTSHeader",n,"config",a),this._doDecodeByFmp4(n,y,0,!1,0),this.isInitAudio=!0}e.start()},e.onError=t=>{this.player.debug.error(this.TAG_NAME,"mp4Box onError",t)},e.onSamples=(t,e,i)=>{if(t===this.videoTrackId)for(const t of i){const e=t.data,i=t.is_sync,s=1e3*t.cts/t.timescale;t.duration,t.timescale,this.player.updateStats({vbps:e.byteLength,dts:s}),i&&this.calcIframeIntervalTimestamp(s);let r=null;r=this.isHevc?ve(e,i):ue(e,i),this.player.debug.log(this.TAG_NAME,"onSamples: video","timestamp",s),this._doDecodeByFmp4(r,b,s,i,0)}else if(t===this.audioTrackId)for(const t of i){const e=t.data;this.player.updateStats({abps:e.byteLength});const i=1e3*t.cts/t.timescale,s=1e3*t.duration/t.timescale,r=new Uint8Array(e.byteLength+2);r.set([175,1],0),r.set(e,2),this.player.debug.log(this.TAG_NAME,"onSamples: audio","timestamp",i,"duration",s),this._doDecodeByFmp4(r,y,i,!1,0)}else this.player.debug.warn(this.TAG_NAME,"onSamples() trackId error",t)};let i=new Uint8Array(t);i.buffer.fileStart=0,e.appendBuffer(i.buffer),e.flush()}getSeqHeader(t,e){if(t){const i=t.getTrackById(e.id);for(const t of i.mdia.minf.stbl.stsd.entries)if(t.avcC||t.hvcC){const e=new He.DataStream(void 0,0,He.DataStream.BIG_ENDIAN);let i=[];t.avcC?(t.avcC.write(e),i=[23,0,0,0,0]):(this.isHevc=!0,t.hvcC.write(e),i=[28,0,0,0,0]);const s=new Uint8Array(e.buffer,8),r=new Uint8Array(i.length+s.length);return r.set(i,0),r.set(s,i.length),r}}return null}getBuferredDuration(){return this.tempSampleListInfo.buferredDuration||0}getSampleListLength(){return this.tempSampleListInfo.allListLength||0}getSampleAudioListLength(){return this.tempSampleListInfo.audioListLength||0}getSampleVideoListLength(){return this.tempSampleListInfo.videoListLength||0}}class Ki{constructor(t,e){this.hls=t,this.player=this.hls.player,this.isMP4=e,this._initSegmentId="",this.TAG_NAME="HlsTransmuxer",this.hlsV2Mp4NotSupport=!1,this._demuxer=e?new qi(this.hls.player):new ji(this.hls.player)}destroy(){this.hlsV2Mp4NotSupport=!1,this._demuxer&&(this._demuxer.destroy(),this._demuxer=null)}transmux(t,e,i,s,r,a){this.player.debug.log(this.TAG_NAME,`transmux videoChunk:${t&&t.byteLength}, audioChunk:${e&&e.byteLength}, discontinuity:${i}, contiguous:${s}, startTime:${r}, needInit:${a}`);const n=this._demuxer;try{if(this.isMP4){if(this.hlsV2Mp4NotSupport)return;this.player.debug.warn(this.TAG_NAME,"transmuxer isMP4"),this.player._emitError(L.hlsV2Mp4NotSupport),this.hlsV2Mp4NotSupport=!0}else n.demuxAndFix(Hi(t,e),i,s,r)}catch(t){throw new mi(_i,fi,t)}}}function Xi(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return(t[e]<<24>>>0)+(t[e+1]<<16)+(t[e+2]<<8)+(t[e+3]||0)}function Ji(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;const i=Math.pow(2,32);return Xi(t,e)*i+Xi(t,e+4)}class Zi{static probe(t){return!!Zi.findBox(t,["ftyp"])}static findBox(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;const s=[];if(!t)return s;let r=0,a="",n=0;for(;t.length>7;){if(r=Xi(t),a=String.fromCharCode.apply(null,t.subarray(4,8)),n=8,1===r?(r=Ji(t,8),n+=8):r||(r=t.length),!e[0]||a===e[0]){const o=t.subarray(0,r);if(!(e.length<2))return Zi.findBox(o.subarray(n),e.slice(1),i+n);s.push({start:i,size:r,headerSize:n,type:a,data:o})}i+=r,t=t.subarray(r)}return s}}class Qi{constructor(t){this.hls=t,this.player=t.player,this._decryptor=new Vi,this._transmuxer=null,this._mse=null,this._softVideo=null,this._sourceCreated=!1,this._needInitSegment=!0,this._directAppend=!1,this.TAG_NAME="HlsBufferService"}async destroy(){this._softVideo=null,this._transmuxer&&(this._transmuxer.destroy(),this._transmuxer=null)}get baseDts(){return this._transmuxer?._demuxer?._baseDts}get nbSb(){return 0}async updateDuration(t){this.player.debug.log(this.TAG_NAME,"updateDuration()",t)}getBuferredDuration(){return this._transmuxer?._demuxer?.getBuferredDuration()}getBufferedSegments(){return this._transmuxer?._demuxer?.getSampleListLength()}getBufferedAudioSegments(){return this._transmuxer?._demuxer?.getSampleAudioListLength()}getBufferedVideoSegments(){return this._transmuxer?._demuxer?.getSampleVideoListLength()}createSource(t,e,i,s){if(this._sourceCreated)return;const r=t||e;r&&(ji.probe(r)?this._transmuxer||(this._transmuxer=new Ki(this.hls,!1)):Zi.probe(r)?this._transmuxer||(this._transmuxer=new Ki(this.hls,!0)):this.player.debug.error(this.TAG_NAME,"createSource error: chunk is not ts"))}async appendBuffer(t,e,i,s,r,a,n){if(i?.length||s?.length)return this._needInitSegment,this._transmuxer.transmux(i,s,r,a,n,this._needInitSegment||r),!0}async clearAllBuffer(){this.player.debug.log(this.TAG_NAME,"clearAllBuffer")}decryptBuffer(t,e){return this._decryptor.decrypt(t,e)}async reset(){this._transmuxer=null,this._needInitSegment=!0,this._directAppend=!1}async endOfStream(){this._softVideo&&this._softVideo.endOfStream()}async setLiveSeekableRange(t,e){}seamlessSwitch(){this._needInitSegment=!0}}class es{constructor(t){this.emitter=t,this._seiSet=new Set,t.on(gt,(t=>{t&&this._seiSet.add(t)}))}throw(t){if(null==t||!this._seiSet.size)return;const e=t-.2,i=t+.2,s=[];this._seiSet.forEach((t=>{t.time>=e&&t.time<=i&&s.push(t)})),s.forEach((t=>{this._seiSet.delete(t),this.emitter.emit(yt,t)}))}reset(){this._seiSet.clear()}}class is{constructor(t){this._timescale=t,this.encodeType="",this.audioCodec="",this.videoCodec="",this.domain="",this.fps=0,this.bitrate=0,this.width=0,this.height=0,this.samplerate=0,this.channelCount=0,this.gop=0,this._bitsAccumulateSize=0,this._bitsAccumulateDuration=0}getStats(){return{encodeType:this.encodeType,audioCodec:this.audioCodec,videoCodec:this.videoCodec,domain:this.domain,fps:this.fps,bitrate:this.bitrate,width:this.width,height:this.height,samplerate:this.samplerate,channelCount:this.channelCount,gop:this.gop}}setEncodeType(t){this.encodeType=t}setFpsFromScriptData(t){let{data:e}=t;const i=e?.onMetaData?.framerate;i&&i>0&&i<100&&(this.fps=i)}setVideoMeta(t){if(this.width=t.width,this.height=t.height,this.videoCodec=t.codec,this.encodeType=t.codecType,t.fpsNum&&t.fpsDen){const e=t.fpsNum/t.fpsDen;e>0&&e<100&&(this.fps=e)}}setAudioMeta(t){this.audioCodec=t.codec,this.samplerate=t.sampleRate,this.channelCount=t.channelCount}setDomain(t){this.domain=t.split("/").slice(2,3)[0]}updateBitrate(t){if((!this.fps||this.fps>=100)&&t.length){const e=t.reduce(((t,e)=>t+e.duration),0)/t.length;this.fps=Math.round(this._timescale/e)}t.forEach((t=>{1===t.gopId&&this.gop++,this._bitsAccumulateDuration+=t.duration/(this._timescale/1e3),this._bitsAccumulateSize+=t.units.reduce(((t,e)=>t+e.length),0),this._bitsAccumulateDuration>=1e3&&(this.bitrate=8*this._bitsAccumulateSize,this._bitsAccumulateDuration=0,this._bitsAccumulateSize=0)}))}}class ss{_core=null;_samples=[];constructor(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1e3;this._core=t,this._timescale=e,this._stats=new is(e),this._bindEvents()}getStats(){const{currentTime:t=0,decodeFps:e=0}=this._core?.media||{};return{...this._stats.getStats(),downloadSpeed:this._core?.speedInfo?.().speed||0,avgSpeed:this._core?.speedInfo?.().avgSpeed||0,currentTime:t,bufferEnd:this._core?.bufferInfo()?.remaining||0,decodeFps:e}}_bindEvents(){this._core.on(ht,(t=>this._stats.updateBitrate(t.samples))),this._core.on(lt,(t=>{this._stats.setFpsFromScriptData(t)})),this._core.on(dt,(t=>{"video"===t.type?this._stats.setVideoMeta(t.track):this._stats.setAudioMeta(t.track)})),this._core.on(ut,(t=>{this._stats.setDomain(t.responseUrl)}))}reset(){this._samples=[],this._stats=new is(this._timescale)}}class rs extends t{constructor(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),this.player=t,this.config=null,this._manifestLoader=null,this._segmentLoader=null,this._playlist=null,this._bufferService=null,this._seiService=null,this._stats=null,this._prevSegSn=null,this._prevSegCc=null,this._tickTimer=null,this._tickInterval=500,this._segmentProcessing=!1,this._reloadOnPlay=!1,this._switchUrlOpts=null,this._disconnectTimer=null,this.TAG_NAME="Hls256",this.config=e=function(t){return{isLive:!0,maxPlaylistSize:50,retryCount:3,retryDelay:1e3,pollRetryCount:2,loadTimeout:1e4,preloadTime:30,softDecode:!1,bufferBehind:10,maxJumpDistance:3,startTime:0,targetLatency:10,maxLatency:20,allowedStreamTrackChange:!0,...t}}(e),this._manifestLoader=new Ni(this),this._segmentLoader=new zi(this),this._playlist=new Oi(this),this._bufferService=new Qi(this),this._seiService=new es(this),this._stats=new ss(this,9e4),this.player.debug.log(this.TAG_NAME,"init")}async destroy(){this.player.debug.log(this.TAG_NAME,"destroy()"),this._playlist.reset(),this._segmentLoader.reset(),this._seiService.reset(),await Promise.all([this._clear(),this._bufferService.destroy()]),this._manifestLoader&&(await this._manifestLoader.destroy(),this._manifestLoader=null),this._segmentLoader&&(this._segmentLoader.destroy(),this._segmentLoader=null),this._playlist&&(this._playlist.destroy(),this._playlist=null),this.player.debug.log(this.TAG_NAME,"destroy end")}_startTick(){this._stopTick(),this._tickTimer=setTimeout((()=>{this._tick()}),this._tickInterval)}_stopTick(){this._tickTimer&&clearTimeout(this._tickTimer),this._tickTimer=null}_tick(){this._startTick(),this._loadSegment()}get isLive(){return this._playlist.isLive}get streams(){return this._playlist.streams}get currentStream(){return this._playlist.currentStream}get hasSubtitle(){return this._playlist.hasSubtitle}get baseDts(){return this._bufferService?.baseDts}speedInfo(){return this._segmentLoader.speedInfo()}getStats(){return this._stats.getStats()}async loadSource(t){return this.player.debug.log(this.TAG_NAME,`loadSource() ${t}`),await this._reset(),await this._loadData(t),this._startTick(),!0}async _loadData(t){this.player.debug.log(this.TAG_NAME,`_loadData() ${t}`);try{t&&(t=t.trim())}catch(t){}if(!t)throw this._emitError(new mi(pi,pi,null,null,"m3u8 url is missing"));const e=await this._loadM3U8(t),{currentStream:i}=this._playlist;if(this._urlSwitching){0===i.bitrate&&this._switchUrlOpts?.bitrate&&(i.bitrate=this._switchUrlOpts?.bitrate);const t=this._getSeamlessSwitchPoint();this.config.startTime=t;const e=this._playlist.findSegmentIndexByTime(t),s=this._playlist.getSegmentByIndex(e+1);if(s){const t=s.start;this.player.debug.warn(this.TAG_NAME,`clear buffer from ${t}`)}}e&&(this.isLive?(this.player.debug.log(this.TAG_NAME,"is live"),this._bufferService.setLiveSeekableRange(0,4294967295),this.config.targetLatency<this._playlist.totalDuration&&(this.config.targetLatency=this._playlist.totalDuration,this.config.maxLatency=1.5*this.config.targetLatency),e.isMaster||this._pollM3U8(t)):(this.player.debug.log(this.TAG_NAME,`is vod and totalDuration is ${i.totalDuration} s`),await this._bufferService.updateDuration(i.totalDuration))),await this._loadSegment()}async _loadM3U8(t){let e;this.player.debug.log(this.TAG_NAME,`load m3u8: ${t}`);try{[e]=await this._manifestLoader.load(t)}catch(t){throw this._emitError(mi.create(t))}if(e)return this._playlist.upsertPlaylist(e),e.isMaster?(this._playlist.currentStream.subtitleStreams?.length&&this.emit(vt,{list:this._playlist.currentStream.subtitleStreams}),await this._refreshM3U8()):this.player.debug.warn(this.TAG_NAME,"_loadM3U8() is not master playlist"),this.emit(wt),e;this.player.debug.warn(this.TAG_NAME,"_loadM3U8() playlist is empty")}_refreshM3U8(){this.player.debug.log(this.TAG_NAME,"_refreshM3U8()");const t=this._playlist.currentStream;if(!t||!t.url)throw this._emitError(mi.create(null,null,new Error("m3u8 url is not defined")));const e=t.url,i=t.currentAudioStream?.url,s=t.currentSubtitleStream?.url;return this._manifestLoader.load(e,i,s).then((t=>{let[r,a,n]=t;r?(this._playlist.upsertPlaylist(r,a,n),this.isLive&&this._pollM3U8(e,i,s)):this.player.debug.warn(this.TAG_NAME,"_refreshM3U8() mediaPlaylist is empty")})).catch((t=>{throw this._emitError(mi.create(t))}))}_pollM3U8(t,e,i){let s=this._playlist.isEmpty;this._manifestLoader.poll(t,e,i,((t,e,i)=>{this._playlist.upsertPlaylist(t,e,i),this._playlist.clearOldSegment(),t&&s&&!this._playlist.isEmpty&&this._loadSegment(),s&&(s=this._playlist.isEmpty)}),(t=>{this._emitError(mi.create(t))}),1e3*(this._playlist.lastSegment?.duration||0))}_loadSegment=async()=>{if(this.player.debug.log(this.TAG_NAME,"_loadSegment()","_segmentProcessing",this._segmentProcessing),this._segmentProcessing)return void this.player.debug.warn("_loadSegment()","_segmentProcessing is ture and return");const t=this._playlist.currentSegment,e=this._playlist.nextSegment;if(this.player.debug.log(this.TAG_NAME,"_loadSegment()","curSeg",t,"nextSeg",e),e)return this._loadSegmentDirect();this.player.debug.log(this.TAG_NAME,"nextSeg is null and return")};async _loadSegmentDirect(){this.player.debug.log(this.TAG_NAME,"_loadSegmentDirect()");const t=this._playlist.nextSegment;if(!t)return void this.player.debug.log(this.TAG_NAME,"_loadSegmentDirect() !seg");let e=!1,i=null;try{this._segmentProcessing=!0,e=await this._reqAndBufferSegment(t,this._playlist.getAudioSegment(t))}catch(t){i=t}finally{this._segmentProcessing=!1}return i?this._emitError(mi.create(i)):(e?(this._urlSwitching&&(this._urlSwitching=!1,this.emit(St,{url:this.config.url})),this._playlist.moveSegmentPointer(),this.player.debug.log(this.TAG_NAME,"_loadSegmentDirect()","seg.isLast",t.isLast),t.isLast?(this.player.debug.log(this.TAG_NAME,"_loadSegmentDirect()","seg.isLast"),this._end()):(this.player.debug.log(this.TAG_NAME,"_loadSegmentDirect()","and next _loadSegment()"),this._loadSegment())):this.player.debug.log(this.TAG_NAME,"_loadSegmentDirect() not appended"),e)}async _reqAndBufferSegment(t,e){this.player.debug.log(this.TAG_NAME,"video seg",t&&t.url,"audio seg",e&&e.url);const i=t?t.cc:e.cc,s=this._prevSegCc!==i;let r=[];try{r=await this._segmentLoader.load(t,e,s)}catch(t){throw t.fatal=!1,this._segmentLoader.error=t,t}if(!r[0])return;const a=await this._bufferService.decryptBuffer(...r);if(!a)return void this.player.debug.log(this.TAG_NAME,"decryptBuffer return null");const n=t?t.sn:e.sn,o=t?t.start:e.start,h=this._playlist.currentStream;return this._bufferService.createSource(a[0],a[1],h?.videoCodec,h?.audioCodec),await this._bufferService.appendBuffer(t,e,a[0],a[1],s,this._prevSegSn===n-1,o),this._prevSegCc=i,this._prevSegSn=n,!0}async _clear(){this.player.debug.log(this.TAG_NAME,"_clear()"),clearTimeout(this._disconnectTimer),this._stopTick(),await Promise.all([this._segmentLoader.cancel(),this._manifestLoader.stopPoll()]),this._segmentProcessing=!1}async _reset(){let t=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return this.player.debug.log(this.TAG_NAME,"_reset()"),this._reloadOnPlay=!1,this._prevSegSn=null,this._prevSegCc=null,this._switchUrlOpts=null,this._playlist.reset(),this._segmentLoader.reset(),this._seiService.reset(),this._stats.reset(),await this._clear(),this._bufferService.reset(t)}_end(){this.player.debug.log(this.TAG_NAME,"_end()"),this._clear()}_emitError(t){let e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return!1===t.originError?.fatal?console.warn(t):(console.table(t),console.error(t),console.error(this.media?.error),this._stopTick(),this._urlSwitching&&(this._urlSwitching=!1,this.emit(bt,t)),e&&this._end(),this._seiService.reset(),this.emit(xt,t)),t}_getSeamlessSwitchPoint(){const{media:t}=this;let e=t.currentTime;if(!t.paused){const i=this._playlist.findSegmentIndexByTime(t.currentTime),s=this._playlist.getSegmentByIndex(i),r=this._stats?.getStats().downloadSpeed;if(r&&s){e+=s.duration*this._playlist.currentStream.bitrate/r+1}else e+=5}return e}getDemuxBuferredDuration(){return this._bufferService.getBuferredDuration()||0}getDemuxBufferedListLength(){return this._bufferService.getBufferedSegments()||0}getDemuxAudioBufferedListLength(){return this._bufferService.getBufferedAudioSegments()||0}getDemuxVideoBufferedListLength(){return this._bufferService.getBufferedVideoSegments()||0}}class as extends t{constructor(t){super(),this.TAG_NAME="Hls256Decoder",this.player=t,this.canVideoPlay=!1,this.hls=null,this.eventsDestroy=[],this.bandwidthEstimateInterval=null,this.hls=new rs(t),this._bindEvents()}async destroy(){return this._stopBandwidthEstimateInterval(),this.hls&&(await this.hls.destroy(),this.hls=null),this.eventsDestroy.length&&(this.eventsDestroy.forEach((t=>t())),this.eventsDestroy=[]),this.player.debug.log(this.TAG_NAME,"destroy"),!0}_bindEvents(){this.hls.on(xt,(t=>{this.player._emitError(L.hlsError,t)})),this._startBandwidthEstimateInterval()}_startBandwidthEstimateInterval(){this._stopBandwidthEstimateInterval(),this.bandwidthEstimateInterval=setInterval((()=>{const t=this.hls.speedInfo();this.player.emit(k.kBps,(t.avgSpeed/1024/8).toFixed(2))}),1e3)}_stopBandwidthEstimateInterval(){this.bandwidthEstimateInterval&&(clearInterval(this.bandwidthEstimateInterval),this.bandwidthEstimateInterval=null)}async loadSource(t){return this.player.debug.log(this.TAG_NAME,`loadSource() ${t}`),this.url=t,await this.hls.loadSource(t),!0}checkHlsBufferedDelay(){let t=0;return this.hls&&(t=this.hls.getDemuxBuferredDuration()),t}getDemuxBufferedListLength(){let t=0;return this.hls&&(t=this.hls.getDemuxBufferedListLength()),t}getDemuxAudioBufferedListLength(){let t=0;return this.hls&&(t=this.hls.getDemuxAudioBufferedListLength()),t}getDemuxVideoBufferedListLength(){let t=0;return this.hls&&(t=this.hls.getDemuxVideoBufferedListLength()),t}}class ns extends t{constructor(t){super(),this._opt={},this.TAG_NAME="JbProRecorder",Object.keys(t).forEach((e=>{if(void 0===t[e])throw new Error(`JbPro option "${e}" can not be undefined`)}));const e=jt();let i=Object.assign({},e,t);Wt(i.timeout)&&(Vt(i.loadingTimeout)&&(i.loadingTimeout=i.timeout),Vt(i.heartTimeout)&&(i.heartTimeout=i.timeout)),i.debugUuid="xxxx".replace(/[xy]/g,(function(t){var e=16*Math.random()|0;return("x"==t?e:3&e|8).toString(16)})),this._opt=i,this._destroyed=!1,this._loadingTimeoutReplayTimes=0,this.debug=new Jt(this),this.events=new Zt(this),this.audio=new te(this),this.video=new Qt(this),this.recorder=null,this.stream=null,this.demux=null,this.hlsDecoder=null,this._stats={},this._initDebug(),this.debug.log(this.TAG_NAME,`init success and version is ${zt}`),console.log(`JbProRecorder version is ${zt}`)}destroy(){return new Promise(((t,e)=>{this.stop().then((()=>{this.audio&&(this.audio.destroy(),this.audio=null),this.video&&(this.video.destroy(),this.video=null),t()})).catch((t=>{e(t)}))}))}_init(){return new Promise(((t,e)=>{this.stream||(this.stream=new ne(this)),this.demux||(this.demux=new We(this)),this.recorder||(this.recorder=new Le(this)),this._opt.isHls&&!this.hlsDecoder&&(this.hlsDecoder=new as(this)),t()}))}_initDebug(){if(this._opt.debug){const t=[],e=[k.stats,k.playbackStats,k.playbackTimestamp,k.flvMetaData,k.playToRenderTimes];Object.keys(k).forEach((i=>{this.on(k[i],(s=>{t.includes(i)||(e.includes(i)&&(s=JSON.stringify(s)),this.debug.log("player events",k[i],s))}))})),Object.keys(L).forEach((t=>{this.on(L[t],(e=>{this.debug.warn("player event error",L[t],e)}))}))}}_checkLoadingTimeout(){}_startCheckStatsInterval(){this._checkStatsInterval=setInterval((()=>{this._updateStats()}),1e3)}_stopCheckStatsInterval(){this._checkStatsInterval&&(clearInterval(this._checkStatsInterval),this._checkStatsInterval=null)}_updateStats(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(this._startBpsTime||(this._startBpsTime=Rt()),Wt(t.ts)){const e=parseInt(t.ts,10);this._stats.ts=e}t.abps&&(this._stats.abps+=t.abps),t.vbps&&(this._stats.vbps+=t.vbps);const e=Rt();if(e-this._startBpsTime<1e3)return;const i=this.recorder.getTotalDuration(),s=this.recorder.getToTalByteLength();this.emit(k.stats,{...this._stats,duration:i,durationShow:Yt(i),size:s,sizeShow:Ot(s)}),this._stats.abps=0,this._stats.vbps=0,this._startBpsTime=e}_resetStats(){this._stats={abps:0,vbps:0,ts:0}}_resetDemuxType(t){this._opt.isFlv=!1,this._opt.isFmp4=!1,this._opt.isNakedFlow=!1,this._opt.isHls=!1,t&&(this._opt[t]=!0)}_updateOption(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this._opt=Object.assign({},this._opt,t)}startRecord(t){let a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new Promise(((n,o)=>{if(!t)return o("url is required");this.loading=!0,this.playing=!1,this._opt.url=t,this._opt.playOptions=a;const h=0===t.indexOf("http"),l=0===t.indexOf("wt:"),m=-1!==t.indexOf(".m3u8"),g=-1!==t.indexOf(".flv"),y=-1!==t.indexOf(".fmp4")||-1!==t.indexOf(".mp4"),b=-1!==t.indexOf(".h264")||-1!==t.indexOf(".h265");let S=null,v=null;if(g&&!this._opt.isFlv&&this._resetDemuxType("isFlv"),y&&!this._opt.isFmp4&&this._resetDemuxType("isFmp4"),b&&!this._opt.isNakedFlow&&this._resetDemuxType("isNakedFlow"),S=h?m?s:i:l?r:e,v=this._opt.isNakedFlow?f:this._opt.isFmp4?_:h&&!m||g||this._opt.isFlv?d:m?p:l?c:u,!S||!v)return o(`play protocol is ${S}, demuxType is ${v}`);this._updateOption({protocol:S,demuxType:v,isHls:m}),this._init().then((()=>{this._checkLoadingTimeout(),this.stream&&(this.stream.once(k.streamSuccess,(()=>{n(),this._startCheckStatsInterval(),this.debug.log(this.TAG_NAME,"stream success and start play")})),this.stream.fetchStream(t))}))}))}stopRecordAndSave(t,e){return new Promise(((i,s)=>{this.recorder.stopRecordAndSave(t,e).then((t=>{setTimeout((()=>{i(t)}),0)})).catch((t=>{s(t)})).finally((()=>{this.stop()}))}))}async stop(){this._stopCheckStatsInterval(),this.hlsDecoder&&(await this.hlsDecoder.destroy(),this.hlsDecoder=null),this.stream&&(this.stream.destroy(),this.stream=null),this.recorder&&(this.recorder.destroy(),this.recorder=null),this.demux&&(this.demux.destroy(),this.demux=null),this.audio&&this.audio.resetInit(),this.video&&this.video.resetInit()}clear(){this.stop()}isRecordTypeFlv(){return this.recorder&&this._opt.recordType===l.flv}isRecordTypeMp4(){return this.recorder&&this._opt.recordType===l.mp4}_hasVideoAndAudioInit(){let t=Kt(this._opt.hasVideo),e=Kt(this._opt.hasAudio);return qt(this._opt.hasVideo)&&this.video&&this.video.hasInit()&&(t=!0),qt(this._opt.hasAudio)&&this.audio&&this.audio.hasInit()&&(e=!0),t&&e}_emitError(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";this.emit(k.error,t,e),this.emit(t,e)}downloadBlob(t,e,i){if(![l.mp4,l.flv].includes(i))throw new Error(`downloadBlob type is ${i}, must be ${l.mp4} or ${l.flv}`);Ht((e||Rt())+"."+i,t)}}return ns.ERROR=L,ns.EVENTS=k,window.JessibucaProRecorder=ns,window.WebPlayerProRecorder=ns,ns}));
|