@twick/visualizer 0.14.17 → 0.14.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -14,6 +14,8 @@ npm install @twick/visualizer
14
14
  pnpm add @twick/visualizer
15
15
  ```
16
16
 
17
+ **Note:** All required dependencies (`@twick/media-utils`) are automatically installed with `@twick/visualizer`.
18
+
17
19
  ## Quick Start
18
20
 
19
21
  ```typescript
package/dist/project.js CHANGED
@@ -142,4 +142,4 @@ Schedule: ${u.map(_=>_t(_))} pos: ${this.timelinePos}`),p.length&&this.log(`Remo
142
142
  `),d=[],p=e?Xy(e.baseTime,e.timescale):0;let g="00:00.000",y=0,x=0,v,_=!0;l.oncue=function(o){const c=t[s];let f=t.ccOffset;const m=(y-p)/9e4;if(c!=null&&c.new&&(x!==void 0?f=t.ccOffset=c.start:Hx(t,s,m)),m){if(!e){v=new Error("Missing initPTS for VTT MPEGTS");return}f=m-t.presentationOffset}const S=o.endTime-o.startTime,T=lt((o.startTime+f-x)*9e4,n*9e4)/9e4;o.startTime=Math.max(T,0),o.endTime=Math.max(T+S,0);const b=o.text.trim();o.text=decodeURIComponent(encodeURIComponent(b)),o.id||(o.id=Xo(o.startTime,o.endTime,b)),o.endTime>0&&d.push(o)},l.onparsingerror=function(o){v=o},l.onflush=function(){if(v){h(v);return}a(d)},u.forEach(o=>{if(_)if(va(o,"X-TIMESTAMP-MAP=")){_=!1,o.slice(16).split(",").forEach(c=>{va(c,"LOCAL:")?g=c.slice(6):va(c,"MPEGTS:")&&(y=parseInt(c.slice(7)))});try{x=zx(g)/1e3}catch(c){v=c}return}else o===""&&(_=!1);l.parse(o+`
143
143
  `)}),l.flush()}const xa="stpp.ttml.im1t",Lu=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Ru=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Kx={left:"start",center:"center",right:"end",start:"start",end:"end"};function zh(r,e,t,s){const n=de(new Uint8Array(r),["mdat"]);if(n.length===0){s(new Error("Could not parse IMSC1 mdat"));return}const a=n.map(l=>dt(l)),h=qy(e.baseTime,1,e.timescale);try{a.forEach(l=>t(Yx(l,h)))}catch(l){s(l)}}function Yx(r,e){const n=new DOMParser().parseFromString(r,"text/xml").getElementsByTagName("tt")[0];if(!n)throw new Error("Invalid ttml");const a={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},h=Object.keys(a).reduce((g,y)=>(g[y]=n.getAttribute(`ttp:${y}`)||a[y],g),{}),l=n.getAttribute("xml:space")!=="preserve",u=Hh(Sa(n,"styling","style")),d=Hh(Sa(n,"layout","region")),p=Sa(n,"body","[begin]");return[].map.call(p,g=>{const y=Cu(g,l);if(!y||!g.hasAttribute("begin"))return null;const x=Ea(g.getAttribute("begin"),h),v=Ea(g.getAttribute("dur"),h);let _=Ea(g.getAttribute("end"),h);if(x===null)throw Vh(g);if(_===null){if(v===null)throw Vh(g);_=x+v}const o=new qo(x-e,_-e,y);o.id=Xo(o.startTime,o.endTime,o.text);const c=d[g.getAttribute("region")],f=u[g.getAttribute("style")],m=Wx(c,f,u),{textAlign:S}=m;if(S){const T=Kx[S];T&&(o.lineAlign=T),o.align=S}return Ee(o,m),o}).filter(g=>g!==null)}function Sa(r,e,t){const s=r.getElementsByTagName(e)[0];return s?[].slice.call(s.querySelectorAll(t)):[]}function Hh(r){return r.reduce((e,t)=>{const s=t.getAttribute("xml:id");return s&&(e[s]=t),e},{})}function Cu(r,e){return[].slice.call(r.childNodes).reduce((t,s,n)=>{var a;return s.nodeName==="br"&&n?t+`
144
144
  `:(a=s.childNodes)!=null&&a.length?Cu(s,e):e?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent},"")}function Wx(r,e,t){const s="http://www.w3.org/ns/ttml#styling";let n=null;const a=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],h=r!=null&&r.hasAttribute("style")?r.getAttribute("style"):null;return h&&t.hasOwnProperty(h)&&(n=t[h]),a.reduce((l,u)=>{const d=_a(e,s,u)||_a(r,s,u)||_a(n,s,u);return d&&(l[u]=d),l},{})}function _a(r,e,t){return r&&r.hasAttributeNS(e,t)?r.getAttributeNS(e,t):null}function Vh(r){return new Error(`Could not parse ttml timestamp ${r}`)}function Ea(r,e){if(!r)return null;let t=Au(r);return t===null&&(Lu.test(r)?t=jx(r,e):Ru.test(r)&&(t=qx(r,e))),t}function jx(r,e){const t=Lu.exec(r),s=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+s/e.frameRate}function qx(r,e){const t=Ru.exec(r),s=Number(t[1]);switch(t[2]){case"h":return s*3600;case"m":return s*60;case"ms":return s*1e3;case"f":return s/e.frameRate;case"t":return s/e.tickRate}return s}class An{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,s){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=s,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class Xx{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Yh(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(E.FRAG_LOADING,this.onFragLoading,this),e.on(E.FRAG_LOADED,this.onFragLoaded,this),e.on(E.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(E.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(E.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(E.FRAG_LOADING,this.onFragLoading,this),e.off(E.FRAG_LOADED,this.onFragLoaded,this),e.off(E.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(E.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(E.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new An(this,"textTrack1"),t=new An(this,"textTrack2"),s=new An(this,"textTrack3"),n=new An(this,"textTrack4");this.cea608Parser1=new Gh(1,e,t),this.cea608Parser2=new Gh(3,s,n)}addCues(e,t,s,n,a){let h=!1;for(let l=a.length;l--;){const u=a[l],d=Qx(u[0],u[1],t,s);if(d>=0&&(u[0]=Math.min(u[0],t),u[1]=Math.max(u[1],s),h=!0,d/(s-t)>.5))return}if(h||a.push([t,s]),this.config.renderTextTracksNatively){const l=this.captionsTracks[e];this.Cues.newCue(l,t,s,n)}else{const l=this.Cues.newCue(null,t,s,n);this.hls.trigger(E.CUES_PARSED,{type:"captions",cues:l,track:e})}}onInitPtsFound(e,{frag:t,id:s,initPTS:n,timescale:a,trackId:h}){const{unparsedVttFrags:l}=this;s===X.MAIN&&(this.initPTS[t.cc]={baseTime:n,timescale:a,trackId:h}),l.length&&(this.unparsedVttFrags=[],l.forEach(u=>{this.initPTS[u.frag.cc]?this.onFragLoaded(E.FRAG_LOADED,u):this.hls.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:u.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(e,t){const{media:s}=this;if(s)for(let n=0;n<s.textTracks.length;n++){const a=s.textTracks[n];if(Kh(a,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return a}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:s,media:n}=this,{label:a,languageCode:h}=t[e],l=this.getExistingTrack(a,h);if(l)s[e]=l,ss(s[e]),Su(s[e],n);else{const u=this.createTextTrack("captions",a,h);u&&(u[e]=!0,s[e]=u)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const s=t.label,n={_id:e,label:s,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=n,this.hls.trigger(E.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[n]})}createTextTrack(e,t,s){const n=this.media;if(n)return n.addTextTrack(e,t,s)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){const s=!!t.transferMedia;if(this.media=null,s)return;const{captionsTracks:n}=this;Object.keys(n).forEach(a=>{ss(n[a]),delete n[a]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Yh(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let s=0;s<t.length;s++)ss(t[s])}onSubtitleTracksUpdated(e,t){const s=t.subtitleTracks||[],n=s.some(a=>a.textCodec===xa);if(this.config.enableWebVTT||n&&this.config.enableIMSC1){if(ou(this.tracks,s)){this.tracks=s;return}if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){const h=this.media,l=h?$n(h.textTracks):null;if(this.tracks.forEach((u,d)=>{let p;if(l){let g=null;for(let y=0;y<l.length;y++)if(l[y]&&Kh(l[y],u)){g=l[y],l[y]=null;break}g&&(p=g)}if(p)ss(p);else{const g=Pu(u);p=this.createTextTrack(g,u.name,u.lang),p&&(p.mode="disabled")}p&&this.textTracks.push(p)}),l!=null&&l.length){const u=l.filter(d=>d!==null).map(d=>d.label);u.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${u.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const h=this.tracks.map(l=>({label:l.name,kind:l.type.toLowerCase(),default:l.default,subtitleTrack:l}));this.hls.trigger(E.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:h})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(s=>{const n=/(?:CC|SERVICE)([1-4])/.exec(s.instreamId);if(!n)return;const a=`textTrack${n[1]}`,h=this.captionsProperties[a];h&&(h.label=s.name,s.lang&&(h.languageCode=s.lang),h.media=s)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t==null?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===X.MAIN){var s,n;const{cea608Parser1:a,cea608Parser2:h,lastSn:l}=this,{cc:u,sn:d}=t.frag,p=(s=(n=t.part)==null?void 0:n.index)!=null?s:-1;a&&h&&(d!==l+1||d===l&&p!==this.lastPartIndex+1||u!==this.lastCc)&&(a.reset(),h.reset()),this.lastCc=u,this.lastSn=d,this.lastPartIndex=p}}onFragLoaded(e,t){const{frag:s,payload:n}=t;if(s.type===X.SUBTITLE)if(n.byteLength){const a=s.decryptdata,h="stats"in t;if(a==null||!a.encrypted||h){const l=this.tracks[s.level],u=this.vttCCs;u[s.cc]||(u[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),l&&l.textCodec===xa?this._parseIMSC1(s,n):this._parseVTTs(t)}}else this.hls.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const s=this.hls;zh(t,this.initPTS[e.cc],n=>{this._appendCues(n,e.level),s.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},n=>{s.logger.log(`Failed to parse IMSC1: ${n}`),s.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:n})})}_parseVTTs(e){var t;const{frag:s,payload:n}=e,{initPTS:a,unparsedVttFrags:h}=this,l=a.length-1;if(!a[s.cc]&&l===-1){h.push(e);return}const u=this.hls,d=(t=s.initSegment)!=null&&t.data?yt(s.initSegment.data,new Uint8Array(n)).buffer:n;Vx(d,this.initPTS[s.cc],this.vttCCs,s.cc,s.start,p=>{this._appendCues(p,s.level),u.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s})},p=>{const g=p.message==="Missing initPTS for VTT MPEGTS";g?h.push(e):this._fallbackToIMSC1(s,n),u.logger.log(`Failed to parse VTT cue: ${p}`),!(g&&l>s.cc)&&u.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:p})})}_fallbackToIMSC1(e,t){const s=this.tracks[e.level];s.textCodec||zh(t,this.initPTS[e.cc],()=>{s.textCodec=xa,this._parseIMSC1(e,t)},()=>{s.textCodec="wvtt"})}_appendCues(e,t){const s=this.hls;if(this.config.renderTextTracksNatively){const n=this.textTracks[t];if(!n||n.mode==="disabled")return;e.forEach(a=>_u(n,a))}else{const n=this.tracks[t];if(!n)return;const a=n.default?"default":"subtitles"+t;s.trigger(E.CUES_PARSED,{type:"subtitles",cues:e,track:a})}}onFragDecrypted(e,t){const{frag:s}=t;s.type===X.SUBTITLE&&this.onFragLoaded(E.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:s,samples:n}=t;if(!(s.type===X.MAIN&&this.closedCaptionsForLevel(s)==="NONE"))for(let a=0;a<n.length;a++){const h=n[a].bytes;if(h){this.cea608Parser1||this.initCea608Parsers();const l=this.extractCea608Data(h);this.cea608Parser1.addData(n[a].pts,l[0]),this.cea608Parser2.addData(n[a].pts,l[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:s,endOffsetSubtitles:n,type:a}){const{media:h}=this;if(!(!h||h.currentTime<s)){if(!a||a==="video"){const{captionsTracks:l}=this;Object.keys(l).forEach(u=>io(l[u],t,s))}if(this.config.renderTextTracksNatively&&t===0&&n!==void 0){const{textTracks:l}=this;Object.keys(l).forEach(u=>io(l[u],t,n))}}}extractCea608Data(e){const t=[[],[]],s=e[0]&31;let n=2;for(let a=0;a<s;a++){const h=e[n++],l=127&e[n++],u=127&e[n++];if(l===0&&u===0)continue;if((4&h)!==0){const p=3&h;(p===0||p===1)&&(t[p].push(l),t[p].push(u))}}return t}}function Pu(r){return r.characteristics&&/transcribes-spoken-dialog/gi.test(r.characteristics)&&/describes-music-and-sound/gi.test(r.characteristics)?"captions":"subtitles"}function Kh(r,e){return!!r&&r.kind===Pu(e)&&Za(e,r)}function Qx(r,e,t,s){return Math.min(e,s)-Math.max(r,t)}function Yh(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}const Zx=/\s/,Jx={newCue(r,e,t,s){const n=[];let a,h,l,u,d;const p=self.VTTCue||self.TextTrackCue;for(let y=0;y<s.rows.length;y++)if(a=s.rows[y],l=!0,u=0,d="",!a.isEmpty()){var g;for(let _=0;_<a.chars.length;_++)Zx.test(a.chars[_].uchar)&&l?u++:(d+=a.chars[_].uchar,l=!1);a.cueStartTime=e,e===t&&(t+=1e-4),u>=16?u--:u++;const x=wu(d.trim()),v=Xo(e,t,x);r!=null&&(g=r.cues)!=null&&g.getCueById(v)||(h=new p(e,t,x),h.id=v,h.line=y+1,h.align="left",h.position=10+Math.min(80,Math.floor(u*8/32)*10),n.push(h))}return r&&n.length&&(n.sort((y,x)=>y.line==="auto"||x.line==="auto"?0:y.line>8&&x.line>8?x.line-y.line:y.line-x.line),n.forEach(y=>_u(r,y))),n}};function eS(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const tS=/(\d+)-(\d+)\/(\d+)/;class Wh{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||rS,this.controller=new self.AbortController,this.stats=new Lo}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,s){const n=this.stats;if(n.loading.start)throw new Error("Loader can only be used once.");n.loading.start=self.performance.now();const a=iS(e,this.controller.signal),h=e.responseType==="arraybuffer",l=h?"byteLength":"length",{maxTimeToFirstByteMs:u,maxLoadTimeMs:d}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=s,this.request=this.fetchSetup(e,a),self.clearTimeout(this.requestTimeout),t.timeout=u&&q(u)?u:d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(n,e,this.response))},t.timeout),(Ys(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(g=>{var y;this.response=this.loader=g;const x=Math.max(self.performance.now(),n.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(n,e,this.response))},d-(x-n.loading.start)),!g.ok){const{status:_,statusText:o}=g;throw new aS(o||"fetch, bad network response",_,g)}n.loading.first=x,n.total=nS(g.headers)||n.total;const v=(y=this.callbacks)==null?void 0:y.onProgress;return v&&q(t.highWaterMark)?this.loadProgressively(g,n,e,t.highWaterMark,v):h?g.arrayBuffer():e.responseType==="json"?g.json():g.text()}).then(g=>{var y,x;const v=this.response;if(!v)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),n.loading.end=Math.max(self.performance.now(),n.loading.first);const _=g[l];_&&(n.loaded=n.total=_);const o={url:v.url,data:g,code:v.status},c=(y=this.callbacks)==null?void 0:y.onProgress;c&&!q(t.highWaterMark)&&c(n,e,g,v),(x=this.callbacks)==null||x.onSuccess(o,n,e,v)}).catch(g=>{var y;if(self.clearTimeout(this.requestTimeout),n.aborted)return;const x=g&&g.code||0,v=g?g.message:null;(y=this.callbacks)==null||y.onError({code:x,text:v},e,g?g.details:null,n)})}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,s,n=0,a){const h=new Gd,l=e.body.getReader(),u=()=>l.read().then(d=>{if(d.done)return h.dataLength&&a(t,s,h.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const p=d.value,g=p.length;return t.loaded+=g,g<n||h.dataLength?(h.push(p),h.dataLength>=n&&a(t,s,h.flush().buffer,e)):a(t,s,p.buffer,e),u()}).catch(()=>Promise.reject());return u()}}function iS(r,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(Ee({},r.headers))};return r.rangeEnd&&t.headers.set("Range","bytes="+r.rangeStart+"-"+String(r.rangeEnd-1)),t}function sS(r){const e=tS.exec(r);if(e)return parseInt(e[2])-parseInt(e[1])+1}function nS(r){const e=r.get("Content-Range");if(e){const s=sS(e);if(q(s))return s}const t=r.get("Content-Length");if(t)return parseInt(t)}function rS(r,e){return new self.Request(r.url,e)}class aS extends Error{constructor(e,t,s){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=s}}const oS=/^age:\s*[\d.]+\s*$/im;class Du{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new Lo,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,s){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=s,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const s=this.loader=new self.XMLHttpRequest,n=this.stats;n.loading.first=0,n.loaded=0,n.aborted=!1;const a=this.xhrSetup;a?Promise.resolve().then(()=>{if(!(this.loader!==s||this.stats.aborted))return a(s,t.url)}).catch(h=>{if(!(this.loader!==s||this.stats.aborted))return s.open("GET",t.url,!0),a(s,t.url)}).then(()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,t,e)}).catch(h=>{var l;(l=this.callbacks)==null||l.onError({code:s.status,text:h.message},t,s,n)}):this.openAndSendXhr(s,t,e)}openAndSendXhr(e,t,s){e.readyState||e.open("GET",t.url,!0);const n=t.headers,{maxTimeToFirstByteMs:a,maxLoadTimeMs:h}=s.loadPolicy;if(n)for(const l in n)e.setRequestHeader(l,n[l]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),s.timeout=a&&q(a)?a:h,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:s}=this;if(!e||!t)return;const n=t.readyState,a=this.config;if(!s.aborted&&n>=2&&(s.loading.first===0&&(s.loading.first=Math.max(self.performance.now(),s.loading.start),a.timeout!==a.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),a.timeout=a.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),a.loadPolicy.maxLoadTimeMs-(s.loading.first-s.loading.start)))),n===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const d=t.status,p=t.responseType==="text"?t.responseText:null;if(d>=200&&d<300){const v=p??t.response;if(v!=null){var h,l;s.loading.end=Math.max(self.performance.now(),s.loading.first);const _=t.responseType==="arraybuffer"?v.byteLength:v.length;s.loaded=s.total=_,s.bwEstimate=s.total*8e3/(s.loading.end-s.loading.first);const o=(h=this.callbacks)==null?void 0:h.onProgress;o&&o(s,e,v,t);const c={url:t.responseURL,data:v,code:d};(l=this.callbacks)==null||l.onSuccess(c,s,e,t);return}}const g=a.loadPolicy.errorRetry,y=s.retry,x={url:e.url,data:void 0,code:d};if(tr(g,y,!1,x))this.retry(g);else{var u;_e.error(`${d} while loading ${e.url}`),(u=this.callbacks)==null||u.onError({code:d,text:t.statusText},e,t,s)}}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(tr(e,t,!0))this.retry(e);else{var s;_e.warn(`timeout while loading ${(s=this.context)==null?void 0:s.url}`);const n=this.callbacks;n&&(this.abortInternal(),n.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:s}=this;this.retryDelay=Do(e,s.retry),s.retry++,_e.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t==null?void 0:t.url}, retrying ${s.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&oS.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}const lS={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},hS=xe(xe({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:Du,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:_m,bufferController:dv,capLevelController:Yo,errorController:Im,fpsController:ux,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:Cd,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:lS},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},cS()),{},{subtitleStreamController:bx,subtitleTrackController:gx,timelineController:Xx,audioStreamController:ov,audioTrackController:lv,emeController:cs,cmcdController:lx,contentSteeringController:cx,interstitialsController:Tx});function cS(){return{cueHandler:Jx,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function dS(r,e,t){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const s=no(r),n=["manifest","level","frag"],a=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return n.forEach(h=>{const l=`${h==="level"?"playlist":h}LoadPolicy`,u=e[l]===void 0,d=[];a.forEach(p=>{const g=`${h}Loading${p}`,y=e[g];if(y!==void 0&&u){d.push(g);const x=s[l].default;switch(e[l]={default:x},p){case"TimeOut":x.maxLoadTimeMs=y,x.maxTimeToFirstByteMs=y;break;case"MaxRetry":x.errorRetry.maxNumRetry=y,x.timeoutRetry.maxNumRetry=y;break;case"RetryDelay":x.errorRetry.retryDelayMs=y,x.timeoutRetry.retryDelayMs=y;break;case"MaxRetryTimeout":x.errorRetry.maxRetryDelayMs=y,x.timeoutRetry.maxRetryDelayMs=y;break}}}),d.length&&t.warn(`hls.js config: "${d.join('", "')}" setting(s) are deprecated, use "${l}": ${be(e[l])}`)}),xe(xe({},s),e)}function no(r){return r&&typeof r=="object"?Array.isArray(r)?r.map(no):Object.keys(r).reduce((e,t)=>(e[t]=no(r[t]),e),{}):r}function uS(r,e){const t=r.loader;t!==Wh&&t!==Du?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),r.progressive=!1):eS()&&(r.loader=Wh,r.progressive=!0,r.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}const Gn=2,fS=.1,pS=.05,gS=100;class mS extends Ad{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var s;(s=this.media)!=null&&s.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var s;this.ended=((s=this.media)==null?void 0:s.currentTime)||1,this.hls.trigger(E.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(gS),this.mediaSource=t.mediaSource;const s=this.media=t.media;Je(s,"playing",this.onMediaPlaying),Je(s,"waiting",this.onMediaWaiting),Je(s,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:s}=this;s&&(it(s,"playing",this.onMediaPlaying),it(s,"waiting",this.onMediaWaiting),it(s,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;const t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var s,n;const a=(s=this.hls)==null?void 0:s.config;if(!a)return;const h=this.media;if(!h)return;const{seeking:l}=h,u=this.seeking&&!l,d=!this.seeking&&l,p=h.paused&&!l||h.ended||h.playbackRate===0;if(this.seeking=l,e!==t){t&&(this.ended=0),this.moved=!0,l||(this.nudgeRetry=0,a.nudgeOnVideoHole&&!p&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(d||u){u&&this.stallResolved(e);return}if(p){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&h.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(E.MEDIA_ENDED,{stalled:!1}));return}if(!ae.getBuffered(h).length){this.nudgeRetry=0;return}const g=ae.bufferInfo(h,e,0),y=g.nextStart||0,x=this.fragmentTracker;if(l&&x&&this.hls){const b=jh(this.hls.inFlightFragments,e),A=g.len>Gn,I=!y||b||y-e>Gn&&!x.getPartialFragment(e);if(A||I)return;this.moved=!1}const v=(n=this.hls)==null?void 0:n.latestLevelDetails;if(!this.moved&&this.stalled!==null&&x){if(!(g.len>0)&&!y)return;const A=Math.max(y,g.start||0)-e,L=!!(v!=null&&v.live)?v.targetduration*2:Gn,w=In(e,x);if(A>0&&(A<=L||w)){h.paused||this._trySkipBufferHole(w);return}}const _=a.detectStallWithCurrentTimeMs,o=self.performance.now(),c=this.waiting;let f=this.stalled;if(f===null)if(c>0&&o-c<_)f=this.stalled=c;else{this.stalled=o;return}const m=o-f;if(!l&&(m>=_||c)&&this.hls){var S;if(((S=this.mediaSource)==null?void 0:S.readyState)==="ended"&&!(v!=null&&v.live)&&Math.abs(e-((v==null?void 0:v.edge)||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(E.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(g),!this.media||!this.hls)return}const T=ae.bufferInfo(h,e,a.maxBufferHole);this._tryFixBufferStall(T,m,e)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const s=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(s)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(E.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var s;const n=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(s=this.buffered.audio)!=null&&s.length&&n&&n.length>1&&e>n.end(0)){const a=ae.bufferedInfo(ae.timeRangesToArray(this.buffered.audio),e,0);if(a.len>1&&t>=a.start){const h=ae.timeRangesToArray(n),l=ae.bufferedInfo(h,t,0).bufferedIndex;if(l>-1&&l<h.length-1){const u=ae.bufferedInfo(h,e,0).bufferedIndex,d=h[l].end,p=h[l+1].start;if((u===-1||u>l)&&p-d<1&&e-d<2){const g=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${d} -> ${p} buffered index: ${u}`);this.warn(g.message),this.media.currentTime+=1e-6;let y=In(e,this.fragmentTracker);y&&"fragment"in y?y=y.fragment:y||(y=void 0);const x=ae.bufferInfo(this.media,e,0);this.hls.trigger(E.ERROR,{type:Z.MEDIA_ERROR,details:D.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:g,reason:g.message,frag:y,buffer:x.len,bufferInfo:x})}}}}}_tryFixBufferStall(e,t,s){var n,a;const{fragmentTracker:h,media:l}=this,u=(n=this.hls)==null?void 0:n.config;if(!l||!h||!u)return;const d=(a=this.hls)==null?void 0:a.latestLevelDetails,p=In(s,h);if((p||d!=null&&d.live&&s<d.fragmentStart)&&(this._trySkipBufferHole(p)||!this.media))return;const g=e.buffered,y=this.adjacentTraversal(e,s);(g&&g.length>1&&e.len>u.maxBufferHole||e.nextStart&&(e.nextStart-s<u.maxBufferHole||y))&&(t>u.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){const s=this.fragmentTracker,n=e.nextStart;if(s&&n){const a=s.getFragAtPos(t,X.MAIN),h=s.getFragAtPos(n,X.MAIN);if(a&&h)return h.sn-a.sn<2}return!1}_reportStall(e){const{hls:t,media:s,stallReported:n,stalled:a}=this;if(!n&&a!==null&&s&&t){this.stallReported=!0;const h=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${be(e)})`);this.warn(h.message),t.trigger(E.ERROR,{type:Z.MEDIA_ERROR,details:D.BUFFER_STALLED_ERROR,fatal:!1,error:h,buffer:e.len,bufferInfo:e,stalled:{start:a}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:s,media:n}=this,a=(t=this.hls)==null?void 0:t.config;if(!n||!s||!a)return 0;const h=n.currentTime,l=ae.bufferInfo(n,h,0),u=h<l.start?l.start:l.nextStart;if(u&&this.hls){const p=l.len<=a.maxBufferHole,g=l.len>0&&l.len<1&&n.readyState<3,y=u-h;if(y>0&&(p||g)){if(y>a.maxBufferHole){let v=!1;if(h===0){const _=s.getAppendedFrag(0,X.MAIN);_&&u<_.end&&(v=!0)}if(!v&&e){var d;if(!((d=this.hls.loadLevelObj)!=null&&d.details)||jh(this.hls.inFlightFragments,u))return 0;let o=!1,c=e.end;for(;c<u;){const f=In(c,s);if(f)c+=f.duration;else{o=!0;break}}if(o)return 0}}const x=Math.max(u+pS,h+fS);if(this.warn(`skipping hole, adjusting currentTime from ${h} to ${x}`),this.moved=!0,n.currentTime=x,!(e!=null&&e.gap)){const v=new Error(`fragment loaded with buffer holes, seeking from ${h} to ${x}`),_={type:Z.MEDIA_ERROR,details:D.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:v,reason:v.message,buffer:l.len,bufferInfo:l};e&&("fragment"in e?_.part=e:_.frag=e),this.hls.trigger(E.ERROR,_)}return x}}return 0}_tryNudgeBuffer(e){const{hls:t,media:s,nudgeRetry:n}=this,a=t==null?void 0:t.config;if(!s||!a)return 0;const h=s.currentTime;if(this.nudgeRetry++,n<a.nudgeMaxRetry){const l=h+(n+1)*a.nudgeOffset,u=new Error(`Nudging 'currentTime' from ${h} to ${l}`);this.warn(u.message),s.currentTime=l,t.trigger(E.ERROR,{type:Z.MEDIA_ERROR,details:D.BUFFER_NUDGE_ON_STALL,error:u,fatal:!1,buffer:e.len,bufferInfo:e})}else{const l=new Error(`Playhead still not moving while enough data buffered @${h} after ${a.nudgeMaxRetry} nudges`);this.error(l.message),t.trigger(E.ERROR,{type:Z.MEDIA_ERROR,details:D.BUFFER_STALLED_ERROR,error:l,fatal:!0,buffer:e.len,bufferInfo:e})}}}function jh(r,e){const t=qh(r.main);if(t&&t.start<=e)return t;const s=qh(r.audio);return s&&s.start<=e?s:null}function qh(r){if(!r)return null;switch(r.state){case F.IDLE:case F.STOPPED:case F.ENDED:case F.ERROR:return null}return r.frag}function In(r,e){return e.getAppendedFrag(r,X.MAIN)||e.getPartialFragment(r)}const yS=.25;function ro(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function Ta(r,e,t,s,n){let a=new r(e,t,"");try{a.value=s,n&&(a.type=n)}catch{a=new r(e,t,be(n?xe({type:n},s):s))}return a}const wn=(()=>{const r=ro();try{r&&new r(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class vS{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(E.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:e}=this;e&&(e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(E.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(E.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){var s;this.media=t.media,((s=t.overrides)==null?void 0:s.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){var e;const t=(e=this.hls)==null?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&(this.removeCues&&ss(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){const s=e[t];if(s.kind==="metadata"&&s.label==="id3")return Su(s,this.media),s}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:s,enableID3MetadataCues:n}=this.hls.config;if(!s&&!n)return;const{samples:a}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const h=ro();if(h)for(let l=0;l<a.length;l++){const u=a[l].type;if(u===ct.emsg&&!s||!n)continue;const d=jd(a[l].data),p=a[l].pts;let g=p+a[l].duration;g>wn&&(g=wn),g-p<=0&&(g=p+yS);for(let x=0;x<d.length;x++){const v=d[x];if(!qd(v)){this.updateId3CueEnds(p,u);const _=Ta(h,p,g,v,u);_&&this.id3Track.addCue(_)}}}}updateId3CueEnds(e,t){var s;const n=(s=this.id3Track)==null?void 0:s.cues;if(n)for(let a=n.length;a--;){const h=n[a];h.type===t&&h.startTime<e&&h.endTime===wn&&(h.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:s,type:n}){const{id3Track:a,hls:h}=this;if(!h)return;const{config:{enableEmsgMetadataCues:l,enableID3MetadataCues:u}}=h;if(a&&(l||u)){let d;n==="audio"?d=p=>p.type===ct.audioId3&&u:n==="video"?d=p=>p.type===ct.emsg&&l:d=p=>p.type===ct.audioId3&&u||p.type===ct.emsg&&l,io(a,t,s,d)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;const{assetPlayerId:s,timelineOffset:n,enableDateRangeMetadataCues:a,interstitialsController:h}=this.hls.config;if(!a)return;const l=ro();if(s&&n&&!h){const{fragmentStart:_,fragmentEnd:o}=e;let c=this.assetCue;c?(c.startTime=_,c.endTime=o):l&&(c=this.assetCue=Ta(l,_,o,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),c&&(c.id=s,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(c),c.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:u}=this,{dateRanges:d}=e,p=Object.keys(d);let g=this.dateRangeCuesAppended;if(u&&t){var y;if((y=u.cues)!=null&&y.length){const _=Object.keys(g).filter(o=>!p.includes(o));for(let o=_.length;o--;){var x;const c=_[o],f=(x=g[c])==null?void 0:x.cues;delete g[c],f&&Object.keys(f).forEach(m=>{const S=f[m];if(S){S.removeEventListener("enter",this.onEventCueEnter);try{u.removeCue(S)}catch{}}})}}else g=this.dateRangeCuesAppended={}}const v=e.fragments[e.fragments.length-1];if(!(p.length===0||!q(v==null?void 0:v.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let _=0;_<p.length;_++){const o=p[_],c=d[o],f=c.startTime,m=g[o],S=(m==null?void 0:m.cues)||{};let T=(m==null?void 0:m.durationKnown)||!1,b=wn;const{duration:A,endDate:I}=c;if(I&&A!==null)b=f+A,T=!0;else if(c.endOnNext&&!T){const w=p.reduce((R,M)=>{if(M!==c.id){const k=d[M];if(k.class===c.class&&k.startDate>c.startDate&&(!R||c.startDate<R.startDate))return k}return R},null);w&&(b=w.startTime,T=!0)}const L=Object.keys(c.attr);for(let w=0;w<L.length;w++){const R=L[w];if(!Nm(R))continue;const M=S[R];if(M)T&&!(m!=null&&m.durationKnown)?M.endTime=b:Math.abs(M.startTime-f)>.01&&(M.startTime=f,M.endTime=b);else if(l){let k=c.attr[R];$m(R)&&(k=rd(k));const O=Ta(l,f,b,{key:R,data:k},ct.dateRange);O&&(O.id=o,this.id3Track.addCue(O),S[R]=O,h&&(R==="X-ASSET-LIST"||R==="X-ASSET-URL")&&O.addEventListener("enter",this.onEventCueEnter))}}g[o]={cues:S,dateRange:c,durationKnown:T}}}}}class xS{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:t}=this,s=this.levelDetails;if(!t||!s)return;this.currentTime=t.currentTime;const n=this.computeLatency();if(n===null)return;this._latency=n;const{lowLatencyMode:a,maxLiveSyncPlaybackRate:h}=this.config;if(!a||h===1||!s.live)return;const l=this.targetLatency;if(l===null)return;const u=n-l,d=Math.min(this.maxLatency,l+s.targetduration);if(u<d&&u>.05&&this.forwardBufferLength>1){const g=Math.min(2,Math.max(1,h)),y=Math.round(2/(1+Math.exp(-.75*u-this.edgeStalled))*20)/20,x=Math.min(g,Math.max(1,y));this.changeMediaPlaybackRate(t,x)}else t.playbackRate!==1&&t.playbackRate!==0&&this.changeMediaPlaybackRate(t,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;const t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const e=this.levelDetails;if(e===null||this.hls===null)return null;const{holdBack:t,partHoldBack:s,targetduration:n}=e,{liveSyncDuration:a,liveSyncDurationCount:h,lowLatencyMode:l}=this.config,u=this.hls.userConfig;let d=l&&s||t;(this._targetLatencyUpdated||u.liveSyncDuration||u.liveSyncDurationCount||d===0)&&(d=a!==void 0?a:h*n);const p=n;return d+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,p)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null)return null;const s=this.levelDetails;if(s===null)return null;const n=s.edge,a=e-t-this.edgeStalled,h=n-s.totalduration,l=n-(this.config.lowLatencyMode&&s.partTarget||s.targetduration);return Math.min(Math.max(h,a),l)}get drift(){const e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(e===null)return 0;const t=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;const s=e.buffered.length;return(s?e.buffered.end(s-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(E.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(E.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var s;t.details===D.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(s=this.levelDetails)!=null&&s.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var s,n;e.playbackRate!==t&&((s=this.hls)==null||s.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(n=this.targetLatency)==null?void 0:n.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){const e=this.levelDetails;return e===null?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}}class SS extends Ko{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this),e.on(E.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this),e.off(E.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const s=this.hls.config.preferManagedMediaSource,n=[],a={},h={};let l=!1,u=!1,d=!1;t.levels.forEach(p=>{const g=p.attrs;let{audioCodec:y,videoCodec:x}=p;y&&(p.audioCodec=y=Qn(y,s)||void 0),x&&(x=p.videoCodec=im(x));const{width:v,height:_,unknownCodecs:o}=p,c=(o==null?void 0:o.length)||0;if(l||(l=!!(v&&_)),u||(u=!!x),d||(d=!!y),c||y&&!this.isAudioSupported(y)||x&&!this.isVideoSupported(x)){this.log(`Some or all CODECS not supported "${g.CODECS}"`);return}const{CODECS:f,"FRAME-RATE":m,"HDCP-LEVEL":S,"PATHWAY-ID":T,RESOLUTION:b,"VIDEO-RANGE":A}=g,L=`${`${T||"."}-`}${p.bitrate}-${b}-${m}-${f}-${A}-${S}`;if(a[L])if(a[L].uri!==p.url&&!p.attrs["PATHWAY-ID"]){const w=h[L]+=1;p.attrs["PATHWAY-ID"]=new Array(w+1).join(".");const R=this.createLevel(p);a[L]=R,n.push(R)}else a[L].addGroupId("audio",g.AUDIO),a[L].addGroupId("text",g.SUBTITLES);else{const w=this.createLevel(p);a[L]=w,h[L]=1,n.push(w)}}),this.filterAndSortMediaOptions(n,t,l,u,d)}createLevel(e){const t=new Hs(e),s=e.supplemental;if(s!=null&&s.videoCodec&&!this.isVideoSupported(s.videoCodec)){const n=new Error(`SUPPLEMENTAL-CODECS not supported "${s.videoCodec}"`);this.log(n.message),t.supportedResult=yd(n,[])}return t}isAudioSupported(e){return Gs(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return Gs(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,s,n,a){var h;let l=[],u=[],d=e;const p=((h=t.stats)==null?void 0:h.parsing)||{};if((s||n)&&a&&(d=d.filter(({videoCodec:f,videoRange:m,width:S,height:T})=>(!!f||!!(S&&T))&&um(m))),d.length===0){Promise.resolve().then(()=>{if(this.hls){let f="no level with compatible codecs found in manifest",m=f;t.levels.length&&(m=`one or more CODECS in variant not supported: ${be(t.levels.map(T=>T.attrs.CODECS).filter((T,b,A)=>A.indexOf(T)===b))}`,this.warn(m),f+=` (${m})`);const S=new Error(f);this.hls.trigger(E.ERROR,{type:Z.MEDIA_ERROR,details:D.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:S,reason:m})}}),p.end=performance.now();return}t.audioTracks&&(l=t.audioTracks.filter(f=>!f.audioCodec||this.isAudioSupported(f.audioCodec)),Xh(l)),t.subtitles&&(u=t.subtitles,Xh(u));const g=d.slice(0);d.sort((f,m)=>{if(f.attrs["HDCP-LEVEL"]!==m.attrs["HDCP-LEVEL"])return(f.attrs["HDCP-LEVEL"]||"")>(m.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&f.height!==m.height)return f.height-m.height;if(f.frameRate!==m.frameRate)return f.frameRate-m.frameRate;if(f.videoRange!==m.videoRange)return Zn.indexOf(f.videoRange)-Zn.indexOf(m.videoRange);if(f.videoCodec!==m.videoCodec){const S=Gl(f.videoCodec),T=Gl(m.videoCodec);if(S!==T)return T-S}if(f.uri===m.uri&&f.codecSet!==m.codecSet){const S=Xn(f.codecSet),T=Xn(m.codecSet);if(S!==T)return T-S}return f.averageBitrate!==m.averageBitrate?f.averageBitrate-m.averageBitrate:0});let y=g[0];if(this.steering&&(d=this.steering.filterParsedLevels(d),d.length!==g.length)){for(let f=0;f<g.length;f++)if(g[f].pathwayId===d[0].pathwayId){y=g[f];break}}this._levels=d;for(let f=0;f<d.length;f++)if(d[f]===y){var x;this._firstLevel=f;const m=y.bitrate,S=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${d.length} level(s) found, first bitrate: ${m}`),((x=this.hls.userConfig)==null?void 0:x.abrEwmaDefaultEstimate)===void 0){const T=Math.min(m,this.hls.config.abrEwmaDefaultEstimateMax);T>S&&S===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=T)}break}const v=a&&!n,_=this.hls.config,o=!!(_.audioStreamController&&_.audioTrackController),c={levels:d,audioTracks:l,subtitleTracks:u,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:a,video:n,altAudio:o&&!v&&l.some(f=>!!f.url)};p.end=performance.now(),this.hls.trigger(E.MANIFEST_PARSED,c)}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){const p=new Error("invalid level idx"),g=e<0;if(this.hls.trigger(E.ERROR,{type:Z.OTHER_ERROR,details:D.LEVEL_SWITCH_ERROR,level:e,fatal:g,error:p,reason:p.message}),g)return;e=Math.min(e,t.length-1)}const s=this.currentLevelIndex,n=this.currentLevel,a=n?n.attrs["PATHWAY-ID"]:void 0,h=t[e],l=h.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=h,s===e&&n&&a===l)return;this.log(`Switching to level ${e} (${h.height?h.height+"p ":""}${h.videoRange?h.videoRange+" ":""}${h.codecSet?h.codecSet+" ":""}@${h.bitrate})${l?" with Pathway "+l:""} from level ${s}${a?" with Pathway "+a:""}`);const u={level:e,attrs:h.attrs,details:h.details,bitrate:h.bitrate,averageBitrate:h.averageBitrate,maxBitrate:h.maxBitrate,realBitrate:h.realBitrate,width:h.width,height:h.height,codecSet:h.codecSet,audioCodec:h.audioCodec,videoCodec:h.videoCodec,audioGroups:h.audioGroups,subtitleGroups:h.subtitleGroups,loaded:h.loaded,loadError:h.loadError,fragmentError:h.fragmentError,name:h.name,id:h.id,uri:h.uri,url:h.url,urlId:0,audioGroupIds:h.audioGroupIds,textGroupIds:h.textGroupIds};this.hls.trigger(E.LEVEL_SWITCHING,u);const d=h.details;if(!d||d.live){const p=this.switchParams(h.uri,n==null?void 0:n.details,d);this.loadPlaylist(p)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){const e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){const t=this.steering.pathways(),s=e.filter(n=>t.indexOf(n)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=s}}onError(e,t){t.fatal||!t.context||t.context.type===fe.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===X.MAIN){const s=t.elementaryStreams;if(!Object.keys(s).some(a=>!!s[a]))return;const n=this._levels[t.level];n!=null&&n.loadError&&(this.log(`Resetting level error count of ${n.loadError} on frag buffered`),n.loadError=0)}}onLevelLoaded(e,t){var s;const{level:n,details:a}=t,h=t.levelInfo;if(!h){var l;this.warn(`Invalid level index ${n}`),(l=t.deliveryDirectives)!=null&&l.skip&&(a.deltaUpdateFailed=!0);return}if(h===this.currentLevel||t.withoutMultiVariant){h.fragmentError===0&&(h.loadError=0);let u=h.details;u===t.details&&u.advanced&&(u=void 0),this.playlistLoaded(n,t,u)}else(s=t.deliveryDirectives)!=null&&s.skip&&(a.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=this.getUrlWithDirectives(e.uri,t),n=this.currentLevelIndex,a=e.attrs["PATHWAY-ID"],h=e.details,l=h==null?void 0:h.age;this.log(`Loading level index ${n}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${a?" Pathway "+a:""}${l&&h.live?" age "+l.toFixed(1)+(h.type&&" "+h.type||""):""} ${s}`),this.hls.trigger(E.LEVEL_LOADING,{url:s,level:n,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(this._levels.length===1)return;const s=this._levels.filter((a,h)=>h!==e?!0:(this.steering&&this.steering.removeLevel(a),a===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,a.details&&a.details.fragments.forEach(l=>l.level=-1)),!1));Bd(s),this._levels=s,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const n=s.length-1;this._firstLevel=Math.min(this._firstLevel,n),this._startLevel&&(this._startLevel=Math.min(this._startLevel,n)),this.hls.trigger(E.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:s}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(E.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}}function Xh(r){const e={};r.forEach(t=>{const s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++})}function ku(){return self.SourceBuffer||self.WebKitSourceBuffer}function Mu(){if(!Si())return!1;const e=ku();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function _S(){if(!Mu())return!1;const r=Si();return typeof(r==null?void 0:r.isTypeSupported)=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>r.isTypeSupported(zs(e,"video")))||["mp4a.40.2","fLaC"].some(e=>r.isTypeSupported(zs(e,"audio"))))}function ES(){var r;const e=ku();return typeof(e==null||(r=e.prototype)==null?void 0:r.changeType)=="function"}const TS=100;class bS extends Oo{constructor(e,t,s){super(e,t,s,"stream-controller",X.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const n=this.media,a=n?n.currentTime:null;if(a===null||!q(a)||(this.log(`Media seeked to ${a.toFixed(3)}`),!this.getBufferedFrag(a)))return;const h=this.getFwdBufferInfoAtPos(n,a,X.MAIN,0);if(h===null||h.len===0){this.warn(`Main forward buffer length at ${a} on "seeked" event ${h?h.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.LEVEL_LOADING,this.onLevelLoading,this),e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(E.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(E.BUFFER_CREATED,this.onBufferCreated,this),e.on(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(E.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(E.BUFFER_CREATED,this.onBufferCreated,this),e.off(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){const{lastCurrentTime:s,hls:n}=this;if(this.stopLoad(),this.setInterval(TS),this.level=-1,!this.startFragRequested){let a=n.startLevel;a===-1&&(n.config.testBandwidth&&this.levels.length>1?(a=0,this.bitrateTest=!0):a=n.firstAutoLevel),n.nextLoadLevel=a,this.level=n.loadLevel,this._hasEnoughToStart=!!t}s>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s),this.state=F.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=F.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case F.WAITING_LEVEL:{const{levels:e,level:t}=this,s=e==null?void 0:e[t],n=s==null?void 0:s.details;if(n&&(!n.live||this.levelLastLoaded===s&&!this.waitForLive(s))){if(this.waitForCdnTuneIn(n))break;this.state=F.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=F.IDLE;break}break}case F.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===F.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:s,media:n}=this;if(t===null||!n&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const a=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(s!=null&&s[a]))return;const h=s[a],l=this.getMainFwdBufferInfo();if(l===null)return;const u=this.getLevelDetails();if(u&&this._streamEnded(l,u)){const _={};this.altAudio===2&&(_.type="video"),this.hls.trigger(E.BUFFER_EOS,_),this.state=F.ENDED;return}if(!this.buffering)return;e.loadLevel!==a&&e.manualLevel===-1&&this.log(`Adapting to level ${a} from level ${this.level}`),this.level=e.nextLoadLevel=a;const d=h.details;if(!d||this.state===F.WAITING_LEVEL||this.waitForLive(h)){this.level=a,this.state=F.WAITING_LEVEL,this.startFragRequested=!1;return}const p=l.len,g=this.getMaxBufferLength(h.maxBitrate);if(p>=g)return;this.backtrackFragment&&this.backtrackFragment.start>l.end&&(this.backtrackFragment=null);const y=this.backtrackFragment?this.backtrackFragment.start:l.end;let x=this.getNextFragment(y,d);if(this.couldBacktrack&&!this.fragPrevious&&x&&Pe(x)&&this.fragmentTracker.getState(x)!==Fe.OK){var v;const o=((v=this.backtrackFragment)!=null?v:x).sn-d.startSN,c=d.fragments[o-1];c&&x.cc===c.cc&&(x=c,this.fragmentTracker.removeFragment(c))}else this.backtrackFragment&&l.len&&(this.backtrackFragment=null);if(x&&this.isLoopLoading(x,y)){if(!x.gap){const o=this.audioOnly&&!this.altAudio?Te.AUDIO:Te.VIDEO,c=(o===Te.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;c&&this.afterBufferFlushed(c,o,X.MAIN)}x=this.getNextFragmentLoopLoading(x,d,l,X.MAIN,g)}x&&(x.initSegment&&!x.initSegment.data&&!this.bitrateTest&&(x=x.initSegment),this.loadFragment(x,h,y))}loadFragment(e,t,s){const n=this.fragmentTracker.getState(e);n===Fe.NOT_LOADED||n===Fe.PARTIAL?Pe(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,s):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,X.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(t!=null&&t.readyState){let s;const n=this.getAppendedFrag(t.currentTime);n&&n.start>1&&this.flushMainBuffer(0,n.start-1);const a=this.getLevelDetails();if(a!=null&&a.live){const l=this.getMainFwdBufferInfo();if(!l||l.len<a.targetduration*2)return}if(!t.paused&&e){const l=this.hls.nextLoadLevel,u=e[l],d=this.fragLastKbps;d&&this.fragCurrent?s=this.fragCurrent.duration*u.maxBitrate/(1e3*d)+1:s=0}else s=0;const h=this.getBufferedFrag(t.currentTime+s);if(h){const l=this.followingBufferedFrag(h);if(l){this.abortCurrentFrag();const u=l.maxStartPTS?l.maxStartPTS:l.start,d=l.duration,p=Math.max(h.end,u+Math.min(Math.max(d-this.config.maxFragLookUpTolerance,d*(this.couldBacktrack?.5:.125)),d*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(p,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case F.KEY_LOADING:case F.FRAG_LOADING:case F.FRAG_LOADING_WAITING_RETRY:case F.PARSING:case F.PARSED:this.state=F.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio===2?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const s=t.media;Je(s,"playing",this.onMediaPlaying),Je(s,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:s}=this;s&&(it(s,"playing",this.onMediaPlaying),it(s,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t),!t.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(E.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let s=!1,n=!1;for(let a=0;a<t.levels.length;a++){const h=t.levels[a].audioCodec;h&&(s=s||h.indexOf("mp4a.40.2")!==-1,n=n||h.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=s&&n&&!ES(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:s}=this;if(!s||this.state!==F.IDLE)return;const n=t.levelInfo;(!n.details||n.details.live&&(this.levelLastLoaded!==n||n.details.expired)||this.waitForCdnTuneIn(n.details))&&(this.state=F.WAITING_LEVEL)}onLevelLoaded(e,t){var s;const{levels:n,startFragRequested:a}=this,h=t.level,l=t.details,u=l.totalduration;if(!n){this.warn(`Levels were reset while loading level ${h}`);return}this.log(`Level ${h} loaded [${l.startSN},${l.endSN}]${l.lastPartSn?`[part-${l.lastPartSn}-${l.lastPartIndex}]`:""}, cc [${l.startCC}, ${l.endCC}] duration:${u}`);const d=t.levelInfo,p=this.fragCurrent;p&&(this.state===F.FRAG_LOADING||this.state===F.FRAG_LOADING_WAITING_RETRY)&&p.level!==t.level&&p.loader&&this.abortCurrentFrag();let g=0;if(l.live||(s=d.details)!=null&&s.live){var y;if(this.checkLiveUpdate(l),l.deltaUpdateFailed)return;g=this.alignPlaylists(l,d.details,(y=this.levelLastLoaded)==null?void 0:y.details)}if(d.details=l,this.levelLastLoaded=d,a||this.setStartPosition(l,g),this.hls.trigger(E.LEVEL_UPDATED,{details:l,level:h}),this.state===F.WAITING_LEVEL){if(this.waitForCdnTuneIn(l))return;this.state=F.IDLE}a&&l.live&&this.synchronizeToLiveEdge(l),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:s}=this;if(!s)return;const n=this.hls.liveSyncPosition,a=this.getLoadPosition(),h=e.fragmentStart,l=e.edge,u=a>=h-t.maxFragLookUpTolerance&&a<=l;if(n!==null&&s.duration>n&&(a<n||!u)){const p=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!u&&s.readyState<4||a<l-p)&&(this._hasEnoughToStart||(this.nextLoadPosition=n),s.readyState))if(this.warn(`Playback: ${a.toFixed(3)} is located too far from the end of live sliding playlist: ${l}, reset currentTime to : ${n.toFixed(3)}`),this.config.liveSyncMode==="buffered"){var d;const g=ae.bufferInfo(s,n,0);if(!((d=g.buffered)!=null&&d.length)){s.currentTime=n;return}if(g.start<=a){s.currentTime=n;return}const{nextStart:x}=ae.bufferedInfo(g.buffered,a,0);x&&(s.currentTime=x)}else s.currentTime=n}}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:n,payload:a}=e,{levels:h}=this;if(!h){this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}const l=h[s.level];if(!l){this.warn(`Level ${s.level} not found on progress`);return}const u=l.details;if(!u){this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),this.fragmentTracker.removeFragment(s);return}const d=l.videoCodec,p=u.PTSKnown||!u.live,g=(t=s.initSegment)==null?void 0:t.data,y=this._getAudioCodec(l),x=this.transmuxer=this.transmuxer||new au(this.hls,X.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),v=n?n.index:-1,_=v!==-1,o=new Mo(s.level,s.sn,s.stats.chunkCount,a.byteLength,v,_),c=this.initPTS[s.cc];x.push(a,g,y,d,s,n,u.totalduration,p,o,c)}onAudioTrackSwitching(e,t){const s=this.hls,n=this.altAudio===2;if(Jn(t.url,s))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const h=this.fragCurrent;h&&(this.log("Switching to main audio track, cancel main fragment load"),h.abortRequests(),this.fragmentTracker.removeFragment(h)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(n){this.fragmentTracker.removeAllFragments(),s.once(E.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(E.AUDIO_TRACK_SWITCHED,t)}),s.trigger(E.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}s.trigger(E.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const s=Jn(t.url,this.hls);if(s){const n=this.videoBuffer;n&&this.mediaBuffer!==n&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=n)}this.altAudio=s?2:0,this.tick()}onBufferCreated(e,t){const s=t.tracks;let n,a,h=!1;for(const l in s){const u=s[l];if(u.id==="main"){if(a=l,n=u,l==="video"){const d=s[l];d&&(this.videoBuffer=d.buffer)}}else h=!0}h&&n?(this.log(`Alternate track found, use ${a}.buffered to schedule main fragment loading`),this.mediaBuffer=n.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:s,part:n}=t,a=s.type===X.MAIN;if(a){if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${n?" p: "+n.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),this.state===F.PARSED&&(this.state=F.IDLE);return}const l=n?n.stats:s.stats;this.fragLastKbps=Math.round(8*l.total/(l.buffering.end-l.loading.first)),Pe(s)&&(this.fragPrevious=s),this.fragBufferedComplete(s,n)}const h=this.media;h&&(!this._hasEnoughToStart&&ae.getBuffered(h).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),a&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var s;if(t.fatal){this.state=F.ERROR;return}switch(t.details){case D.FRAG_GAP:case D.FRAG_PARSING_ERROR:case D.FRAG_DECRYPT_ERROR:case D.FRAG_LOAD_ERROR:case D.FRAG_LOAD_TIMEOUT:case D.KEY_LOAD_ERROR:case D.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(X.MAIN,t);break;case D.LEVEL_LOAD_ERROR:case D.LEVEL_LOAD_TIMEOUT:case D.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===F.WAITING_LEVEL&&((s=t.context)==null?void 0:s.type)===fe.LEVEL&&(this.state=F.IDLE);break;case D.BUFFER_ADD_CODEC_ERROR:case D.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case D.BUFFER_FULL_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case D.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=F.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==Te.AUDIO||!this.altAudio){const s=(t===Te.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;s&&(this.afterBufferFlushed(s,t,X.MAIN),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let s=this.startPosition;if(s>=0&&t<s){if(e.seeking){this.log(`could not seek to ${s}, already seeking at ${t}`);return}const n=this.timelineOffset;n&&s&&(s+=n);const a=this.getLevelDetails(),h=ae.getBuffered(e),l=h.length?h.start(0):0,u=l-s,d=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||u>0&&(u<d||this.loadingParts&&u<2*((a==null?void 0:a.partTarget)||0)))&&(this.log(`adjusting start position by ${u} to match buffer start`),s+=u,this.startPosition=s),t<s&&(this.log(`seek to target start position ${s} from current time ${t} buffer start ${l}`),e.currentTime=s)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(s=>{const{hls:n}=this,a=s==null?void 0:s.frag;if(!a||this.fragContextChanged(a))return;t.fragmentError=0,this.state=F.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const h=a.stats;h.parsing.start=h.parsing.end=h.buffering.start=h.buffering.end=self.performance.now(),n.trigger(E.FRAG_LOADED,s),a.bitrateTest=!1}).catch(s=>{this.state===F.STOPPED||this.state===F.ERROR||(this.warn(s),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:s}=this,{remuxResult:n,chunkMeta:a}=e,h=this.getCurrentContext(a);if(!h){this.resetWhenMissingContext(a);return}const{frag:l,part:u,level:d}=h,{video:p,text:g,id3:y,initSegment:x}=n,{details:v}=d,_=this.altAudio?void 0:n.audio;if(this.fragContextChanged(l)){this.fragmentTracker.removeFragment(l);return}if(this.state=F.PARSING,x){const o=x.tracks;if(o){const S=l.initSegment||l;if(this.unhandledEncryptionError(x,l))return;this._bufferInitSegment(d,o,S,a),s.trigger(E.FRAG_PARSING_INIT_SEGMENT,{frag:S,id:t,tracks:o})}const c=x.initPTS,f=x.timescale,m=this.initPTS[l.cc];if(q(c)&&(!m||m.baseTime!==c||m.timescale!==f)){const S=x.trackId;this.initPTS[l.cc]={baseTime:c,timescale:f,trackId:S},s.trigger(E.INIT_PTS_FOUND,{frag:l,id:t,initPTS:c,timescale:f,trackId:S})}}if(p&&v){_&&p.type==="audiovideo"&&this.logMuxedErr(l);const o=v.fragments[l.sn-1-v.startSN],c=l.sn===v.startSN,f=!o||l.cc>o.cc;if(n.independent!==!1){const{startPTS:m,endPTS:S,startDTS:T,endDTS:b}=p;if(u)u.elementaryStreams[p.type]={startPTS:m,endPTS:S,startDTS:T,endDTS:b};else if(p.firstKeyFrame&&p.independent&&a.id===1&&!f&&(this.couldBacktrack=!0),p.dropped&&p.independent){const A=this.getMainFwdBufferInfo(),I=(A?A.end:this.getLoadPosition())+this.config.maxBufferHole,L=p.firstKeyFramePTS?p.firstKeyFramePTS:m;if(!c&&I<L-this.config.maxBufferHole&&!f){this.backtrack(l);return}else f&&(l.gap=!0);l.setElementaryStreamInfo(p.type,l.start,S,l.start,b,!0)}else c&&m-(v.appliedTimelineOffset||0)>Gn&&(l.gap=!0);l.setElementaryStreamInfo(p.type,m,S,T,b),this.backtrackFragment&&(this.backtrackFragment=l),this.bufferFragmentData(p,l,u,a,c||f)}else if(c||f)l.gap=!0;else{this.backtrack(l);return}}if(_){const{startPTS:o,endPTS:c,startDTS:f,endDTS:m}=_;u&&(u.elementaryStreams[Te.AUDIO]={startPTS:o,endPTS:c,startDTS:f,endDTS:m}),l.setElementaryStreamInfo(Te.AUDIO,o,c,f,m),this.bufferFragmentData(_,l,u,a)}if(v&&y!=null&&y.samples.length){const o={id:t,frag:l,details:v,samples:y.samples};s.trigger(E.FRAG_PARSING_METADATA,o)}if(v&&g){const o={id:t,frag:l,details:v,samples:g.samples};s.trigger(E.FRAG_PARSING_USERDATA,o)}}logMuxedErr(e){this.warn(`${Pe(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,s,n){if(this.state!==F.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(s));const{audio:a,video:h,audiovideo:l}=t;if(a){const d=e.audioCodec;let p=Mn(a.codec,d);p==="mp4a"&&(p="mp4a.40.5");const g=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){p&&(p.indexOf("mp4a.40.5")!==-1?p="mp4a.40.2":p="mp4a.40.5");const y=a.metadata;y&&"channelCount"in y&&(y.channelCount||1)!==1&&g.indexOf("firefox")===-1&&(p="mp4a.40.5")}p&&p.indexOf("mp4a.40.5")!==-1&&g.indexOf("android")!==-1&&a.container!=="audio/mpeg"&&(p="mp4a.40.2",this.log(`Android: force audio codec to ${p}`)),d&&d!==p&&this.log(`Swapping manifest audio codec "${d}" for "${p}"`),a.levelCodec=p,a.id=X.MAIN,this.log(`Init audio buffer, container:${a.container}, codecs[selected/level/parsed]=[${p||""}/${d||""}/${a.codec}]`),delete t.audiovideo}if(h){h.levelCodec=e.videoCodec,h.id=X.MAIN;const d=h.codec;if((d==null?void 0:d.length)===4)switch(d){case"hvc1":case"hev1":h.codec="hvc1.1.6.L120.90";break;case"av01":h.codec="av01.0.04M.08";break;case"avc1":h.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${h.container}, codecs[level/parsed]=[${e.videoCodec||""}/${d}]${h.codec!==d?" parsed-corrected="+h.codec:""}${h.supplemental?" supplemental="+h.supplemental:""}`),delete t.audiovideo}l&&(this.log(`Init audiovideo buffer, container:${l.container}, codecs[level/parsed]=[${e.codecs}/${l.codec}]`),delete t.video,delete t.audio);const u=Object.keys(t);if(u.length){if(this.hls.trigger(E.BUFFER_CODECS,t),!this.hls)return;u.forEach(d=>{const g=t[d].initSegment;g!=null&&g.byteLength&&this.hls.trigger(E.BUFFER_APPENDING,{type:d,data:g,frag:s,part:null,chunkMeta:n,parent:s.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,X.MAIN)}get maxBufferLength(){const{levels:e,level:t}=this,s=e==null?void 0:e[t];return s?this.getMaxBufferLength(s.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=F.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const s=e.currentTime;if(ae.isBuffered(e,s)?t=this.getAppendedFrag(s):ae.isBuffered(e,s+.1)&&(t=this.getAppendedFrag(s+.1)),t){this.backtrackFragment=null;const n=this.fragPlaying,a=t.level;(!n||t.sn!==n.sn||n.level!==a)&&(this.fragPlaying=t,this.hls.trigger(E.FRAG_CHANGED,{frag:t}),(!n||n.level!==a)&&this.hls.trigger(E.LEVEL_SWITCHED,{level:a}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;return q(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(q(t)){const s=this.getLevelDetails(),n=this.currentFrag||(s?zi(null,s.fragments,t):null);if(n){const a=n.programDateTime;if(a!==null){const h=a+(t-n.start)*1e3;return new Date(h)}}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class AS extends xt{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const s in this.keyIdToKeyInfo){const n=this.keyIdToKeyInfo[s].loader;if(n){var t;if(e&&e!==((t=n.context)==null?void 0:t.frag.type))return;n.abort()}}}detach(){for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,t=D.KEY_LOAD_ERROR,s,n,a){return new qt({type:Z.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:a,error:s,networkDetails:n})}loadClear(e,t,s){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let n=0,a=t.length;n<a;n++){const h=t[n];if(e.cc<=h.cc&&(!Pe(e)||!Pe(h)||e.sn<h.sn)||!s&&n==a-1)return this.emeController.selectKeySystemFormat(h).then(l=>{if(!this.emeController)return;h.setKeyFormat(l);const u=Un(l);if(u)return this.emeController.getKeySystemAccess([u])})}if(this.config.requireKeySystemAccessOnStart){const n=Rs(this.config);if(n.length)return this.emeController.getKeySystemAccess(n)}}return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var s,n;t&&e.setKeyFormat(t);const a=e.decryptdata;if(!a){const d=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,D.KEY_LOAD_ERROR,d))}const h=a.uri;if(!h)return Promise.reject(this.createKeyLoadError(e,D.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${h}"`)));const l=ba(a);let u=this.keyIdToKeyInfo[l];if((s=u)!=null&&s.decryptdata.key)return a.key=u.decryptdata.key,Promise.resolve({frag:e,keyInfo:u});if(this.emeController&&(n=u)!=null&&n.keyLoadPromise)switch(this.emeController.getKeyStatus(u.decryptdata)){case"usable":case"usable-in-future":return u.keyLoadPromise.then(p=>{const{keyInfo:g}=p;return a.key=g.decryptdata.key,{frag:e,keyInfo:g}})}switch(this.log(`${this.keyIdToKeyInfo[l]?"Rel":"L"}oading${a.keyId?" keyId: "+Ze(a.keyId):""} URI: ${a.uri} from ${e.type} ${e.level}`),u=this.keyIdToKeyInfo[l]={decryptdata:a,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},a.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return a.keyFormat==="identity"?this.loadKeyHTTP(u,e):this.loadKeyEME(u,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(u,e);default:return Promise.reject(this.createKeyLoadError(e,D.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${a.method}"`)))}}loadKeyEME(e,t){const s={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var n;if(!e.decryptdata.keyId&&(n=t.initSegment)!=null&&n.data){const h=V0(t.initSegment.data);if(h.length){const l=h[0];l.some(u=>u!==0)&&(this.log(`Using keyId found in init segment ${Ze(l)}`),e.decryptdata.keyId=l,Ni.setKeyIdForUri(e.decryptdata.uri,l))}}const a=this.emeController.loadKey(s);return(e.keyLoadPromise=a.then(h=>(e.mediaKeySessionContext=h,s))).catch(h=>{throw e.keyLoadPromise=null,"data"in h&&(h.data.frag=t),h})}return Promise.resolve(s)}loadKeyHTTP(e,t){const s=this.config,n=s.loader,a=new n(s);return t.keyLoader=e.loader=a,e.keyLoadPromise=new Promise((h,l)=>{const u={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},d=s.keyLoadPolicy.default,p={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},g={onSuccess:(y,x,v,_)=>{const{frag:o,keyInfo:c}=v,f=ba(c.decryptdata);if(!o.decryptdata||c!==this.keyIdToKeyInfo[f])return l(this.createKeyLoadError(o,D.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),_));c.decryptdata.key=o.decryptdata.key=new Uint8Array(y.data),o.keyLoader=null,c.loader=null,h({frag:o,keyInfo:c})},onError:(y,x,v,_)=>{this.resetLoader(x),l(this.createKeyLoadError(t,D.KEY_LOAD_ERROR,new Error(`HTTP Error ${y.code} loading key ${y.text}`),v,xe({url:u.url,data:void 0},y)))},onTimeout:(y,x,v)=>{this.resetLoader(x),l(this.createKeyLoadError(t,D.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),v))},onAbort:(y,x,v)=>{this.resetLoader(x),l(this.createKeyLoadError(t,D.INTERNAL_ABORTED,new Error("key loading aborted"),v))}};a.load(u,p,g)})}resetLoader(e){const{frag:t,keyInfo:s,url:n}=e,a=s.loader;t.keyLoader===a&&(t.keyLoader=null,s.loader=null);const h=ba(s.decryptdata)||n;delete this.keyIdToKeyInfo[h],a&&a.destroy()}}function ba(r){if(r.keyFormat!==Ve.FAIRPLAY){const e=r.keyId;if(e)return Ze(e)}return r.uri}function Qh(r){const{type:e}=r;switch(e){case fe.AUDIO_TRACK:return X.AUDIO;case fe.SUBTITLE_TRACK:return X.SUBTITLE;default:return X.MAIN}}function Aa(r,e){let t=r.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class IS{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.LEVEL_LOADING,this.onLevelLoading,this),e.on(E.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(E.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.LEVEL_LOADING,this.onLevelLoading,this),e.off(E.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(E.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,s=t.pLoader,n=t.loader,a=s||n,h=new a(t);return this.loaders[e.type]=h,h}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:s}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:fe.MANIFEST,url:s,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:s,level:n,pathwayId:a,url:h,deliveryDirectives:l,levelInfo:u}=t;this.load({id:s,level:n,pathwayId:a,responseType:"text",type:fe.LEVEL,url:h,deliveryDirectives:l,levelOrTrack:u})}onAudioTrackLoading(e,t){const{id:s,groupId:n,url:a,deliveryDirectives:h,track:l}=t;this.load({id:s,groupId:n,level:null,responseType:"text",type:fe.AUDIO_TRACK,url:a,deliveryDirectives:h,levelOrTrack:l})}onSubtitleTrackLoading(e,t){const{id:s,groupId:n,url:a,deliveryDirectives:h,track:l}=t;this.load({id:s,groupId:n,level:null,responseType:"text",type:fe.SUBTITLE_TRACK,url:a,deliveryDirectives:h,levelOrTrack:l})}onLevelsUpdated(e,t){const s=this.loaders[fe.LEVEL];if(s){const n=s.context;n&&!t.levels.some(a=>a===n.levelOrTrack)&&(s.abort(),delete this.loaders[fe.LEVEL])}}load(e){var t;const s=this.hls.config;let n=this.getInternalLoader(e);if(n){const d=this.hls.logger,p=n.context;if(p&&p.levelOrTrack===e.levelOrTrack&&(p.url===e.url||p.deliveryDirectives&&!e.deliveryDirectives)){p.url===e.url?d.log(`[playlist-loader]: ignore ${e.url} ongoing request`):d.log(`[playlist-loader]: ignore ${e.url} in favor of ${p.url}`);return}d.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),n.abort()}let a;if(e.type===fe.MANIFEST?a=s.manifestLoadPolicy.default:a=Ee({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),n=this.createInternalLoader(e),q((t=e.deliveryDirectives)==null?void 0:t.part)){let d;if(e.type===fe.LEVEL&&e.level!==null?d=this.hls.levels[e.level].details:e.type===fe.AUDIO_TRACK&&e.id!==null?d=this.hls.audioTracks[e.id].details:e.type===fe.SUBTITLE_TRACK&&e.id!==null&&(d=this.hls.subtitleTracks[e.id].details),d){const p=d.partTarget,g=d.targetduration;if(p&&g){const y=Math.max(p*3,g*.8)*1e3;a=Ee({},a,{maxTimeToFirstByteMs:Math.min(y,a.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(y,a.maxTimeToFirstByteMs)})}}}const h=a.errorRetry||a.timeoutRetry||{},l={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:h.maxNumRetry||0,retryDelay:h.retryDelayMs||0,maxRetryDelay:h.maxRetryDelayMs||0},u={onSuccess:(d,p,g,y)=>{const x=this.getInternalLoader(g);this.resetInternalLoader(g.type);const v=d.data;p.parsing.start=performance.now(),Ut.isMediaPlaylist(v)||g.type!==fe.MANIFEST?this.handleTrackOrLevelPlaylist(d,p,g,y||null,x):this.handleMasterPlaylist(d,p,g,y)},onError:(d,p,g,y)=>{this.handleNetworkError(p,g,!1,d,y)},onTimeout:(d,p,g)=>{this.handleNetworkError(p,g,!0,void 0,d)}};n.load(e,l,u)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:s}=this.hls;(e||s)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,s,n){const a=this.hls,h=e.data,l=Aa(e,s),u=Ut.parseMasterPlaylist(h,l);if(u.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,s,u.playlistParsingError,n,t);return}const{contentSteering:d,levels:p,sessionData:g,sessionKeys:y,startTimeOffset:x,variableList:v}=u;this.variableList=v,p.forEach(f=>{const{unknownCodecs:m}=f;if(m){const{preferManagedMediaSource:S}=this.hls.config;let{audioCodec:T,videoCodec:b}=f;for(let A=m.length;A--;){const I=m[A];Gs(I,"audio",S)?(f.audioCodec=T=T?`${T},${I}`:I,ms.audio[T.substring(0,4)]=2,m.splice(A,1)):Gs(I,"video",S)&&(f.videoCodec=b=b?`${b},${I}`:I,ms.video[b.substring(0,4)]=2,m.splice(A,1))}}});const{AUDIO:_=[],SUBTITLES:o,"CLOSED-CAPTIONS":c}=Ut.parseMasterPlaylistMedia(h,l,u);_.length&&!_.some(m=>!m.url)&&p[0].audioCodec&&!p[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),_.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new Ae({}),bitrate:0,url:""})),a.trigger(E.MANIFEST_LOADED,{levels:p,audioTracks:_,subtitles:o,captions:c,contentSteering:d,url:l,stats:t,networkDetails:n,sessionData:g,sessionKeys:y,startTimeOffset:x,variableList:v})}handleTrackOrLevelPlaylist(e,t,s,n,a){const h=this.hls,{id:l,level:u,type:d}=s,p=Aa(e,s),g=q(u)?u:q(l)?l:0,y=Qh(s),x=Ut.parseLevelPlaylist(e.data,p,g,y,0,this.variableList);if(d===fe.MANIFEST){const v={attrs:new Ae({}),bitrate:0,details:x,name:"",url:p};x.requestScheduled=t.loading.start+Fd(x,0),h.trigger(E.MANIFEST_LOADED,{levels:[v],audioTracks:[],url:p,stats:t,networkDetails:n,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),s.levelDetails=x,this.handlePlaylistLoaded(x,e,t,s,n,a)}handleManifestParsingError(e,t,s,n,a){this.hls.trigger(E.ERROR,{type:Z.NETWORK_ERROR,details:D.MANIFEST_PARSING_ERROR,fatal:t.type===fe.MANIFEST,url:e.url,err:s,error:s,reason:s.message,response:e,context:t,networkDetails:n,stats:a})}handleNetworkError(e,t,s=!1,n,a){let h=`A network ${s?"timeout":"error"+(n?" (status "+n.code+")":"")} occurred while loading ${e.type}`;e.type===fe.LEVEL?h+=`: ${e.level} id: ${e.id}`:(e.type===fe.AUDIO_TRACK||e.type===fe.SUBTITLE_TRACK)&&(h+=` id: ${e.id} group-id: "${e.groupId}"`);const l=new Error(h);this.hls.logger.warn(`[playlist-loader]: ${h}`);let u=D.UNKNOWN,d=!1;const p=this.getInternalLoader(e);switch(e.type){case fe.MANIFEST:u=s?D.MANIFEST_LOAD_TIMEOUT:D.MANIFEST_LOAD_ERROR,d=!0;break;case fe.LEVEL:u=s?D.LEVEL_LOAD_TIMEOUT:D.LEVEL_LOAD_ERROR,d=!1;break;case fe.AUDIO_TRACK:u=s?D.AUDIO_TRACK_LOAD_TIMEOUT:D.AUDIO_TRACK_LOAD_ERROR,d=!1;break;case fe.SUBTITLE_TRACK:u=s?D.SUBTITLE_TRACK_LOAD_TIMEOUT:D.SUBTITLE_LOAD_ERROR,d=!1;break}p&&this.resetInternalLoader(e.type);const g={type:Z.NETWORK_ERROR,details:u,fatal:d,url:e.url,loader:p,context:e,error:l,networkDetails:t,stats:a};if(n){const y=(t==null?void 0:t.url)||e.url;g.response=xe({url:y,data:void 0},n)}this.hls.trigger(E.ERROR,g)}handlePlaylistLoaded(e,t,s,n,a,h){const l=this.hls,{type:u,level:d,levelOrTrack:p,id:g,groupId:y,deliveryDirectives:x}=n,v=Aa(t,n),_=Qh(n);let o=typeof n.level=="number"&&_===X.MAIN?d:void 0;const c=e.playlistParsingError;if(c){if(this.hls.logger.warn(`${c} ${e.url}`),!l.config.ignorePlaylistParsingErrors){l.trigger(E.ERROR,{type:Z.NETWORK_ERROR,details:D.LEVEL_PARSING_ERROR,fatal:!1,url:v,error:c,reason:c.message,response:t,context:n,level:o,parent:_,networkDetails:a,stats:s});return}e.playlistParsingError=null}if(!e.fragments.length){const f=e.playlistParsingError=new Error("No Segments found in Playlist");l.trigger(E.ERROR,{type:Z.NETWORK_ERROR,details:D.LEVEL_EMPTY_ERROR,fatal:!1,url:v,error:f,reason:f.message,response:t,context:n,level:o,parent:_,networkDetails:a,stats:s});return}switch(e.live&&h&&(h.getCacheAge&&(e.ageHeader=h.getCacheAge()||0),(!h.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),u){case fe.MANIFEST:case fe.LEVEL:if(o){if(!p)o=0;else if(p!==l.levels[o]){const f=l.levels.indexOf(p);f>-1&&(o=f)}}l.trigger(E.LEVEL_LOADED,{details:e,levelInfo:p||l.levels[0],level:o||0,id:g||0,stats:s,networkDetails:a,deliveryDirectives:x,withoutMultiVariant:u===fe.MANIFEST});break;case fe.AUDIO_TRACK:l.trigger(E.AUDIO_TRACK_LOADED,{details:e,track:p,id:g||0,groupId:y||"",stats:s,networkDetails:a,deliveryDirectives:x});break;case fe.SUBTITLE_TRACK:l.trigger(E.SUBTITLE_TRACK_LOADED,{details:e,track:p,id:g||0,groupId:y||"",stats:s,networkDetails:a,deliveryDirectives:x});break}}}class Qt{static get version(){return Vs}static isMSESupported(){return Mu()}static isSupported(){return _S()}static getMediaSource(){return Si()}static get Events(){return E}static get MetadataSchema(){return ct}static get ErrorTypes(){return Z}static get ErrorDetails(){return D}static get DefaultConfig(){return Qt.defaultConfig?Qt.defaultConfig:hS}static set DefaultConfig(e){Qt.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Bo,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const t=this.logger=D0(e.debug||!1,"Hls instance",e.assetPlayerId),s=this.config=dS(Qt.DefaultConfig,e,t);this.userConfig=e,s.progressive&&uS(s,t);const{abrController:n,bufferController:a,capLevelController:h,errorController:l,fpsController:u}=s,d=new l(this),p=this.abrController=new n(this),g=new wm(this),y=s.interstitialsController,x=y?this.interstitialsController=new y(this,Qt):null,v=this.bufferController=new a(this,g),_=this.capLevelController=new h(this),o=new u(this),c=new IS(this),f=s.contentSteeringController,m=f?new f(this):null,S=this.levelController=new SS(this,m),T=new vS(this),b=new AS(this.config,this.logger),A=this.streamController=new bS(this,g,b),I=this.gapController=new mS(this,g);_.setStreamController(A),o.setStreamController(A);const L=[c,S,A];x&&L.splice(1,0,x),m&&L.splice(1,0,m),this.networkControllers=L;const w=[p,v,I,_,o,T,g];this.audioTrackController=this.createController(s.audioTrackController,L);const R=s.audioStreamController;R&&L.push(this.audioStreamController=new R(this,g,b)),this.subtitleTrackController=this.createController(s.subtitleTrackController,L);const M=s.subtitleStreamController;M&&L.push(this.subtititleStreamController=new M(this,g,b)),this.createController(s.timelineController,w),b.emeController=this.emeController=this.createController(s.emeController,w),this.cmcdController=this.createController(s.cmcdController,w),this.latencyController=this.createController(xS,w),this.coreComponents=w,L.push(d);const k=d.onErrorOut;typeof k=="function"&&this.on(E.ERROR,k,d),this.on(E.MANIFEST_LOADED,c.onManifestLoaded,c)}createController(e,t){if(e){const s=new e(this);return t&&t.push(s),s}return null}on(e,t,s=this){this._emitter.on(e,t,s)}once(e,t,s=this){this._emitter.once(e,t,s)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,s=this,n){this._emitter.off(e,t,s,n)}listeners(e){return this._emitter.listeners(e)}emit(e,t,s){return this._emitter.emit(e,t,s)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(s){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+s.message+'". Here is a stacktrace:',s),!this.triggeringException){this.triggeringException=!0;const n=e===E.ERROR;this.trigger(E.ERROR,{type:Z.OTHER_ERROR,details:D.INTERNAL_EXCEPTION,fatal:n,event:e,error:s}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(E.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){const a=new Error(`attachMedia failed: invalid argument (${e})`);this.trigger(E.ERROR,{type:Z.OTHER_ERROR,details:D.ATTACH_MEDIA_ERROR,fatal:!0,error:a});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const t="media"in e,s=t?e.media:e,n=t?e:{media:s};this._media=s,this.trigger(E.MEDIA_ATTACHING,n)}detachMedia(){this.logger.log("detachMedia"),this.trigger(E.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger(E.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const t=this.media,s=this._url,n=this._url=wo.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${n}`),t&&s&&(s!==n||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(E.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let s=0;s<this.networkControllers.length&&(this.networkControllers[s].startLoad(e,t),!(!this.started||!this.networkControllers));s++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!(this.started||!this.networkControllers));e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){const e={[X.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[X.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[X.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,t=e==null?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=mx()),e}get levels(){const e=this.levelController.levels;return e||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){const{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){dm(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const s=e.length;for(let n=0;n<s;n++)if(e[n].maxBitrate>=t)return n;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:s}=this;let n;if(t===-1&&e!=null&&e.length?n=e.length-1:n=t,s)for(let a=n;a--;){const h=e[a].attrs["HDCP-LEVEL"];if(h&&h<=s)return a}return n}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return((t=this.audioTrackController)==null?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return((t=this.subtitleTrackController)==null?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(e){this.latencyController.targetLatency=e}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!!((e=this.bufferController)!=null&&e.bufferedToEnd)}get interstitialsManager(){var e;return((e=this.interstitialsController)==null?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){const s=Sd(t);return vd(e,s,navigator.mediaCapabilities)}}Qt.defaultConfig=void 0;var or={};(function(r){var e=function(){var o=new Date,c=4,f=3,m=2,S=1,T=c,b={setLogLevel:function(A){A==this.debug?T=S:A==this.info?T=m:A==this.warn?T=f:(A==this.error,T=c)},debug:function(A,I){console.debug===void 0&&(console.debug=console.log),S>=T&&console.debug("["+e.getDurationString(new Date-o,1e3)+"]","["+A+"]",I)},log:function(A,I){this.debug(A.msg)},info:function(A,I){m>=T&&console.info("["+e.getDurationString(new Date-o,1e3)+"]","["+A+"]",I)},warn:function(A,I){f>=T&&console.warn("["+e.getDurationString(new Date-o,1e3)+"]","["+A+"]",I)},error:function(A,I){c>=T&&console.error("["+e.getDurationString(new Date-o,1e3)+"]","["+A+"]",I)}};return b}();e.getDurationString=function(o,c){var f;function m(L,w){for(var R=""+L,M=R.split(".");M[0].length<w;)M[0]="0"+M[0];return M.join(".")}o<0?(f=!0,o=-o):f=!1;var S=c||1,T=o/S,b=Math.floor(T/3600);T-=b*3600;var A=Math.floor(T/60);T-=A*60;var I=T*1e3;return T=Math.floor(T),I-=T*1e3,I=Math.floor(I),(f?"-":"")+b+":"+m(A,2)+":"+m(T,2)+"."+m(I,3)},e.printRanges=function(o){var c=o.length;if(c>0){for(var f="",m=0;m<c;m++)m>0&&(f+=","),f+="["+e.getDurationString(o.start(m))+","+e.getDurationString(o.end(m))+"]";return f}else return"(empty)"},r.Log=e;var t=function(o){if(o instanceof ArrayBuffer)this.buffer=o,this.dataview=new DataView(o);else throw"Needs an array buffer";this.position=0};t.prototype.getPosition=function(){return this.position},t.prototype.getEndPosition=function(){return this.buffer.byteLength},t.prototype.getLength=function(){return this.buffer.byteLength},t.prototype.seek=function(o){var c=Math.max(0,Math.min(this.buffer.byteLength,o));return this.position=isNaN(c)||!isFinite(c)?0:c,!0},t.prototype.isEos=function(){return this.getPosition()>=this.getEndPosition()},t.prototype.readAnyInt=function(o,c){var f=0;if(this.position+o<=this.buffer.byteLength){switch(o){case 1:c?f=this.dataview.getInt8(this.position):f=this.dataview.getUint8(this.position);break;case 2:c?f=this.dataview.getInt16(this.position):f=this.dataview.getUint16(this.position);break;case 3:if(c)throw"No method for reading signed 24 bits values";f=this.dataview.getUint8(this.position)<<16,f|=this.dataview.getUint8(this.position+1)<<8,f|=this.dataview.getUint8(this.position+2);break;case 4:c?f=this.dataview.getInt32(this.position):f=this.dataview.getUint32(this.position);break;case 8:if(c)throw"No method for reading signed 64 bits values";f=this.dataview.getUint32(this.position)<<32,f|=this.dataview.getUint32(this.position+4);break;default:throw"readInt method not implemented for size: "+o}return this.position+=o,f}else throw"Not enough bytes in buffer"},t.prototype.readUint8=function(){return this.readAnyInt(1,!1)},t.prototype.readUint16=function(){return this.readAnyInt(2,!1)},t.prototype.readUint24=function(){return this.readAnyInt(3,!1)},t.prototype.readUint32=function(){return this.readAnyInt(4,!1)},t.prototype.readUint64=function(){return this.readAnyInt(8,!1)},t.prototype.readString=function(o){if(this.position+o<=this.buffer.byteLength){for(var c="",f=0;f<o;f++)c+=String.fromCharCode(this.readUint8());return c}else throw"Not enough bytes in buffer"},t.prototype.readCString=function(){for(var o=[];;){var c=this.readUint8();if(c!==0)o.push(c);else break}return String.fromCharCode.apply(null,o)},t.prototype.readInt8=function(){return this.readAnyInt(1,!0)},t.prototype.readInt16=function(){return this.readAnyInt(2,!0)},t.prototype.readInt32=function(){return this.readAnyInt(4,!0)},t.prototype.readInt64=function(){return this.readAnyInt(8,!1)},t.prototype.readUint8Array=function(o){for(var c=new Uint8Array(o),f=0;f<o;f++)c[f]=this.readUint8();return c},t.prototype.readInt16Array=function(o){for(var c=new Int16Array(o),f=0;f<o;f++)c[f]=this.readInt16();return c},t.prototype.readUint16Array=function(o){for(var c=new Int16Array(o),f=0;f<o;f++)c[f]=this.readUint16();return c},t.prototype.readUint32Array=function(o){for(var c=new Uint32Array(o),f=0;f<o;f++)c[f]=this.readUint32();return c},t.prototype.readInt32Array=function(o){for(var c=new Int32Array(o),f=0;f<o;f++)c[f]=this.readInt32();return c},r.MP4BoxStream=t;var s=function(o,c,f){this._byteOffset=c||0,o instanceof ArrayBuffer?this.buffer=o:typeof o=="object"?(this.dataView=o,c&&(this._byteOffset+=c)):this.buffer=new ArrayBuffer(o||0),this.position=0,this.endianness=f??s.LITTLE_ENDIAN};s.prototype={},s.prototype.getPosition=function(){return this.position},s.prototype._realloc=function(o){if(this._dynamicSize){var c=this._byteOffset+this.position+o,f=this._buffer.byteLength;if(c<=f){c>this._byteLength&&(this._byteLength=c);return}for(f<1&&(f=1);c>f;)f*=2;var m=new ArrayBuffer(f),S=new Uint8Array(this._buffer),T=new Uint8Array(m,0,S.length);T.set(S),this.buffer=m,this._byteLength=c}},s.prototype._trimAlloc=function(){if(this._byteLength!=this._buffer.byteLength){var o=new ArrayBuffer(this._byteLength),c=new Uint8Array(o),f=new Uint8Array(this._buffer,0,c.length);c.set(f),this.buffer=o}},s.BIG_ENDIAN=!1,s.LITTLE_ENDIAN=!0,s.prototype._byteLength=0,Object.defineProperty(s.prototype,"byteLength",{get:function(){return this._byteLength-this._byteOffset}}),Object.defineProperty(s.prototype,"buffer",{get:function(){return this._trimAlloc(),this._buffer},set:function(o){this._buffer=o,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._buffer.byteLength}}),Object.defineProperty(s.prototype,"byteOffset",{get:function(){return this._byteOffset},set:function(o){this._byteOffset=o,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._buffer.byteLength}}),Object.defineProperty(s.prototype,"dataView",{get:function(){return this._dataView},set:function(o){this._byteOffset=o.byteOffset,this._buffer=o.buffer,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._byteOffset+o.byteLength}}),s.prototype.seek=function(o){var c=Math.max(0,Math.min(this.byteLength,o));this.position=isNaN(c)||!isFinite(c)?0:c},s.prototype.isEof=function(){return this.position>=this._byteLength},s.prototype.mapUint8Array=function(o){this._realloc(o*1);var c=new Uint8Array(this._buffer,this.byteOffset+this.position,o);return this.position+=o*1,c},s.prototype.readInt32Array=function(o,c){o=o??this.byteLength-this.position/4;var f=new Int32Array(o);return s.memcpy(f.buffer,0,this.buffer,this.byteOffset+this.position,o*f.BYTES_PER_ELEMENT),s.arrayToNative(f,c??this.endianness),this.position+=f.byteLength,f},s.prototype.readInt16Array=function(o,c){o=o??this.byteLength-this.position/2;var f=new Int16Array(o);return s.memcpy(f.buffer,0,this.buffer,this.byteOffset+this.position,o*f.BYTES_PER_ELEMENT),s.arrayToNative(f,c??this.endianness),this.position+=f.byteLength,f},s.prototype.readInt8Array=function(o){o=o??this.byteLength-this.position;var c=new Int8Array(o);return s.memcpy(c.buffer,0,this.buffer,this.byteOffset+this.position,o*c.BYTES_PER_ELEMENT),this.position+=c.byteLength,c},s.prototype.readUint32Array=function(o,c){o=o??this.byteLength-this.position/4;var f=new Uint32Array(o);return s.memcpy(f.buffer,0,this.buffer,this.byteOffset+this.position,o*f.BYTES_PER_ELEMENT),s.arrayToNative(f,c??this.endianness),this.position+=f.byteLength,f},s.prototype.readUint16Array=function(o,c){o=o??this.byteLength-this.position/2;var f=new Uint16Array(o);return s.memcpy(f.buffer,0,this.buffer,this.byteOffset+this.position,o*f.BYTES_PER_ELEMENT),s.arrayToNative(f,c??this.endianness),this.position+=f.byteLength,f},s.prototype.readUint8Array=function(o){o=o??this.byteLength-this.position;var c=new Uint8Array(o);return s.memcpy(c.buffer,0,this.buffer,this.byteOffset+this.position,o*c.BYTES_PER_ELEMENT),this.position+=c.byteLength,c},s.prototype.readFloat64Array=function(o,c){o=o??this.byteLength-this.position/8;var f=new Float64Array(o);return s.memcpy(f.buffer,0,this.buffer,this.byteOffset+this.position,o*f.BYTES_PER_ELEMENT),s.arrayToNative(f,c??this.endianness),this.position+=f.byteLength,f},s.prototype.readFloat32Array=function(o,c){o=o??this.byteLength-this.position/4;var f=new Float32Array(o);return s.memcpy(f.buffer,0,this.buffer,this.byteOffset+this.position,o*f.BYTES_PER_ELEMENT),s.arrayToNative(f,c??this.endianness),this.position+=f.byteLength,f},s.prototype.readInt32=function(o){var c=this._dataView.getInt32(this.position,o??this.endianness);return this.position+=4,c},s.prototype.readInt16=function(o){var c=this._dataView.getInt16(this.position,o??this.endianness);return this.position+=2,c},s.prototype.readInt8=function(){var o=this._dataView.getInt8(this.position);return this.position+=1,o},s.prototype.readUint32=function(o){var c=this._dataView.getUint32(this.position,o??this.endianness);return this.position+=4,c},s.prototype.readUint16=function(o){var c=this._dataView.getUint16(this.position,o??this.endianness);return this.position+=2,c},s.prototype.readUint8=function(){var o=this._dataView.getUint8(this.position);return this.position+=1,o},s.prototype.readFloat32=function(o){var c=this._dataView.getFloat32(this.position,o??this.endianness);return this.position+=4,c},s.prototype.readFloat64=function(o){var c=this._dataView.getFloat64(this.position,o??this.endianness);return this.position+=8,c},s.endianness=new Int8Array(new Int16Array([1]).buffer)[0]>0,s.memcpy=function(o,c,f,m,S){var T=new Uint8Array(o,c,S),b=new Uint8Array(f,m,S);T.set(b)},s.arrayToNative=function(o,c){return c==this.endianness?o:this.flipArrayEndianness(o)},s.nativeToEndian=function(o,c){return this.endianness==c?o:this.flipArrayEndianness(o)},s.flipArrayEndianness=function(o){for(var c=new Uint8Array(o.buffer,o.byteOffset,o.byteLength),f=0;f<o.byteLength;f+=o.BYTES_PER_ELEMENT)for(var m=f+o.BYTES_PER_ELEMENT-1,S=f;m>S;m--,S++){var T=c[S];c[S]=c[m],c[m]=T}return o},s.prototype.failurePosition=0,String.fromCharCodeUint8=function(o){for(var c=[],f=0;f<o.length;f++)c[f]=o[f];return String.fromCharCode.apply(null,c)},s.prototype.readString=function(o,c){return c==null||c=="ASCII"?String.fromCharCodeUint8.apply(null,[this.mapUint8Array(o??this.byteLength-this.position)]):new TextDecoder(c).decode(this.mapUint8Array(o))},s.prototype.readCString=function(o){var c=this.byteLength-this.position,f=new Uint8Array(this._buffer,this._byteOffset+this.position),m=c;o!=null&&(m=Math.min(o,c));for(var S=0;S<m&&f[S]!==0;S++);var T=String.fromCharCodeUint8.apply(null,[this.mapUint8Array(S)]);return o!=null?this.position+=m-S:S!=c&&(this.position+=1),T};var n=Math.pow(2,32);s.prototype.readInt64=function(){return this.readInt32()*n+this.readUint32()},s.prototype.readUint64=function(){return this.readUint32()*n+this.readUint32()},s.prototype.readInt64=function(){return this.readUint32()*n+this.readUint32()},s.prototype.readUint24=function(){return(this.readUint8()<<16)+(this.readUint8()<<8)+this.readUint8()},r.DataStream=s,s.prototype.save=function(o){var c=new Blob([this.buffer]);if(window.URL&&URL.createObjectURL){var f=window.URL.createObjectURL(c),m=document.createElement("a");document.body.appendChild(m),m.setAttribute("href",f),m.setAttribute("download",o),m.setAttribute("target","_self"),m.click(),window.URL.revokeObjectURL(f)}else throw"DataStream.save: Can't create object URL."},s.prototype._dynamicSize=!0,Object.defineProperty(s.prototype,"dynamicSize",{get:function(){return this._dynamicSize},set:function(o){o||this._trimAlloc(),this._dynamicSize=o}}),s.prototype.shift=function(o){var c=new ArrayBuffer(this._byteLength-o),f=new Uint8Array(c),m=new Uint8Array(this._buffer,o,f.length);f.set(m),this.buffer=c,this.position-=o},s.prototype.writeInt32Array=function(o,c){if(this._realloc(o.length*4),o instanceof Int32Array&&this.byteOffset+this.position%o.BYTES_PER_ELEMENT===0)s.memcpy(this._buffer,this.byteOffset+this.position,o.buffer,0,o.byteLength),this.mapInt32Array(o.length,c);else for(var f=0;f<o.length;f++)this.writeInt32(o[f],c)},s.prototype.writeInt16Array=function(o,c){if(this._realloc(o.length*2),o instanceof Int16Array&&this.byteOffset+this.position%o.BYTES_PER_ELEMENT===0)s.memcpy(this._buffer,this.byteOffset+this.position,o.buffer,0,o.byteLength),this.mapInt16Array(o.length,c);else for(var f=0;f<o.length;f++)this.writeInt16(o[f],c)},s.prototype.writeInt8Array=function(o){if(this._realloc(o.length*1),o instanceof Int8Array&&this.byteOffset+this.position%o.BYTES_PER_ELEMENT===0)s.memcpy(this._buffer,this.byteOffset+this.position,o.buffer,0,o.byteLength),this.mapInt8Array(o.length);else for(var c=0;c<o.length;c++)this.writeInt8(o[c])},s.prototype.writeUint32Array=function(o,c){if(this._realloc(o.length*4),o instanceof Uint32Array&&this.byteOffset+this.position%o.BYTES_PER_ELEMENT===0)s.memcpy(this._buffer,this.byteOffset+this.position,o.buffer,0,o.byteLength),this.mapUint32Array(o.length,c);else for(var f=0;f<o.length;f++)this.writeUint32(o[f],c)},s.prototype.writeUint16Array=function(o,c){if(this._realloc(o.length*2),o instanceof Uint16Array&&this.byteOffset+this.position%o.BYTES_PER_ELEMENT===0)s.memcpy(this._buffer,this.byteOffset+this.position,o.buffer,0,o.byteLength),this.mapUint16Array(o.length,c);else for(var f=0;f<o.length;f++)this.writeUint16(o[f],c)},s.prototype.writeUint8Array=function(o){if(this._realloc(o.length*1),o instanceof Uint8Array&&this.byteOffset+this.position%o.BYTES_PER_ELEMENT===0)s.memcpy(this._buffer,this.byteOffset+this.position,o.buffer,0,o.byteLength),this.mapUint8Array(o.length);else for(var c=0;c<o.length;c++)this.writeUint8(o[c])},s.prototype.writeFloat64Array=function(o,c){if(this._realloc(o.length*8),o instanceof Float64Array&&this.byteOffset+this.position%o.BYTES_PER_ELEMENT===0)s.memcpy(this._buffer,this.byteOffset+this.position,o.buffer,0,o.byteLength),this.mapFloat64Array(o.length,c);else for(var f=0;f<o.length;f++)this.writeFloat64(o[f],c)},s.prototype.writeFloat32Array=function(o,c){if(this._realloc(o.length*4),o instanceof Float32Array&&this.byteOffset+this.position%o.BYTES_PER_ELEMENT===0)s.memcpy(this._buffer,this.byteOffset+this.position,o.buffer,0,o.byteLength),this.mapFloat32Array(o.length,c);else for(var f=0;f<o.length;f++)this.writeFloat32(o[f],c)},s.prototype.writeInt32=function(o,c){this._realloc(4),this._dataView.setInt32(this.position,o,c??this.endianness),this.position+=4},s.prototype.writeInt16=function(o,c){this._realloc(2),this._dataView.setInt16(this.position,o,c??this.endianness),this.position+=2},s.prototype.writeInt8=function(o){this._realloc(1),this._dataView.setInt8(this.position,o),this.position+=1},s.prototype.writeUint32=function(o,c){this._realloc(4),this._dataView.setUint32(this.position,o,c??this.endianness),this.position+=4},s.prototype.writeUint16=function(o,c){this._realloc(2),this._dataView.setUint16(this.position,o,c??this.endianness),this.position+=2},s.prototype.writeUint8=function(o){this._realloc(1),this._dataView.setUint8(this.position,o),this.position+=1},s.prototype.writeFloat32=function(o,c){this._realloc(4),this._dataView.setFloat32(this.position,o,c??this.endianness),this.position+=4},s.prototype.writeFloat64=function(o,c){this._realloc(8),this._dataView.setFloat64(this.position,o,c??this.endianness),this.position+=8},s.prototype.writeUCS2String=function(o,c,f){f==null&&(f=o.length);for(var m=0;m<o.length&&m<f;m++)this.writeUint16(o.charCodeAt(m),c);for(;m<f;m++)this.writeUint16(0)},s.prototype.writeString=function(o,c,f){var m=0;if(c==null||c=="ASCII")if(f!=null){var S=Math.min(o.length,f);for(m=0;m<S;m++)this.writeUint8(o.charCodeAt(m));for(;m<f;m++)this.writeUint8(0)}else for(m=0;m<o.length;m++)this.writeUint8(o.charCodeAt(m));else this.writeUint8Array(new TextEncoder(c).encode(o.substring(0,f)))},s.prototype.writeCString=function(o,c){var f=0;if(c!=null){var m=Math.min(o.length,c);for(f=0;f<m;f++)this.writeUint8(o.charCodeAt(f));for(;f<c;f++)this.writeUint8(0)}else{for(f=0;f<o.length;f++)this.writeUint8(o.charCodeAt(f));this.writeUint8(0)}},s.prototype.writeStruct=function(o,c){for(var f=0;f<o.length;f+=2){var m=o[f+1];this.writeType(m,c[o[f]],c)}},s.prototype.writeType=function(o,c,f){var m;if(typeof o=="function")return o(this,c);if(typeof o=="object"&&!(o instanceof Array))return o.set(this,c,f);var S=null,T="ASCII",b=this.position;switch(typeof o=="string"&&/:/.test(o)&&(m=o.split(":"),o=m[0],S=parseInt(m[1])),typeof o=="string"&&/,/.test(o)&&(m=o.split(","),o=m[0],T=parseInt(m[1])),o){case"uint8":this.writeUint8(c);break;case"int8":this.writeInt8(c);break;case"uint16":this.writeUint16(c,this.endianness);break;case"int16":this.writeInt16(c,this.endianness);break;case"uint32":this.writeUint32(c,this.endianness);break;case"int32":this.writeInt32(c,this.endianness);break;case"float32":this.writeFloat32(c,this.endianness);break;case"float64":this.writeFloat64(c,this.endianness);break;case"uint16be":this.writeUint16(c,s.BIG_ENDIAN);break;case"int16be":this.writeInt16(c,s.BIG_ENDIAN);break;case"uint32be":this.writeUint32(c,s.BIG_ENDIAN);break;case"int32be":this.writeInt32(c,s.BIG_ENDIAN);break;case"float32be":this.writeFloat32(c,s.BIG_ENDIAN);break;case"float64be":this.writeFloat64(c,s.BIG_ENDIAN);break;case"uint16le":this.writeUint16(c,s.LITTLE_ENDIAN);break;case"int16le":this.writeInt16(c,s.LITTLE_ENDIAN);break;case"uint32le":this.writeUint32(c,s.LITTLE_ENDIAN);break;case"int32le":this.writeInt32(c,s.LITTLE_ENDIAN);break;case"float32le":this.writeFloat32(c,s.LITTLE_ENDIAN);break;case"float64le":this.writeFloat64(c,s.LITTLE_ENDIAN);break;case"cstring":this.writeCString(c,S);break;case"string":this.writeString(c,T,S);break;case"u16string":this.writeUCS2String(c,this.endianness,S);break;case"u16stringle":this.writeUCS2String(c,s.LITTLE_ENDIAN,S);break;case"u16stringbe":this.writeUCS2String(c,s.BIG_ENDIAN,S);break;default:if(o.length==3){for(var A=o[1],I=0;I<c.length;I++)this.writeType(A,c[I]);break}else{this.writeStruct(o,c);break}}S!=null&&(this.position=b,this._realloc(S),this.position=b+S)},s.prototype.writeUint64=function(o){var c=Math.floor(o/n);this.writeUint32(c),this.writeUint32(o&4294967295)},s.prototype.writeUint24=function(o){this.writeUint8((o&16711680)>>16),this.writeUint8((o&65280)>>8),this.writeUint8(o&255)},s.prototype.adjustUint32=function(o,c){var f=this.position;this.seek(o),this.writeUint32(c),this.seek(f)},s.prototype.mapInt32Array=function(o,c){this._realloc(o*4);var f=new Int32Array(this._buffer,this.byteOffset+this.position,o);return s.arrayToNative(f,c??this.endianness),this.position+=o*4,f},s.prototype.mapInt16Array=function(o,c){this._realloc(o*2);var f=new Int16Array(this._buffer,this.byteOffset+this.position,o);return s.arrayToNative(f,c??this.endianness),this.position+=o*2,f},s.prototype.mapInt8Array=function(o){this._realloc(o*1);var c=new Int8Array(this._buffer,this.byteOffset+this.position,o);return this.position+=o*1,c},s.prototype.mapUint32Array=function(o,c){this._realloc(o*4);var f=new Uint32Array(this._buffer,this.byteOffset+this.position,o);return s.arrayToNative(f,c??this.endianness),this.position+=o*4,f},s.prototype.mapUint16Array=function(o,c){this._realloc(o*2);var f=new Uint16Array(this._buffer,this.byteOffset+this.position,o);return s.arrayToNative(f,c??this.endianness),this.position+=o*2,f},s.prototype.mapFloat64Array=function(o,c){this._realloc(o*8);var f=new Float64Array(this._buffer,this.byteOffset+this.position,o);return s.arrayToNative(f,c??this.endianness),this.position+=o*8,f},s.prototype.mapFloat32Array=function(o,c){this._realloc(o*4);var f=new Float32Array(this._buffer,this.byteOffset+this.position,o);return s.arrayToNative(f,c??this.endianness),this.position+=o*4,f};var a=function(o){this.buffers=[],this.bufferIndex=-1,o&&(this.insertBuffer(o),this.bufferIndex=0)};a.prototype=new s(new ArrayBuffer,0,s.BIG_ENDIAN),a.prototype.initialized=function(){var o;return this.bufferIndex>-1?!0:this.buffers.length>0?(o=this.buffers[0],o.fileStart===0?(this.buffer=o,this.bufferIndex=0,e.debug("MultiBufferStream","Stream ready for parsing"),!0):(e.warn("MultiBufferStream","The first buffer should have a fileStart of 0"),this.logBufferLevel(),!1)):(e.warn("MultiBufferStream","No buffer to start parsing from"),this.logBufferLevel(),!1)},ArrayBuffer.concat=function(o,c){e.debug("ArrayBuffer","Trying to create a new buffer of size: "+(o.byteLength+c.byteLength));var f=new Uint8Array(o.byteLength+c.byteLength);return f.set(new Uint8Array(o),0),f.set(new Uint8Array(c),o.byteLength),f.buffer},a.prototype.reduceBuffer=function(o,c,f){var m;return m=new Uint8Array(f),m.set(new Uint8Array(o,c,f)),m.buffer.fileStart=o.fileStart+c,m.buffer.usedBytes=0,m.buffer},a.prototype.insertBuffer=function(o){for(var c=!0,f=0;f<this.buffers.length;f++){var m=this.buffers[f];if(o.fileStart<=m.fileStart){if(o.fileStart===m.fileStart)if(o.byteLength>m.byteLength){this.buffers.splice(f,1),f--;continue}else e.warn("MultiBufferStream","Buffer (fileStart: "+o.fileStart+" - Length: "+o.byteLength+") already appended, ignoring");else o.fileStart+o.byteLength<=m.fileStart||(o=this.reduceBuffer(o,0,m.fileStart-o.fileStart)),e.debug("MultiBufferStream","Appending new buffer (fileStart: "+o.fileStart+" - Length: "+o.byteLength+")"),this.buffers.splice(f,0,o),f===0&&(this.buffer=o);c=!1;break}else if(o.fileStart<m.fileStart+m.byteLength){var S=m.fileStart+m.byteLength-o.fileStart,T=o.byteLength-S;if(T>0)o=this.reduceBuffer(o,S,T);else{c=!1;break}}}c&&(e.debug("MultiBufferStream","Appending new buffer (fileStart: "+o.fileStart+" - Length: "+o.byteLength+")"),this.buffers.push(o),f===0&&(this.buffer=o))},a.prototype.logBufferLevel=function(o){var c,f,m,S,T=[],b,A="";for(m=0,S=0,c=0;c<this.buffers.length;c++)f=this.buffers[c],c===0?(b={},T.push(b),b.start=f.fileStart,b.end=f.fileStart+f.byteLength,A+="["+b.start+"-"):b.end===f.fileStart?b.end=f.fileStart+f.byteLength:(b={},b.start=f.fileStart,A+=T[T.length-1].end-1+"], ["+b.start+"-",b.end=f.fileStart+f.byteLength,T.push(b)),m+=f.usedBytes,S+=f.byteLength;T.length>0&&(A+=b.end-1+"]");var I=o?e.info:e.debug;this.buffers.length===0?I("MultiBufferStream","No more buffer in memory"):I("MultiBufferStream",""+this.buffers.length+" stored buffer(s) ("+m+"/"+S+" bytes), continuous ranges: "+A)},a.prototype.cleanBuffers=function(){var o,c;for(o=0;o<this.buffers.length;o++)c=this.buffers[o],c.usedBytes===c.byteLength&&(e.debug("MultiBufferStream","Removing buffer #"+o),this.buffers.splice(o,1),o--)},a.prototype.mergeNextBuffer=function(){var o;if(this.bufferIndex+1<this.buffers.length)if(o=this.buffers[this.bufferIndex+1],o.fileStart===this.buffer.fileStart+this.buffer.byteLength){var c=this.buffer.byteLength,f=this.buffer.usedBytes,m=this.buffer.fileStart;return this.buffers[this.bufferIndex]=ArrayBuffer.concat(this.buffer,o),this.buffer=this.buffers[this.bufferIndex],this.buffers.splice(this.bufferIndex+1,1),this.buffer.usedBytes=f,this.buffer.fileStart=m,e.debug("ISOFile","Concatenating buffer for box parsing (length: "+c+"->"+this.buffer.byteLength+")"),!0}else return!1;else return!1},a.prototype.findPosition=function(o,c,f){var m,S=null,T=-1;for(o===!0?m=0:m=this.bufferIndex;m<this.buffers.length&&(S=this.buffers[m],S.fileStart<=c);){T=m,f&&(S.fileStart+S.byteLength<=c?S.usedBytes=S.byteLength:S.usedBytes=c-S.fileStart,this.logBufferLevel());m++}return T!==-1?(S=this.buffers[T],S.fileStart+S.byteLength>=c?(e.debug("MultiBufferStream","Found position in existing buffer #"+T),T):-1):-1},a.prototype.findEndContiguousBuf=function(o){var c,f,m,S=o!==void 0?o:this.bufferIndex;if(f=this.buffers[S],this.buffers.length>S+1)for(c=S+1;c<this.buffers.length&&(m=this.buffers[c],m.fileStart===f.fileStart+f.byteLength);c++)f=m;return f.fileStart+f.byteLength},a.prototype.getEndFilePositionAfter=function(o){var c=this.findPosition(!0,o,!1);return c!==-1?this.findEndContiguousBuf(c):o},a.prototype.addUsedBytes=function(o){this.buffer.usedBytes+=o,this.logBufferLevel()},a.prototype.setAllUsedBytes=function(){this.buffer.usedBytes=this.buffer.byteLength,this.logBufferLevel()},a.prototype.seek=function(o,c,f){var m;return m=this.findPosition(c,o,f),m!==-1?(this.buffer=this.buffers[m],this.bufferIndex=m,this.position=o-this.buffer.fileStart,e.debug("MultiBufferStream","Repositioning parser at buffer position: "+this.position),!0):(e.debug("MultiBufferStream","Position "+o+" not found in buffered data"),!1)},a.prototype.getPosition=function(){if(this.bufferIndex===-1||this.buffers[this.bufferIndex]===null)throw"Error accessing position in the MultiBufferStream";return this.buffers[this.bufferIndex].fileStart+this.position},a.prototype.getLength=function(){return this.byteLength},a.prototype.getEndPosition=function(){if(this.bufferIndex===-1||this.buffers[this.bufferIndex]===null)throw"Error accessing position in the MultiBufferStream";return this.buffers[this.bufferIndex].fileStart+this.byteLength},r.MultiBufferStream=a;var h=function(){var o=3,c=4,f=5,m=6,S=[];S[o]="ES_Descriptor",S[c]="DecoderConfigDescriptor",S[f]="DecoderSpecificInfo",S[m]="SLConfigDescriptor",this.getDescriptorName=function(A){return S[A]};var T=this,b={};return this.parseOneDescriptor=function(A){var I=0,L,w,R;for(L=A.readUint8(),R=A.readUint8();R&128;)I=(I<<7)+(R&127),R=A.readUint8();return I=(I<<7)+(R&127),e.debug("MPEG4DescriptorParser","Found "+(S[L]||"Descriptor "+L)+", size "+I+" at position "+A.getPosition()),S[L]?w=new b[S[L]](I):w=new b.Descriptor(I),w.parse(A),w},b.Descriptor=function(A,I){this.tag=A,this.size=I,this.descs=[]},b.Descriptor.prototype.parse=function(A){this.data=A.readUint8Array(this.size)},b.Descriptor.prototype.findDescriptor=function(A){for(var I=0;I<this.descs.length;I++)if(this.descs[I].tag==A)return this.descs[I];return null},b.Descriptor.prototype.parseRemainingDescriptors=function(A){for(var I=A.position;A.position<I+this.size;){var L=T.parseOneDescriptor(A);this.descs.push(L)}},b.ES_Descriptor=function(A){b.Descriptor.call(this,o,A)},b.ES_Descriptor.prototype=new b.Descriptor,b.ES_Descriptor.prototype.parse=function(A){if(this.ES_ID=A.readUint16(),this.flags=A.readUint8(),this.size-=3,this.flags&128?(this.dependsOn_ES_ID=A.readUint16(),this.size-=2):this.dependsOn_ES_ID=0,this.flags&64){var I=A.readUint8();this.URL=A.readString(I),this.size-=I+1}else this.URL="";this.flags&32?(this.OCR_ES_ID=A.readUint16(),this.size-=2):this.OCR_ES_ID=0,this.parseRemainingDescriptors(A)},b.ES_Descriptor.prototype.getOTI=function(A){var I=this.findDescriptor(c);return I?I.oti:0},b.ES_Descriptor.prototype.getAudioConfig=function(A){var I=this.findDescriptor(c);if(!I)return null;var L=I.findDescriptor(f);if(L&&L.data){var w=(L.data[0]&248)>>3;return w===31&&L.data.length>=2&&(w=32+((L.data[0]&7)<<3)+((L.data[1]&224)>>5)),w}else return null},b.DecoderConfigDescriptor=function(A){b.Descriptor.call(this,c,A)},b.DecoderConfigDescriptor.prototype=new b.Descriptor,b.DecoderConfigDescriptor.prototype.parse=function(A){this.oti=A.readUint8(),this.streamType=A.readUint8(),this.upStream=(this.streamType>>1&1)!==0,this.streamType=this.streamType>>>2,this.bufferSize=A.readUint24(),this.maxBitrate=A.readUint32(),this.avgBitrate=A.readUint32(),this.size-=13,this.parseRemainingDescriptors(A)},b.DecoderSpecificInfo=function(A){b.Descriptor.call(this,f,A)},b.DecoderSpecificInfo.prototype=new b.Descriptor,b.SLConfigDescriptor=function(A){b.Descriptor.call(this,m,A)},b.SLConfigDescriptor.prototype=new b.Descriptor,this};r.MPEG4DescriptorParser=h;var l={ERR_INVALID_DATA:-1,ERR_NOT_ENOUGH_DATA:0,OK:1,BASIC_BOXES:[{type:"mdat",name:"MediaDataBox"},{type:"idat",name:"ItemDataBox"},{type:"free",name:"FreeSpaceBox"},{type:"skip",name:"FreeSpaceBox"},{type:"meco",name:"AdditionalMetadataContainerBox"},{type:"strk",name:"SubTrackBox"}],FULL_BOXES:[{type:"hmhd",name:"HintMediaHeaderBox"},{type:"nmhd",name:"NullMediaHeaderBox"},{type:"iods",name:"ObjectDescriptorBox"},{type:"xml ",name:"XMLBox"},{type:"bxml",name:"BinaryXMLBox"},{type:"ipro",name:"ItemProtectionBox"},{type:"mere",name:"MetaboxRelationBox"}],CONTAINER_BOXES:[[{type:"moov",name:"CompressedMovieBox"},["trak","pssh"]],[{type:"trak",name:"TrackBox"}],[{type:"edts",name:"EditBox"}],[{type:"mdia",name:"MediaBox"}],[{type:"minf",name:"MediaInformationBox"}],[{type:"dinf",name:"DataInformationBox"}],[{type:"stbl",name:"SampleTableBox"},["sgpd","sbgp"]],[{type:"mvex",name:"MovieExtendsBox"},["trex"]],[{type:"moof",name:"CompressedMovieFragmentBox"},["traf"]],[{type:"traf",name:"TrackFragmentBox"},["trun","sgpd","sbgp"]],[{type:"vttc",name:"VTTCueBox"}],[{type:"tref",name:"TrackReferenceBox"}],[{type:"iref",name:"ItemReferenceBox"}],[{type:"mfra",name:"MovieFragmentRandomAccessBox"},["tfra"]],[{type:"meco",name:"AdditionalMetadataContainerBox"}],[{type:"hnti",name:"trackhintinformation"}],[{type:"hinf",name:"hintstatisticsbox"}],[{type:"strk",name:"SubTrackBox"}],[{type:"strd",name:"SubTrackDefinitionBox"}],[{type:"sinf",name:"ProtectionSchemeInfoBox"}],[{type:"rinf",name:"RestrictedSchemeInfoBox"}],[{type:"schi",name:"SchemeInformationBox"}],[{type:"trgr",name:"TrackGroupBox"}],[{type:"udta",name:"UserDataBox"},["kind"]],[{type:"iprp",name:"ItemPropertiesBox"},["ipma"]],[{type:"ipco",name:"ItemPropertyContainerBox"}],[{type:"grpl",name:"GroupsListBox"}],[{type:"j2kH",name:"J2KHeaderInfoBox"}],[{type:"etyp",name:"ExtendedTypeBox"},["tyco"]]],boxCodes:[],fullBoxCodes:[],containerBoxCodes:[],sampleEntryCodes:{},sampleGroupEntryCodes:[],trackGroupTypes:[],UUIDBoxes:{},UUIDs:[],initialize:function(){l.FullBox.prototype=new l.Box,l.ContainerBox.prototype=new l.Box,l.SampleEntry.prototype=new l.Box,l.TrackGroupTypeBox.prototype=new l.FullBox,l.BASIC_BOXES.forEach(function(o){l.createBoxCtor(o.type,o.name)}),l.FULL_BOXES.forEach(function(o){l.createFullBoxCtor(o.type,o.name)}),l.CONTAINER_BOXES.forEach(function(o){l.createContainerBoxCtor(o[0].type,o[0].name,null,o[1])})},Box:function(o,c,f,m){this.type=o,this.box_name=f,this.size=c,this.uuid=m},FullBox:function(o,c,f,m){l.Box.call(this,o,c,f,m),this.flags=0,this.version=0},ContainerBox:function(o,c,f,m){l.Box.call(this,o,c,f,m),this.boxes=[]},SampleEntry:function(o,c,f,m){l.ContainerBox.call(this,o,c),this.hdr_size=f,this.start=m},SampleGroupEntry:function(o){this.grouping_type=o},TrackGroupTypeBox:function(o,c){l.FullBox.call(this,o,c)},createBoxCtor:function(o,c,f){l.boxCodes.push(o),l[o+"Box"]=function(m){l.Box.call(this,o,m,c)},l[o+"Box"].prototype=new l.Box,f&&(l[o+"Box"].prototype.parse=f)},createFullBoxCtor:function(o,c,f){l[o+"Box"]=function(m){l.FullBox.call(this,o,m,c)},l[o+"Box"].prototype=new l.FullBox,l[o+"Box"].prototype.parse=function(m){this.parseFullHeader(m),f&&f.call(this,m)}},addSubBoxArrays:function(o){if(o){this.subBoxNames=o;for(var c=o.length,f=0;f<c;f++)this[o[f]+"s"]=[]}},createContainerBoxCtor:function(o,c,f,m){l[o+"Box"]=function(S){l.ContainerBox.call(this,o,S,c),l.addSubBoxArrays.call(this,m)},l[o+"Box"].prototype=new l.ContainerBox,f&&(l[o+"Box"].prototype.parse=f)},createMediaSampleEntryCtor:function(o,c,f){l.sampleEntryCodes[o]=[],l[o+"SampleEntry"]=function(m,S){l.SampleEntry.call(this,m,S),l.addSubBoxArrays.call(this,f)},l[o+"SampleEntry"].prototype=new l.SampleEntry,c&&(l[o+"SampleEntry"].prototype.parse=c)},createSampleEntryCtor:function(o,c,f,m){l.sampleEntryCodes[o].push(c),l[c+"SampleEntry"]=function(S){l[o+"SampleEntry"].call(this,c,S),l.addSubBoxArrays.call(this,m)},l[c+"SampleEntry"].prototype=new l[o+"SampleEntry"],f&&(l[c+"SampleEntry"].prototype.parse=f)},createEncryptedSampleEntryCtor:function(o,c,f){l.createSampleEntryCtor.call(this,o,c,f,["sinf"])},createSampleGroupCtor:function(o,c){l[o+"SampleGroupEntry"]=function(f){l.SampleGroupEntry.call(this,o,f)},l[o+"SampleGroupEntry"].prototype=new l.SampleGroupEntry,c&&(l[o+"SampleGroupEntry"].prototype.parse=c)},createTrackGroupCtor:function(o,c){l[o+"TrackGroupTypeBox"]=function(f){l.TrackGroupTypeBox.call(this,o,f)},l[o+"TrackGroupTypeBox"].prototype=new l.TrackGroupTypeBox,c&&(l[o+"TrackGroupTypeBox"].prototype.parse=c)},createUUIDBox:function(o,c,f,m,S){l.UUIDs.push(o),l.UUIDBoxes[o]=function(T){f?l.FullBox.call(this,"uuid",T,c,o):m?l.ContainerBox.call(this,"uuid",T,c,o):l.Box.call(this,"uuid",T,c,o)},l.UUIDBoxes[o].prototype=f?new l.FullBox:m?new l.ContainerBox:new l.Box,S&&(f?l.UUIDBoxes[o].prototype.parse=function(T){this.parseFullHeader(T),S&&S.call(this,T)}:l.UUIDBoxes[o].prototype.parse=S)}};l.initialize(),l.TKHD_FLAG_ENABLED=1,l.TKHD_FLAG_IN_MOVIE=2,l.TKHD_FLAG_IN_PREVIEW=4,l.TFHD_FLAG_BASE_DATA_OFFSET=1,l.TFHD_FLAG_SAMPLE_DESC=2,l.TFHD_FLAG_SAMPLE_DUR=8,l.TFHD_FLAG_SAMPLE_SIZE=16,l.TFHD_FLAG_SAMPLE_FLAGS=32,l.TFHD_FLAG_DUR_EMPTY=65536,l.TFHD_FLAG_DEFAULT_BASE_IS_MOOF=131072,l.TRUN_FLAGS_DATA_OFFSET=1,l.TRUN_FLAGS_FIRST_FLAG=4,l.TRUN_FLAGS_DURATION=256,l.TRUN_FLAGS_SIZE=512,l.TRUN_FLAGS_FLAGS=1024,l.TRUN_FLAGS_CTS_OFFSET=2048,l.Box.prototype.add=function(o){return this.addBox(new l[o+"Box"])},l.Box.prototype.addBox=function(o){return this.boxes.push(o),this[o.type+"s"]?this[o.type+"s"].push(o):this[o.type]=o,o},l.Box.prototype.set=function(o,c){return this[o]=c,this},l.Box.prototype.addEntry=function(o,c){var f=c||"entries";return this[f]||(this[f]=[]),this[f].push(o),this},r.BoxParser=l,l.parseUUID=function(o){return l.parseHex16(o)},l.parseHex16=function(o){for(var c="",f=0;f<16;f++){var m=o.readUint8().toString(16);c+=m.length===1?"0"+m:m}return c},l.parseOneBox=function(o,c,f){var m,S=o.getPosition(),T=0,b,A;if(o.getEndPosition()-S<8)return e.debug("BoxParser","Not enough data in stream to parse the type and size of the box"),{code:l.ERR_NOT_ENOUGH_DATA};if(f&&f<8)return e.debug("BoxParser","Not enough bytes left in the parent box to parse a new box"),{code:l.ERR_NOT_ENOUGH_DATA};var I=o.readUint32(),L=o.readString(4),w=L;if(e.debug("BoxParser","Found box of type '"+L+"' and size "+I+" at position "+S),T=8,L=="uuid"){if(o.getEndPosition()-o.getPosition()<16||f-T<16)return o.seek(S),e.debug("BoxParser","Not enough bytes left in the parent box to parse a UUID box"),{code:l.ERR_NOT_ENOUGH_DATA};A=l.parseUUID(o),T+=16,w=A}if(I==1){if(o.getEndPosition()-o.getPosition()<8||f&&f-T<8)return o.seek(S),e.warn("BoxParser",'Not enough data in stream to parse the extended size of the "'+L+'" box'),{code:l.ERR_NOT_ENOUGH_DATA};I=o.readUint64(),T+=8}else if(I===0){if(f)I=f;else if(L!=="mdat")return e.error("BoxParser","Unlimited box size not supported for type: '"+L+"'"),m=new l.Box(L,I),{code:l.OK,box:m,size:m.size}}return I!==0&&I<T?(e.error("BoxParser","Box of type "+L+" has an invalid size "+I+" (too small to be a box)"),{code:l.ERR_NOT_ENOUGH_DATA,type:L,size:I,hdr_size:T,start:S}):I!==0&&f&&I>f?(e.error("BoxParser","Box of type '"+L+"' has a size "+I+" greater than its container size "+f),{code:l.ERR_NOT_ENOUGH_DATA,type:L,size:I,hdr_size:T,start:S}):I!==0&&S+I>o.getEndPosition()?(o.seek(S),e.info("BoxParser","Not enough data in stream to parse the entire '"+L+"' box"),{code:l.ERR_NOT_ENOUGH_DATA,type:L,size:I,hdr_size:T,start:S}):c?{code:l.OK,type:L,size:I,hdr_size:T,start:S}:(l[L+"Box"]?m=new l[L+"Box"](I):L!=="uuid"?(e.warn("BoxParser","Unknown box type: '"+L+"'"),m=new l.Box(L,I),m.has_unparsed_data=!0):l.UUIDBoxes[A]?m=new l.UUIDBoxes[A](I):(e.warn("BoxParser","Unknown uuid type: '"+A+"'"),m=new l.Box(L,I),m.uuid=A,m.has_unparsed_data=!0),m.hdr_size=T,m.start=S,m.write===l.Box.prototype.write&&m.type!=="mdat"&&(e.info("BoxParser","'"+w+"' box writing not yet implemented, keeping unparsed data in memory for later write"),m.parseDataAndRewind(o)),m.parse(o),b=o.getPosition()-(m.start+m.size),b<0?(e.warn("BoxParser","Parsing of box '"+w+"' did not read the entire indicated box data size (missing "+-b+" bytes), seeking forward"),o.seek(m.start+m.size)):b>0&&(e.error("BoxParser","Parsing of box '"+w+"' read "+b+" more bytes than the indicated box data size, seeking backwards"),m.size!==0&&o.seek(m.start+m.size)),{code:l.OK,box:m,size:m.size})},l.Box.prototype.parse=function(o){this.type!="mdat"?this.data=o.readUint8Array(this.size-this.hdr_size):this.size===0?o.seek(o.getEndPosition()):o.seek(this.start+this.size)},l.Box.prototype.parseDataAndRewind=function(o){this.data=o.readUint8Array(this.size-this.hdr_size),o.position-=this.size-this.hdr_size},l.FullBox.prototype.parseDataAndRewind=function(o){this.parseFullHeader(o),this.data=o.readUint8Array(this.size-this.hdr_size),this.hdr_size-=4,o.position-=this.size-this.hdr_size},l.FullBox.prototype.parseFullHeader=function(o){this.version=o.readUint8(),this.flags=o.readUint24(),this.hdr_size+=4},l.FullBox.prototype.parse=function(o){this.parseFullHeader(o),this.data=o.readUint8Array(this.size-this.hdr_size)},l.ContainerBox.prototype.parse=function(o){for(var c,f;o.getPosition()<this.start+this.size;)if(c=l.parseOneBox(o,!1,this.size-(o.getPosition()-this.start)),c.code===l.OK)if(f=c.box,this.boxes.push(f),this.subBoxNames&&this.subBoxNames.indexOf(f.type)!=-1)this[this.subBoxNames[this.subBoxNames.indexOf(f.type)]+"s"].push(f);else{var m=f.type!=="uuid"?f.type:f.uuid;this[m]?e.warn("Box of type "+m+" already stored in field of this type"):this[m]=f}else return},l.Box.prototype.parseLanguage=function(o){this.language=o.readUint16();var c=[];c[0]=this.language>>10&31,c[1]=this.language>>5&31,c[2]=this.language&31,this.languageString=String.fromCharCode(c[0]+96,c[1]+96,c[2]+96)},l.SAMPLE_ENTRY_TYPE_VISUAL="Visual",l.SAMPLE_ENTRY_TYPE_AUDIO="Audio",l.SAMPLE_ENTRY_TYPE_HINT="Hint",l.SAMPLE_ENTRY_TYPE_METADATA="Metadata",l.SAMPLE_ENTRY_TYPE_SUBTITLE="Subtitle",l.SAMPLE_ENTRY_TYPE_SYSTEM="System",l.SAMPLE_ENTRY_TYPE_TEXT="Text",l.SampleEntry.prototype.parseHeader=function(o){o.readUint8Array(6),this.data_reference_index=o.readUint16(),this.hdr_size+=8},l.SampleEntry.prototype.parse=function(o){this.parseHeader(o),this.data=o.readUint8Array(this.size-this.hdr_size)},l.SampleEntry.prototype.parseDataAndRewind=function(o){this.parseHeader(o),this.data=o.readUint8Array(this.size-this.hdr_size),this.hdr_size-=8,o.position-=this.size-this.hdr_size},l.SampleEntry.prototype.parseFooter=function(o){l.ContainerBox.prototype.parse.call(this,o)},l.createMediaSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_HINT),l.createMediaSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_METADATA),l.createMediaSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_SUBTITLE),l.createMediaSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_SYSTEM),l.createMediaSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_TEXT),l.createMediaSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,function(o){var c;this.parseHeader(o),o.readUint16(),o.readUint16(),o.readUint32Array(3),this.width=o.readUint16(),this.height=o.readUint16(),this.horizresolution=o.readUint32(),this.vertresolution=o.readUint32(),o.readUint32(),this.frame_count=o.readUint16(),c=Math.min(31,o.readUint8()),this.compressorname=o.readString(c),c<31&&o.readString(31-c),this.depth=o.readUint16(),o.readUint16(),this.parseFooter(o)}),l.createMediaSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_AUDIO,function(o){this.parseHeader(o),o.readUint32Array(2),this.channel_count=o.readUint16(),this.samplesize=o.readUint16(),o.readUint16(),o.readUint16(),this.samplerate=o.readUint32()/65536,this.parseFooter(o)}),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"avc1"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"avc2"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"avc3"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"avc4"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"av01"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"dav1"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"hvc1"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"hev1"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"hvt1"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"lhe1"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"dvh1"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"dvhe"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"vvc1"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"vvi1"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"vvs1"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"vvcN"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"vp08"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"vp09"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"avs3"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"j2ki"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"mjp2"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"mjpg"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"uncv"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_AUDIO,"mp4a"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_AUDIO,"ac-3"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_AUDIO,"ac-4"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_AUDIO,"ec-3"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_AUDIO,"Opus"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_AUDIO,"mha1"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_AUDIO,"mha2"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_AUDIO,"mhm1"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_AUDIO,"mhm2"),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_AUDIO,"fLaC"),l.createEncryptedSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_VISUAL,"encv"),l.createEncryptedSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_AUDIO,"enca"),l.createEncryptedSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_SUBTITLE,"encu"),l.createEncryptedSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_SYSTEM,"encs"),l.createEncryptedSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_TEXT,"enct"),l.createEncryptedSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_METADATA,"encm"),l.createBoxCtor("a1lx","AV1LayeredImageIndexingProperty",function(o){var c=o.readUint8()&1,f=((c&1)+1)*16;this.layer_size=[];for(var m=0;m<3;m++)f==16?this.layer_size[m]=o.readUint16():this.layer_size[m]=o.readUint32()}),l.createBoxCtor("a1op","OperatingPointSelectorProperty",function(o){this.op_index=o.readUint8()}),l.createFullBoxCtor("auxC","AuxiliaryTypeProperty",function(o){this.aux_type=o.readCString();var c=this.size-this.hdr_size-(this.aux_type.length+1);this.aux_subtype=o.readUint8Array(c)}),l.createBoxCtor("av1C","AV1CodecConfigurationBox",function(o){var c=o.readUint8();if((c>>7&1)!==1){e.error("av1C marker problem");return}if(this.version=c&127,this.version!==1){e.error("av1C version "+this.version+" not supported");return}if(c=o.readUint8(),this.seq_profile=c>>5&7,this.seq_level_idx_0=c&31,c=o.readUint8(),this.seq_tier_0=c>>7&1,this.high_bitdepth=c>>6&1,this.twelve_bit=c>>5&1,this.monochrome=c>>4&1,this.chroma_subsampling_x=c>>3&1,this.chroma_subsampling_y=c>>2&1,this.chroma_sample_position=c&3,c=o.readUint8(),this.reserved_1=c>>5&7,this.reserved_1!==0){e.error("av1C reserved_1 parsing problem");return}if(this.initial_presentation_delay_present=c>>4&1,this.initial_presentation_delay_present===1)this.initial_presentation_delay_minus_one=c&15;else if(this.reserved_2=c&15,this.reserved_2!==0){e.error("av1C reserved_2 parsing problem");return}var f=this.size-this.hdr_size-4;this.configOBUs=o.readUint8Array(f)});function u(o){var c="<table class='inner-table'>";c+="<thead><tr><th>length</th><th>nalu_data</th></tr></thead>",c+="<tbody>";for(var f=0;f<o.length;f++){var m=o[f];c+="<tr>",c+="<td>"+m.length+"</td>",c+="<td>",c+=m.nalu.reduce(function(S,T){return S+T.toString(16).padStart(2,"0")},"0x"),c+="</td></tr>"}return c+="</tbody></table>",c}l.createBoxCtor("avcC","AVCConfigurationBox",function(o){var c,f;for(this.configurationVersion=o.readUint8(),this.AVCProfileIndication=o.readUint8(),this.profile_compatibility=o.readUint8(),this.AVCLevelIndication=o.readUint8(),this.lengthSizeMinusOne=o.readUint8()&3,this.nb_SPS_nalus=o.readUint8()&31,f=this.size-this.hdr_size-6,this.SPS=[],this.SPS.toString=function(){return u(this)},c=0;c<this.nb_SPS_nalus;c++)this.SPS[c]={},this.SPS[c].length=o.readUint16(),this.SPS[c].nalu=o.readUint8Array(this.SPS[c].length),f-=2+this.SPS[c].length;for(this.nb_PPS_nalus=o.readUint8(),f--,this.PPS=[],this.PPS.toString=function(){return u(this)},c=0;c<this.nb_PPS_nalus;c++)this.PPS[c]={},this.PPS[c].length=o.readUint16(),this.PPS[c].nalu=o.readUint8Array(this.PPS[c].length),f-=2+this.PPS[c].length;f>0&&(this.ext=o.readUint8Array(f))}),l.createBoxCtor("btrt","BitRateBox",function(o){this.bufferSizeDB=o.readUint32(),this.maxBitrate=o.readUint32(),this.avgBitrate=o.readUint32()}),l.createFullBoxCtor("ccst","CodingConstraintsBox",function(o){var c=o.readUint8();this.all_ref_pics_intra=(c&128)==128,this.intra_pred_used=(c&64)==64,this.max_ref_per_pic=(c&63)>>2,o.readUint24()}),l.createBoxCtor("cdef","ComponentDefinitionBox",function(o){var c;for(this.channel_count=o.readUint16(),this.channel_indexes=[],this.channel_types=[],this.channel_associations=[],c=0;c<this.channel_count;c++)this.channel_indexes.push(o.readUint16()),this.channel_types.push(o.readUint16()),this.channel_associations.push(o.readUint16())}),l.createBoxCtor("clap","CleanApertureBox",function(o){this.cleanApertureWidthN=o.readUint32(),this.cleanApertureWidthD=o.readUint32(),this.cleanApertureHeightN=o.readUint32(),this.cleanApertureHeightD=o.readUint32(),this.horizOffN=o.readUint32(),this.horizOffD=o.readUint32(),this.vertOffN=o.readUint32(),this.vertOffD=o.readUint32()}),l.createBoxCtor("clli","ContentLightLevelBox",function(o){this.max_content_light_level=o.readUint16(),this.max_pic_average_light_level=o.readUint16()}),l.createFullBoxCtor("cmex","CameraExtrinsicMatrixProperty",function(o){this.flags&1&&(this.pos_x=o.readInt32()),this.flags&2&&(this.pos_y=o.readInt32()),this.flags&4&&(this.pos_z=o.readInt32()),this.flags&8&&(this.version==0?this.flags&16?(this.quat_x=o.readInt32(),this.quat_y=o.readInt32(),this.quat_z=o.readInt32()):(this.quat_x=o.readInt16(),this.quat_y=o.readInt16(),this.quat_z=o.readInt16()):this.version==1),this.flags&32&&(this.id=o.readUint32())}),l.createFullBoxCtor("cmin","CameraIntrinsicMatrixProperty",function(o){this.focal_length_x=o.readInt32(),this.principal_point_x=o.readInt32(),this.principal_point_y=o.readInt32(),this.flags&1&&(this.focal_length_y=o.readInt32(),this.skew_factor=o.readInt32())}),l.createBoxCtor("cmpd","ComponentDefinitionBox",function(o){for(this.component_count=o.readUint32(),this.component_types=[],this.component_type_urls=[],i=0;i<this.component_count;i++){var c=o.readUint16();this.component_types.push(c),c>=32768&&this.component_type_urls.push(o.readCString())}}),l.createFullBoxCtor("co64","ChunkLargeOffsetBox",function(o){var c,f;if(c=o.readUint32(),this.chunk_offsets=[],this.version===0)for(f=0;f<c;f++)this.chunk_offsets.push(o.readUint64())}),l.createFullBoxCtor("CoLL","ContentLightLevelBox",function(o){this.maxCLL=o.readUint16(),this.maxFALL=o.readUint16()}),l.createBoxCtor("colr","ColourInformationBox",function(o){if(this.colour_type=o.readString(4),this.colour_type==="nclx"){this.colour_primaries=o.readUint16(),this.transfer_characteristics=o.readUint16(),this.matrix_coefficients=o.readUint16();var c=o.readUint8();this.full_range_flag=c>>7}else this.colour_type==="rICC"?this.ICC_profile=o.readUint8Array(this.size-4):this.colour_type==="prof"&&(this.ICC_profile=o.readUint8Array(this.size-4))}),l.createFullBoxCtor("cprt","CopyrightBox",function(o){this.parseLanguage(o),this.notice=o.readCString()}),l.createFullBoxCtor("cslg","CompositionToDecodeBox",function(o){this.version===0&&(this.compositionToDTSShift=o.readInt32(),this.leastDecodeToDisplayDelta=o.readInt32(),this.greatestDecodeToDisplayDelta=o.readInt32(),this.compositionStartTime=o.readInt32(),this.compositionEndTime=o.readInt32())}),l.createFullBoxCtor("ctts","CompositionOffsetBox",function(o){var c,f;if(c=o.readUint32(),this.sample_counts=[],this.sample_offsets=[],this.version===0)for(f=0;f<c;f++){this.sample_counts.push(o.readUint32());var m=o.readInt32();m<0&&e.warn("BoxParser","ctts box uses negative values without using version 1"),this.sample_offsets.push(m)}else if(this.version==1)for(f=0;f<c;f++)this.sample_counts.push(o.readUint32()),this.sample_offsets.push(o.readInt32())}),l.createBoxCtor("dac3","AC3SpecificBox",function(o){var c=o.readUint8(),f=o.readUint8(),m=o.readUint8();this.fscod=c>>6,this.bsid=c>>1&31,this.bsmod=(c&1)<<2|f>>6&3,this.acmod=f>>3&7,this.lfeon=f>>2&1,this.bit_rate_code=f&3|m>>5&7}),l.createBoxCtor("dec3","EC3SpecificBox",function(o){var c=o.readUint16();this.data_rate=c>>3,this.num_ind_sub=c&7,this.ind_subs=[];for(var f=0;f<this.num_ind_sub+1;f++){var m={};this.ind_subs.push(m);var S=o.readUint8(),T=o.readUint8(),b=o.readUint8();m.fscod=S>>6,m.bsid=S>>1&31,m.bsmod=(S&1)<<4|T>>4&15,m.acmod=T>>1&7,m.lfeon=T&1,m.num_dep_sub=b>>1&15,m.num_dep_sub>0&&(m.chan_loc=(b&1)<<8|o.readUint8())}}),l.createFullBoxCtor("dfLa","FLACSpecificBox",function(o){var c=127,f=128,m=[],S=["STREAMINFO","PADDING","APPLICATION","SEEKTABLE","VORBIS_COMMENT","CUESHEET","PICTURE","RESERVED"];do{var T=o.readUint8(),b=Math.min(T&c,S.length-1);if(b?o.readUint8Array(o.readUint24()):(o.readUint8Array(13),this.samplerate=o.readUint32()>>12,o.readUint8Array(20)),m.push(S[b]),T&f)break}while(!0);this.numMetadataBlocks=m.length+" ("+m.join(", ")+")"}),l.createBoxCtor("dimm","hintimmediateBytesSent",function(o){this.bytessent=o.readUint64()}),l.createBoxCtor("dmax","hintlongestpacket",function(o){this.time=o.readUint32()}),l.createBoxCtor("dmed","hintmediaBytesSent",function(o){this.bytessent=o.readUint64()}),l.createBoxCtor("dOps","OpusSpecificBox",function(o){if(this.Version=o.readUint8(),this.OutputChannelCount=o.readUint8(),this.PreSkip=o.readUint16(),this.InputSampleRate=o.readUint32(),this.OutputGain=o.readInt16(),this.ChannelMappingFamily=o.readUint8(),this.ChannelMappingFamily!==0){this.StreamCount=o.readUint8(),this.CoupledCount=o.readUint8(),this.ChannelMapping=[];for(var c=0;c<this.OutputChannelCount;c++)this.ChannelMapping[c]=o.readUint8()}}),l.createFullBoxCtor("dref","DataReferenceBox",function(o){var c,f;this.entries=[];for(var m=o.readUint32(),S=0;S<m;S++)if(c=l.parseOneBox(o,!1,this.size-(o.getPosition()-this.start)),c.code===l.OK)f=c.box,this.entries.push(f);else return}),l.createBoxCtor("drep","hintrepeatedBytesSent",function(o){this.bytessent=o.readUint64()}),l.createFullBoxCtor("elng","ExtendedLanguageBox",function(o){this.extended_language=o.readString(this.size-this.hdr_size)}),l.createFullBoxCtor("elst","EditListBox",function(o){this.entries=[];for(var c=o.readUint32(),f=0;f<c;f++){var m={};this.entries.push(m),this.version===1?(m.segment_duration=o.readUint64(),m.media_time=o.readInt64()):(m.segment_duration=o.readUint32(),m.media_time=o.readInt32()),m.media_rate_integer=o.readInt16(),m.media_rate_fraction=o.readInt16()}}),l.createFullBoxCtor("emsg","EventMessageBox",function(o){this.version==1?(this.timescale=o.readUint32(),this.presentation_time=o.readUint64(),this.event_duration=o.readUint32(),this.id=o.readUint32(),this.scheme_id_uri=o.readCString(),this.value=o.readCString()):(this.scheme_id_uri=o.readCString(),this.value=o.readCString(),this.timescale=o.readUint32(),this.presentation_time_delta=o.readUint32(),this.event_duration=o.readUint32(),this.id=o.readUint32());var c=this.size-this.hdr_size-(4*4+(this.scheme_id_uri.length+1)+(this.value.length+1));this.version==1&&(c-=4),this.message_data=o.readUint8Array(c)}),l.createEntityToGroupCtor=function(o,c){l[o+"Box"]=function(f){l.FullBox.call(this,o,f)},l[o+"Box"].prototype=new l.FullBox,l[o+"Box"].prototype.parse=function(f){if(this.parseFullHeader(f),c)c.call(this,f);else for(this.group_id=f.readUint32(),this.num_entities_in_group=f.readUint32(),this.entity_ids=[],i=0;i<this.num_entities_in_group;i++){var m=f.readUint32();this.entity_ids.push(m)}}},l.createEntityToGroupCtor("aebr"),l.createEntityToGroupCtor("afbr"),l.createEntityToGroupCtor("albc"),l.createEntityToGroupCtor("altr"),l.createEntityToGroupCtor("brst"),l.createEntityToGroupCtor("dobr"),l.createEntityToGroupCtor("eqiv"),l.createEntityToGroupCtor("favc"),l.createEntityToGroupCtor("fobr"),l.createEntityToGroupCtor("iaug"),l.createEntityToGroupCtor("pano"),l.createEntityToGroupCtor("slid"),l.createEntityToGroupCtor("ster"),l.createEntityToGroupCtor("tsyn"),l.createEntityToGroupCtor("wbbr"),l.createEntityToGroupCtor("prgr"),l.createEntityToGroupCtor("pymd",function(o){this.group_id=o.readUint32(),this.num_entities_in_group=o.readUint32(),this.entity_ids=[];for(var c=0;c<this.num_entities_in_group;c++){var f=o.readUint32();this.entity_ids.push(f)}for(this.tile_size_x=o.readUint16(),this.tile_size_y=o.readUint16(),this.layer_binning=[],this.tiles_in_layer_column_minus1=[],this.tiles_in_layer_row_minus1=[],c=0;c<this.num_entities_in_group;c++)this.layer_binning[c]=o.readUint16(),this.tiles_in_layer_row_minus1[c]=o.readUint16(),this.tiles_in_layer_column_minus1[c]=o.readUint16()}),l.createFullBoxCtor("esds","ElementaryStreamDescriptorBox",function(o){var c=o.readUint8Array(this.size-this.hdr_size);if(typeof h<"u"){var f=new h;this.esd=f.parseOneDescriptor(new s(c.buffer,0,s.BIG_ENDIAN))}}),l.createBoxCtor("fiel","FieldHandlingBox",function(o){this.fieldCount=o.readUint8(),this.fieldOrdering=o.readUint8()}),l.createBoxCtor("frma","OriginalFormatBox",function(o){this.data_format=o.readString(4)}),l.createBoxCtor("ftyp","FileTypeBox",function(o){var c=this.size-this.hdr_size;this.major_brand=o.readString(4),this.minor_version=o.readUint32(),c-=8,this.compatible_brands=[];for(var f=0;c>=4;)this.compatible_brands[f]=o.readString(4),c-=4,f++}),l.createFullBoxCtor("hdlr","HandlerBox",function(o){this.version===0&&(o.readUint32(),this.handler=o.readString(4),o.readUint32Array(3),this.name=o.readString(this.size-this.hdr_size-20),this.name[this.name.length-1]==="\0"&&(this.name=this.name.slice(0,-1)))}),l.createBoxCtor("hvcC","HEVCConfigurationBox",function(o){var c,f,m,S;this.configurationVersion=o.readUint8(),S=o.readUint8(),this.general_profile_space=S>>6,this.general_tier_flag=(S&32)>>5,this.general_profile_idc=S&31,this.general_profile_compatibility=o.readUint32(),this.general_constraint_indicator=o.readUint8Array(6),this.general_level_idc=o.readUint8(),this.min_spatial_segmentation_idc=o.readUint16()&4095,this.parallelismType=o.readUint8()&3,this.chroma_format_idc=o.readUint8()&3,this.bit_depth_luma_minus8=o.readUint8()&7,this.bit_depth_chroma_minus8=o.readUint8()&7,this.avgFrameRate=o.readUint16(),S=o.readUint8(),this.constantFrameRate=S>>6,this.numTemporalLayers=(S&13)>>3,this.temporalIdNested=(S&4)>>2,this.lengthSizeMinusOne=S&3,this.nalu_arrays=[],this.nalu_arrays.toString=function(){var L="<table class='inner-table'>";L+="<thead><tr><th>completeness</th><th>nalu_type</th><th>nalu_data</th></tr></thead>",L+="<tbody>";for(var w=0;w<this.length;w++){var R=this[w];L+="<tr>",L+="<td rowspan='"+R.length+"'>"+R.completeness+"</td>",L+="<td rowspan='"+R.length+"'>"+R.nalu_type+"</td>";for(var M=0;M<R.length;M++){var k=R[M];M!==0&&(L+="<tr>"),L+="<td>",L+=k.data.reduce(function(z,O){return z+O.toString(16).padStart(2,"0")},"0x"),L+="</td></tr>"}}return L+="</tbody></table>",L};var T=o.readUint8();for(c=0;c<T;c++){var b=[];this.nalu_arrays.push(b),S=o.readUint8(),b.completeness=(S&128)>>7,b.nalu_type=S&63;var A=o.readUint16();for(f=0;f<A;f++){var I={};b.push(I),m=o.readUint16(),I.data=o.readUint8Array(m)}}}),l.createFullBoxCtor("iinf","ItemInfoBox",function(o){var c;this.version===0?this.entry_count=o.readUint16():this.entry_count=o.readUint32(),this.item_infos=[];for(var f=0;f<this.entry_count;f++)if(c=l.parseOneBox(o,!1,this.size-(o.getPosition()-this.start)),c.code===l.OK)c.box.type!=="infe"&&e.error("BoxParser","Expected 'infe' box, got "+c.box.type),this.item_infos[f]=c.box;else return}),l.createFullBoxCtor("iloc","ItemLocationBox",function(o){var c;c=o.readUint8(),this.offset_size=c>>4&15,this.length_size=c&15,c=o.readUint8(),this.base_offset_size=c>>4&15,this.version===1||this.version===2?this.index_size=c&15:this.index_size=0,this.items=[];var f=0;if(this.version<2)f=o.readUint16();else if(this.version===2)f=o.readUint32();else throw"version of iloc box not supported";for(var m=0;m<f;m++){var S={};if(this.items.push(S),this.version<2)S.item_ID=o.readUint16();else if(this.version===2)S.item_ID=o.readUint32();else throw"version of iloc box not supported";switch(this.version===1||this.version===2?S.construction_method=o.readUint16()&15:S.construction_method=0,S.data_reference_index=o.readUint16(),this.base_offset_size){case 0:S.base_offset=0;break;case 4:S.base_offset=o.readUint32();break;case 8:S.base_offset=o.readUint64();break;default:throw"Error reading base offset size"}var T=o.readUint16();S.extents=[];for(var b=0;b<T;b++){var A={};if(S.extents.push(A),this.version===1||this.version===2)switch(this.index_size){case 0:A.extent_index=0;break;case 4:A.extent_index=o.readUint32();break;case 8:A.extent_index=o.readUint64();break;default:throw"Error reading extent index"}switch(this.offset_size){case 0:A.extent_offset=0;break;case 4:A.extent_offset=o.readUint32();break;case 8:A.extent_offset=o.readUint64();break;default:throw"Error reading extent index"}switch(this.length_size){case 0:A.extent_length=0;break;case 4:A.extent_length=o.readUint32();break;case 8:A.extent_length=o.readUint64();break;default:throw"Error reading extent index"}}}}),l.createBoxCtor("imir","ImageMirror",function(o){var c=o.readUint8();this.reserved=c>>7,this.axis=c&1}),l.createFullBoxCtor("infe","ItemInfoEntry",function(o){if((this.version===0||this.version===1)&&(this.item_ID=o.readUint16(),this.item_protection_index=o.readUint16(),this.item_name=o.readCString(),this.content_type=o.readCString(),this.content_encoding=o.readCString()),this.version===1){this.extension_type=o.readString(4),e.warn("BoxParser","Cannot parse extension type"),o.seek(this.start+this.size);return}this.version>=2&&(this.version===2?this.item_ID=o.readUint16():this.version===3&&(this.item_ID=o.readUint32()),this.item_protection_index=o.readUint16(),this.item_type=o.readString(4),this.item_name=o.readCString(),this.item_type==="mime"?(this.content_type=o.readCString(),this.content_encoding=o.readCString()):this.item_type==="uri "&&(this.item_uri_type=o.readCString()))}),l.createFullBoxCtor("ipma","ItemPropertyAssociationBox",function(o){var c,f;for(entry_count=o.readUint32(),this.associations=[],c=0;c<entry_count;c++){var m={};this.associations.push(m),this.version<1?m.id=o.readUint16():m.id=o.readUint32();var S=o.readUint8();for(m.props=[],f=0;f<S;f++){var T=o.readUint8(),b={};m.props.push(b),b.essential=(T&128)>>7===1,this.flags&1?b.property_index=(T&127)<<8|o.readUint8():b.property_index=T&127}}}),l.createFullBoxCtor("iref","ItemReferenceBox",function(o){var c,f;for(this.references=[];o.getPosition()<this.start+this.size;)if(c=l.parseOneBox(o,!0,this.size-(o.getPosition()-this.start)),c.code===l.OK)this.version===0?f=new l.SingleItemTypeReferenceBox(c.type,c.size,c.hdr_size,c.start):f=new l.SingleItemTypeReferenceBoxLarge(c.type,c.size,c.hdr_size,c.start),f.write===l.Box.prototype.write&&f.type!=="mdat"&&(e.warn("BoxParser",f.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),f.parseDataAndRewind(o)),f.parse(o),this.references.push(f);else return}),l.createBoxCtor("irot","ImageRotation",function(o){this.angle=o.readUint8()&3}),l.createFullBoxCtor("ispe","ImageSpatialExtentsProperty",function(o){this.image_width=o.readUint32(),this.image_height=o.readUint32()}),l.createFullBoxCtor("kind","KindBox",function(o){this.schemeURI=o.readCString(),this.value=o.readCString()}),l.createFullBoxCtor("leva","LevelAssignmentBox",function(o){var c=o.readUint8();this.levels=[];for(var f=0;f<c;f++){var m={};this.levels[f]=m,m.track_ID=o.readUint32();var S=o.readUint8();switch(m.padding_flag=S>>7,m.assignment_type=S&127,m.assignment_type){case 0:m.grouping_type=o.readString(4);break;case 1:m.grouping_type=o.readString(4),m.grouping_type_parameter=o.readUint32();break;case 2:break;case 3:break;case 4:m.sub_track_id=o.readUint32();break;default:e.warn("BoxParser","Unknown leva assignement type")}}}),l.createBoxCtor("lhvC","LHEVCConfigurationBox",function(o){var c,f,m;this.configurationVersion=o.readUint8(),this.min_spatial_segmentation_idc=o.readUint16()&4095,this.parallelismType=o.readUint8()&3,m=o.readUint8(),this.numTemporalLayers=(m&13)>>3,this.temporalIdNested=(m&4)>>2,this.lengthSizeMinusOne=m&3,this.nalu_arrays=[],this.nalu_arrays.toString=function(){var L="<table class='inner-table'>";L+="<thead><tr><th>completeness</th><th>nalu_type</th><th>nalu_data</th></tr></thead>",L+="<tbody>";for(var w=0;w<this.length;w++){var R=this[w];L+="<tr>",L+="<td rowspan='"+R.length+"'>"+R.completeness+"</td>",L+="<td rowspan='"+R.length+"'>"+R.nalu_type+"</td>";for(var M=0;M<R.length;M++){var k=R[M];M!==0&&(L+="<tr>"),L+="<td>",L+=k.data.reduce(function(z,O){return z+O.toString(16).padStart(2,"0")},"0x"),L+="</td></tr>"}}return L+="</tbody></table>",L};var S=o.readUint8();for(c=0;c<S;c++){var T=[];this.nalu_arrays.push(T),m=o.readUint8(),T.completeness=(m&128)>>7,T.nalu_type=m&63;var b=o.readUint16();for(f=0;f<b;f++){var A={};T.push(A);var I=o.readUint16();A.data=o.readUint8Array(I)}}}),l.createBoxCtor("lsel","LayerSelectorProperty",function(o){this.layer_id=o.readUint16()}),l.createBoxCtor("maxr","hintmaxrate",function(o){this.period=o.readUint32(),this.bytes=o.readUint32()});function d(o,c){this.x=o,this.y=c}d.prototype.toString=function(){return"("+this.x+","+this.y+")"},l.createBoxCtor("mdcv","MasteringDisplayColourVolumeBox",function(o){this.display_primaries=[],this.display_primaries[0]=new d(o.readUint16(),o.readUint16()),this.display_primaries[1]=new d(o.readUint16(),o.readUint16()),this.display_primaries[2]=new d(o.readUint16(),o.readUint16()),this.white_point=new d(o.readUint16(),o.readUint16()),this.max_display_mastering_luminance=o.readUint32(),this.min_display_mastering_luminance=o.readUint32()}),l.createFullBoxCtor("mdhd","MediaHeaderBox",function(o){this.version==1?(this.creation_time=o.readUint64(),this.modification_time=o.readUint64(),this.timescale=o.readUint32(),this.duration=o.readUint64()):(this.creation_time=o.readUint32(),this.modification_time=o.readUint32(),this.timescale=o.readUint32(),this.duration=o.readUint32()),this.parseLanguage(o),o.readUint16()}),l.createFullBoxCtor("mehd","MovieExtendsHeaderBox",function(o){this.flags&1&&(e.warn("BoxParser","mehd box incorrectly uses flags set to 1, converting version to 1"),this.version=1),this.version==1?this.fragment_duration=o.readUint64():this.fragment_duration=o.readUint32()}),l.createFullBoxCtor("meta","MetaBox",function(o){this.boxes=[],l.ContainerBox.prototype.parse.call(this,o)}),l.createFullBoxCtor("mfhd","MovieFragmentHeaderBox",function(o){this.sequence_number=o.readUint32()}),l.createFullBoxCtor("mfro","MovieFragmentRandomAccessOffsetBox",function(o){this._size=o.readUint32()}),l.createFullBoxCtor("mskC","MaskConfigurationProperty",function(o){this.bits_per_pixel=o.readUint8()}),l.createFullBoxCtor("mvhd","MovieHeaderBox",function(o){this.version==1?(this.creation_time=o.readUint64(),this.modification_time=o.readUint64(),this.timescale=o.readUint32(),this.duration=o.readUint64()):(this.creation_time=o.readUint32(),this.modification_time=o.readUint32(),this.timescale=o.readUint32(),this.duration=o.readUint32()),this.rate=o.readUint32(),this.volume=o.readUint16()>>8,o.readUint16(),o.readUint32Array(2),this.matrix=o.readUint32Array(9),o.readUint32Array(6),this.next_track_id=o.readUint32()}),l.createBoxCtor("npck","hintPacketsSent",function(o){this.packetssent=o.readUint32()}),l.createBoxCtor("nump","hintPacketsSent",function(o){this.packetssent=o.readUint64()}),l.createFullBoxCtor("padb","PaddingBitsBox",function(o){var c=o.readUint32();this.padbits=[];for(var f=0;f<Math.floor((c+1)/2);f++)this.padbits=o.readUint8()}),l.createBoxCtor("pasp","PixelAspectRatioBox",function(o){this.hSpacing=o.readUint32(),this.vSpacing=o.readUint32()}),l.createBoxCtor("payl","CuePayloadBox",function(o){this.text=o.readString(this.size-this.hdr_size)}),l.createBoxCtor("payt","hintpayloadID",function(o){this.payloadID=o.readUint32();var c=o.readUint8();this.rtpmap_string=o.readString(c)}),l.createFullBoxCtor("pdin","ProgressiveDownloadInfoBox",function(o){var c=(this.size-this.hdr_size)/8;this.rate=[],this.initial_delay=[];for(var f=0;f<c;f++)this.rate[f]=o.readUint32(),this.initial_delay[f]=o.readUint32()}),l.createFullBoxCtor("pitm","PrimaryItemBox",function(o){this.version===0?this.item_id=o.readUint16():this.item_id=o.readUint32()}),l.createFullBoxCtor("pixi","PixelInformationProperty",function(o){var c;for(this.num_channels=o.readUint8(),this.bits_per_channels=[],c=0;c<this.num_channels;c++)this.bits_per_channels[c]=o.readUint8()}),l.createBoxCtor("pmax","hintlargestpacket",function(o){this.bytes=o.readUint32()}),l.createFullBoxCtor("prdi","ProgressiveDerivedImageItemInformationProperty",function(o){if(this.step_count=o.readUint16(),this.item_count=[],this.flags&2)for(var c=0;c<this.step_count;c++)this.item_count[c]=o.readUint16()}),l.createFullBoxCtor("prft","ProducerReferenceTimeBox",function(o){this.ref_track_id=o.readUint32(),this.ntp_timestamp=o.readUint64(),this.version===0?this.media_time=o.readUint32():this.media_time=o.readUint64()}),l.createFullBoxCtor("pssh","ProtectionSystemSpecificHeaderBox",function(o){if(this.system_id=l.parseHex16(o),this.version>0){var c=o.readUint32();this.kid=[];for(var f=0;f<c;f++)this.kid[f]=l.parseHex16(o)}var m=o.readUint32();m>0&&(this.data=o.readUint8Array(m))}),l.createFullBoxCtor("clef","TrackCleanApertureDimensionsBox",function(o){this.width=o.readUint32(),this.height=o.readUint32()}),l.createFullBoxCtor("enof","TrackEncodedPixelsDimensionsBox",function(o){this.width=o.readUint32(),this.height=o.readUint32()}),l.createFullBoxCtor("prof","TrackProductionApertureDimensionsBox",function(o){this.width=o.readUint32(),this.height=o.readUint32()}),l.createContainerBoxCtor("tapt","TrackApertureModeDimensionsBox",null,["clef","prof","enof"]),l.createBoxCtor("rtp ","rtpmoviehintinformation",function(o){this.descriptionformat=o.readString(4),this.sdptext=o.readString(this.size-this.hdr_size-4)}),l.createFullBoxCtor("saio","SampleAuxiliaryInformationOffsetsBox",function(o){this.flags&1&&(this.aux_info_type=o.readString(4),this.aux_info_type_parameter=o.readUint32());var c=o.readUint32();this.offset=[];for(var f=0;f<c;f++)this.version===0?this.offset[f]=o.readUint32():this.offset[f]=o.readUint64()}),l.createFullBoxCtor("saiz","SampleAuxiliaryInformationSizesBox",function(o){if(this.flags&1&&(this.aux_info_type=o.readString(4),this.aux_info_type_parameter=o.readUint32()),this.default_sample_info_size=o.readUint8(),this.sample_count=o.readUint32(),this.sample_info_size=[],this.default_sample_info_size===0)for(var c=0;c<this.sample_count;c++)this.sample_info_size[c]=o.readUint8()}),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_METADATA,"mett",function(o){this.parseHeader(o),this.content_encoding=o.readCString(),this.mime_format=o.readCString(),this.parseFooter(o)}),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_METADATA,"metx",function(o){this.parseHeader(o),this.content_encoding=o.readCString(),this.namespace=o.readCString(),this.schema_location=o.readCString(),this.parseFooter(o)}),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_SUBTITLE,"sbtt",function(o){this.parseHeader(o),this.content_encoding=o.readCString(),this.mime_format=o.readCString(),this.parseFooter(o)}),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_SUBTITLE,"stpp",function(o){this.parseHeader(o),this.namespace=o.readCString(),this.schema_location=o.readCString(),this.auxiliary_mime_types=o.readCString(),this.parseFooter(o)}),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_SUBTITLE,"stxt",function(o){this.parseHeader(o),this.content_encoding=o.readCString(),this.mime_format=o.readCString(),this.parseFooter(o)}),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_SUBTITLE,"tx3g",function(o){this.parseHeader(o),this.displayFlags=o.readUint32(),this.horizontal_justification=o.readInt8(),this.vertical_justification=o.readInt8(),this.bg_color_rgba=o.readUint8Array(4),this.box_record=o.readInt16Array(4),this.style_record=o.readUint8Array(12),this.parseFooter(o)}),l.createSampleEntryCtor(l.SAMPLE_ENTRY_TYPE_METADATA,"wvtt",function(o){this.parseHeader(o),this.parseFooter(o)}),l.createSampleGroupCtor("alst",function(o){var c,f=o.readUint16();for(this.first_output_sample=o.readUint16(),this.sample_offset=[],c=0;c<f;c++)this.sample_offset[c]=o.readUint32();var m=this.description_length-4-4*f;for(this.num_output_samples=[],this.num_total_samples=[],c=0;c<m/4;c++)this.num_output_samples[c]=o.readUint16(),this.num_total_samples[c]=o.readUint16()}),l.createSampleGroupCtor("avll",function(o){this.layerNumber=o.readUint8(),this.accurateStatisticsFlag=o.readUint8(),this.avgBitRate=o.readUint16(),this.avgFrameRate=o.readUint16()}),l.createSampleGroupCtor("avss",function(o){this.subSequenceIdentifier=o.readUint16(),this.layerNumber=o.readUint8();var c=o.readUint8();this.durationFlag=c>>7,this.avgRateFlag=c>>6&1,this.durationFlag&&(this.duration=o.readUint32()),this.avgRateFlag&&(this.accurateStatisticsFlag=o.readUint8(),this.avgBitRate=o.readUint16(),this.avgFrameRate=o.readUint16()),this.dependency=[];for(var f=o.readUint8(),m=0;m<f;m++){var S={};this.dependency.push(S),S.subSeqDirectionFlag=o.readUint8(),S.layerNumber=o.readUint8(),S.subSequenceIdentifier=o.readUint16()}}),l.createSampleGroupCtor("dtrt",function(o){e.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),l.createSampleGroupCtor("mvif",function(o){e.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),l.createSampleGroupCtor("prol",function(o){this.roll_distance=o.readInt16()}),l.createSampleGroupCtor("rap ",function(o){var c=o.readUint8();this.num_leading_samples_known=c>>7,this.num_leading_samples=c&127}),l.createSampleGroupCtor("rash",function(o){if(this.operation_point_count=o.readUint16(),this.description_length!==2+(this.operation_point_count===1?2:this.operation_point_count*6)+9)e.warn("BoxParser","Mismatch in "+this.grouping_type+" sample group length"),this.data=o.readUint8Array(this.description_length-2);else{if(this.operation_point_count===1)this.target_rate_share=o.readUint16();else{this.target_rate_share=[],this.available_bitrate=[];for(var c=0;c<this.operation_point_count;c++)this.available_bitrate[c]=o.readUint32(),this.target_rate_share[c]=o.readUint16()}this.maximum_bitrate=o.readUint32(),this.minimum_bitrate=o.readUint32(),this.discard_priority=o.readUint8()}}),l.createSampleGroupCtor("roll",function(o){this.roll_distance=o.readInt16()}),l.SampleGroupEntry.prototype.parse=function(o){e.warn("BoxParser","Unknown Sample Group type: "+this.grouping_type),this.data=o.readUint8Array(this.description_length)},l.createSampleGroupCtor("scif",function(o){e.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),l.createSampleGroupCtor("scnm",function(o){e.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),l.createSampleGroupCtor("seig",function(o){this.reserved=o.readUint8();var c=o.readUint8();this.crypt_byte_block=c>>4,this.skip_byte_block=c&15,this.isProtected=o.readUint8(),this.Per_Sample_IV_Size=o.readUint8(),this.KID=l.parseHex16(o),this.constant_IV_size=0,this.constant_IV=0,this.isProtected===1&&this.Per_Sample_IV_Size===0&&(this.constant_IV_size=o.readUint8(),this.constant_IV=o.readUint8Array(this.constant_IV_size))}),l.createSampleGroupCtor("stsa",function(o){e.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),l.createSampleGroupCtor("sync",function(o){var c=o.readUint8();this.NAL_unit_type=c&63}),l.createSampleGroupCtor("tele",function(o){var c=o.readUint8();this.level_independently_decodable=c>>7}),l.createSampleGroupCtor("tsas",function(o){e.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),l.createSampleGroupCtor("tscl",function(o){e.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),l.createSampleGroupCtor("vipr",function(o){e.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),l.createFullBoxCtor("sbgp","SampleToGroupBox",function(o){this.grouping_type=o.readString(4),this.version===1?this.grouping_type_parameter=o.readUint32():this.grouping_type_parameter=0,this.entries=[];for(var c=o.readUint32(),f=0;f<c;f++){var m={};this.entries.push(m),m.sample_count=o.readInt32(),m.group_description_index=o.readInt32()}});function p(o,c){this.bad_pixel_row=o,this.bad_pixel_column=c}p.prototype.toString=function(){return"[row: "+this.bad_pixel_row+", column: "+this.bad_pixel_column+"]"},l.createFullBoxCtor("sbpm","SensorBadPixelsMapBox",function(o){var c;for(this.component_count=o.readUint16(),this.component_index=[],c=0;c<this.component_count;c++)this.component_index.push(o.readUint16());var f=o.readUint8();for(this.correction_applied=(f&128)==128,this.num_bad_rows=o.readUint32(),this.num_bad_cols=o.readUint32(),this.num_bad_pixels=o.readUint32(),this.bad_rows=[],this.bad_columns=[],this.bad_pixels=[],c=0;c<this.num_bad_rows;c++)this.bad_rows.push(o.readUint32());for(c=0;c<this.num_bad_cols;c++)this.bad_columns.push(o.readUint32());for(c=0;c<this.num_bad_pixels;c++){var m=o.readUint32(),S=o.readUint32();this.bad_pixels.push(new p(m,S))}}),l.createFullBoxCtor("schm","SchemeTypeBox",function(o){this.scheme_type=o.readString(4),this.scheme_version=o.readUint32(),this.flags&1&&(this.scheme_uri=o.readString(this.size-this.hdr_size-8))}),l.createBoxCtor("sdp ","rtptracksdphintinformation",function(o){this.sdptext=o.readString(this.size-this.hdr_size)}),l.createFullBoxCtor("sdtp","SampleDependencyTypeBox",function(o){var c,f=this.size-this.hdr_size;this.is_leading=[],this.sample_depends_on=[],this.sample_is_depended_on=[],this.sample_has_redundancy=[];for(var m=0;m<f;m++)c=o.readUint8(),this.is_leading[m]=c>>6,this.sample_depends_on[m]=c>>4&3,this.sample_is_depended_on[m]=c>>2&3,this.sample_has_redundancy[m]=c&3}),l.createFullBoxCtor("senc","SampleEncryptionBox"),l.createFullBoxCtor("sgpd","SampleGroupDescriptionBox",function(o){this.grouping_type=o.readString(4),e.debug("BoxParser","Found Sample Groups of type "+this.grouping_type),this.version===1?this.default_length=o.readUint32():this.default_length=0,this.version>=2&&(this.default_group_description_index=o.readUint32()),this.entries=[];for(var c=o.readUint32(),f=0;f<c;f++){var m;l[this.grouping_type+"SampleGroupEntry"]?m=new l[this.grouping_type+"SampleGroupEntry"](this.grouping_type):m=new l.SampleGroupEntry(this.grouping_type),this.entries.push(m),this.version===1?this.default_length===0?m.description_length=o.readUint32():m.description_length=this.default_length:m.description_length=this.default_length,m.write===l.SampleGroupEntry.prototype.write&&(e.info("BoxParser","SampleGroup for type "+this.grouping_type+" writing not yet implemented, keeping unparsed data in memory for later write"),m.data=o.readUint8Array(m.description_length),o.position-=m.description_length),m.parse(o)}}),l.createFullBoxCtor("sidx","CompressedSegmentIndexBox",function(o){this.reference_ID=o.readUint32(),this.timescale=o.readUint32(),this.version===0?(this.earliest_presentation_time=o.readUint32(),this.first_offset=o.readUint32()):(this.earliest_presentation_time=o.readUint64(),this.first_offset=o.readUint64()),o.readUint16(),this.references=[];for(var c=o.readUint16(),f=0;f<c;f++){var m={};this.references.push(m);var S=o.readUint32();m.reference_type=S>>31&1,m.referenced_size=S&2147483647,m.subsegment_duration=o.readUint32(),S=o.readUint32(),m.starts_with_SAP=S>>31&1,m.SAP_type=S>>28&7,m.SAP_delta_time=S&268435455}}),l.SingleItemTypeReferenceBox=function(o,c,f,m){l.Box.call(this,o,c),this.hdr_size=f,this.start=m},l.SingleItemTypeReferenceBox.prototype=new l.Box,l.SingleItemTypeReferenceBox.prototype.parse=function(o){this.from_item_ID=o.readUint16();var c=o.readUint16();this.references=[];for(var f=0;f<c;f++)this.references[f]={},this.references[f].to_item_ID=o.readUint16()},l.SingleItemTypeReferenceBoxLarge=function(o,c,f,m){l.Box.call(this,o,c),this.hdr_size=f,this.start=m},l.SingleItemTypeReferenceBoxLarge.prototype=new l.Box,l.SingleItemTypeReferenceBoxLarge.prototype.parse=function(o){this.from_item_ID=o.readUint32();var c=o.readUint16();this.references=[];for(var f=0;f<c;f++)this.references[f]={},this.references[f].to_item_ID=o.readUint32()},l.createFullBoxCtor("SmDm","SMPTE2086MasteringDisplayMetadataBox",function(o){this.primaryRChromaticity_x=o.readUint16(),this.primaryRChromaticity_y=o.readUint16(),this.primaryGChromaticity_x=o.readUint16(),this.primaryGChromaticity_y=o.readUint16(),this.primaryBChromaticity_x=o.readUint16(),this.primaryBChromaticity_y=o.readUint16(),this.whitePointChromaticity_x=o.readUint16(),this.whitePointChromaticity_y=o.readUint16(),this.luminanceMax=o.readUint32(),this.luminanceMin=o.readUint32()}),l.createFullBoxCtor("smhd","SoundMediaHeaderBox",function(o){this.balance=o.readUint16(),o.readUint16()}),l.createFullBoxCtor("ssix","CompressedSubsegmentIndexBox",function(o){this.subsegments=[];for(var c=o.readUint32(),f=0;f<c;f++){var m={};this.subsegments.push(m),m.ranges=[];for(var S=o.readUint32(),T=0;T<S;T++){var b={};m.ranges.push(b),b.level=o.readUint8(),b.range_size=o.readUint24()}}}),l.createFullBoxCtor("stco","ChunkOffsetBox",function(o){var c;if(c=o.readUint32(),this.chunk_offsets=[],this.version===0)for(var f=0;f<c;f++)this.chunk_offsets.push(o.readUint32())}),l.createFullBoxCtor("stdp","DegradationPriorityBox",function(o){var c=(this.size-this.hdr_size)/2;this.priority=[];for(var f=0;f<c;f++)this.priority[f]=o.readUint16()}),l.createFullBoxCtor("sthd","SubtitleMediaHeaderBox"),l.createFullBoxCtor("stri","SubTrackInformationBox",function(o){this.switch_group=o.readUint16(),this.alternate_group=o.readUint16(),this.sub_track_id=o.readUint32();var c=(this.size-this.hdr_size-8)/4;this.attribute_list=[];for(var f=0;f<c;f++)this.attribute_list[f]=o.readUint32()}),l.createFullBoxCtor("stsc","SampleToChunkBox",function(o){var c,f;if(c=o.readUint32(),this.first_chunk=[],this.samples_per_chunk=[],this.sample_description_index=[],this.version===0)for(f=0;f<c;f++)this.first_chunk.push(o.readUint32()),this.samples_per_chunk.push(o.readUint32()),this.sample_description_index.push(o.readUint32())}),l.createFullBoxCtor("stsd","SampleDescriptionBox",function(o){var c,f,m,S;for(this.entries=[],m=o.readUint32(),c=1;c<=m;c++)if(f=l.parseOneBox(o,!0,this.size-(o.getPosition()-this.start)),f.code===l.OK)l[f.type+"SampleEntry"]?(S=new l[f.type+"SampleEntry"](f.size),S.hdr_size=f.hdr_size,S.start=f.start):(e.warn("BoxParser","Unknown sample entry type: "+f.type),S=new l.SampleEntry(f.type,f.size,f.hdr_size,f.start)),S.write===l.SampleEntry.prototype.write&&(e.info("BoxParser","SampleEntry "+S.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),S.parseDataAndRewind(o)),S.parse(o),this.entries.push(S);else return}),l.createFullBoxCtor("stsg","SubTrackSampleGroupBox",function(o){this.grouping_type=o.readUint32();var c=o.readUint16();this.group_description_index=[];for(var f=0;f<c;f++)this.group_description_index[f]=o.readUint32()}),l.createFullBoxCtor("stsh","ShadowSyncSampleBox",function(o){var c,f;if(c=o.readUint32(),this.shadowed_sample_numbers=[],this.sync_sample_numbers=[],this.version===0)for(f=0;f<c;f++)this.shadowed_sample_numbers.push(o.readUint32()),this.sync_sample_numbers.push(o.readUint32())}),l.createFullBoxCtor("stss","SyncSampleBox",function(o){var c,f;if(f=o.readUint32(),this.version===0)for(this.sample_numbers=[],c=0;c<f;c++)this.sample_numbers.push(o.readUint32())}),l.createFullBoxCtor("stsz","SampleSizeBox",function(o){var c;if(this.sample_sizes=[],this.version===0)for(this.sample_size=o.readUint32(),this.sample_count=o.readUint32(),c=0;c<this.sample_count;c++)this.sample_size===0?this.sample_sizes.push(o.readUint32()):this.sample_sizes[c]=this.sample_size}),l.createFullBoxCtor("stts","TimeToSampleBox",function(o){var c,f,m;if(c=o.readUint32(),this.sample_counts=[],this.sample_deltas=[],this.version===0)for(f=0;f<c;f++)this.sample_counts.push(o.readUint32()),m=o.readInt32(),m<0&&(e.warn("BoxParser","File uses negative stts sample delta, using value 1 instead, sync may be lost!"),m=1),this.sample_deltas.push(m)}),l.createFullBoxCtor("stvi","StereoVideoBox",function(o){var c=o.readUint32();this.single_view_allowed=c&3,this.stereo_scheme=o.readUint32();var f=o.readUint32();this.stereo_indication_type=o.readString(f);var m,S;for(this.boxes=[];o.getPosition()<this.start+this.size;)if(m=l.parseOneBox(o,!1,this.size-(o.getPosition()-this.start)),m.code===l.OK)S=m.box,this.boxes.push(S),this[S.type]=S;else return}),l.createBoxCtor("styp","SegmentTypeBox",function(o){l.ftypBox.prototype.parse.call(this,o)}),l.createFullBoxCtor("stz2","CompactSampleSizeBox",function(o){var c,f;if(this.sample_sizes=[],this.version===0)if(this.reserved=o.readUint24(),this.field_size=o.readUint8(),f=o.readUint32(),this.field_size===4)for(c=0;c<f;c+=2){var m=o.readUint8();this.sample_sizes[c]=m>>4&15,this.sample_sizes[c+1]=m&15}else if(this.field_size===8)for(c=0;c<f;c++)this.sample_sizes[c]=o.readUint8();else if(this.field_size===16)for(c=0;c<f;c++)this.sample_sizes[c]=o.readUint16();else e.error("BoxParser","Error in length field in stz2 box")}),l.createFullBoxCtor("subs","SubSampleInformationBox",function(o){var c,f,m,S;for(m=o.readUint32(),this.entries=[],c=0;c<m;c++){var T={};if(this.entries[c]=T,T.sample_delta=o.readUint32(),T.subsamples=[],S=o.readUint16(),S>0)for(f=0;f<S;f++){var b={};T.subsamples.push(b),this.version==1?b.size=o.readUint32():b.size=o.readUint16(),b.priority=o.readUint8(),b.discardable=o.readUint8(),b.codec_specific_parameters=o.readUint32()}}}),l.createFullBoxCtor("tenc","TrackEncryptionBox",function(o){if(o.readUint8(),this.version===0)o.readUint8();else{var c=o.readUint8();this.default_crypt_byte_block=c>>4&15,this.default_skip_byte_block=c&15}this.default_isProtected=o.readUint8(),this.default_Per_Sample_IV_Size=o.readUint8(),this.default_KID=l.parseHex16(o),this.default_isProtected===1&&this.default_Per_Sample_IV_Size===0&&(this.default_constant_IV_size=o.readUint8(),this.default_constant_IV=o.readUint8Array(this.default_constant_IV_size))}),l.createFullBoxCtor("tfdt","TrackFragmentBaseMediaDecodeTimeBox",function(o){this.version==1?this.baseMediaDecodeTime=o.readUint64():this.baseMediaDecodeTime=o.readUint32()}),l.createFullBoxCtor("tfhd","TrackFragmentHeaderBox",function(o){var c=0;this.track_id=o.readUint32(),this.size-this.hdr_size>c&&this.flags&l.TFHD_FLAG_BASE_DATA_OFFSET?(this.base_data_offset=o.readUint64(),c+=8):this.base_data_offset=0,this.size-this.hdr_size>c&&this.flags&l.TFHD_FLAG_SAMPLE_DESC?(this.default_sample_description_index=o.readUint32(),c+=4):this.default_sample_description_index=0,this.size-this.hdr_size>c&&this.flags&l.TFHD_FLAG_SAMPLE_DUR?(this.default_sample_duration=o.readUint32(),c+=4):this.default_sample_duration=0,this.size-this.hdr_size>c&&this.flags&l.TFHD_FLAG_SAMPLE_SIZE?(this.default_sample_size=o.readUint32(),c+=4):this.default_sample_size=0,this.size-this.hdr_size>c&&this.flags&l.TFHD_FLAG_SAMPLE_FLAGS?(this.default_sample_flags=o.readUint32(),c+=4):this.default_sample_flags=0}),l.createFullBoxCtor("tfra","TrackFragmentRandomAccessBox",function(o){this.track_ID=o.readUint32(),o.readUint24();var c=o.readUint8();this.length_size_of_traf_num=c>>4&3,this.length_size_of_trun_num=c>>2&3,this.length_size_of_sample_num=c&3,this.entries=[];for(var f=o.readUint32(),m=0;m<f;m++)this.version===1?(this.time=o.readUint64(),this.moof_offset=o.readUint64()):(this.time=o.readUint32(),this.moof_offset=o.readUint32()),this.traf_number=o["readUint"+8*(this.length_size_of_traf_num+1)](),this.trun_number=o["readUint"+8*(this.length_size_of_trun_num+1)](),this.sample_number=o["readUint"+8*(this.length_size_of_sample_num+1)]()}),l.createFullBoxCtor("tkhd","TrackHeaderBox",function(o){this.version==1?(this.creation_time=o.readUint64(),this.modification_time=o.readUint64(),this.track_id=o.readUint32(),o.readUint32(),this.duration=o.readUint64()):(this.creation_time=o.readUint32(),this.modification_time=o.readUint32(),this.track_id=o.readUint32(),o.readUint32(),this.duration=o.readUint32()),o.readUint32Array(2),this.layer=o.readInt16(),this.alternate_group=o.readInt16(),this.volume=o.readInt16()>>8,o.readUint16(),this.matrix=o.readInt32Array(9),this.width=o.readUint32(),this.height=o.readUint32()}),l.createBoxCtor("tmax","hintmaxrelativetime",function(o){this.time=o.readUint32()}),l.createBoxCtor("tmin","hintminrelativetime",function(o){this.time=o.readUint32()}),l.createBoxCtor("totl","hintBytesSent",function(o){this.bytessent=o.readUint32()}),l.createBoxCtor("tpay","hintBytesSent",function(o){this.bytessent=o.readUint32()}),l.createBoxCtor("tpyl","hintBytesSent",function(o){this.bytessent=o.readUint64()}),l.TrackGroupTypeBox.prototype.parse=function(o){this.parseFullHeader(o),this.track_group_id=o.readUint32()},l.createTrackGroupCtor("msrc"),l.TrackReferenceTypeBox=function(o,c,f,m){l.Box.call(this,o,c),this.hdr_size=f,this.start=m},l.TrackReferenceTypeBox.prototype=new l.Box,l.TrackReferenceTypeBox.prototype.parse=function(o){this.track_ids=o.readUint32Array((this.size-this.hdr_size)/4)},l.trefBox.prototype.parse=function(o){for(var c,f;o.getPosition()<this.start+this.size;)if(c=l.parseOneBox(o,!0,this.size-(o.getPosition()-this.start)),c.code===l.OK)f=new l.TrackReferenceTypeBox(c.type,c.size,c.hdr_size,c.start),f.write===l.Box.prototype.write&&f.type!=="mdat"&&(e.info("BoxParser","TrackReference "+f.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),f.parseDataAndRewind(o)),f.parse(o),this.boxes.push(f);else return},l.createFullBoxCtor("trep","TrackExtensionPropertiesBox",function(o){for(this.track_ID=o.readUint32(),this.boxes=[];o.getPosition()<this.start+this.size;)if(ret=l.parseOneBox(o,!1,this.size-(o.getPosition()-this.start)),ret.code===l.OK)box=ret.box,this.boxes.push(box);else return}),l.createFullBoxCtor("trex","TrackExtendsBox",function(o){this.track_id=o.readUint32(),this.default_sample_description_index=o.readUint32(),this.default_sample_duration=o.readUint32(),this.default_sample_size=o.readUint32(),this.default_sample_flags=o.readUint32()}),l.createBoxCtor("trpy","hintBytesSent",function(o){this.bytessent=o.readUint64()}),l.createFullBoxCtor("trun","TrackRunBox",function(o){var c=0;if(this.sample_count=o.readUint32(),c+=4,this.size-this.hdr_size>c&&this.flags&l.TRUN_FLAGS_DATA_OFFSET?(this.data_offset=o.readInt32(),c+=4):this.data_offset=0,this.size-this.hdr_size>c&&this.flags&l.TRUN_FLAGS_FIRST_FLAG?(this.first_sample_flags=o.readUint32(),c+=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>c)for(var f=0;f<this.sample_count;f++)this.flags&l.TRUN_FLAGS_DURATION&&(this.sample_duration[f]=o.readUint32()),this.flags&l.TRUN_FLAGS_SIZE&&(this.sample_size[f]=o.readUint32()),this.flags&l.TRUN_FLAGS_FLAGS&&(this.sample_flags[f]=o.readUint32()),this.flags&l.TRUN_FLAGS_CTS_OFFSET&&(this.version===0?this.sample_composition_time_offset[f]=o.readUint32():this.sample_composition_time_offset[f]=o.readInt32())}),l.createFullBoxCtor("tsel","TrackSelectionBox",function(o){this.switch_group=o.readUint32();var c=(this.size-this.hdr_size-4)/4;this.attribute_list=[];for(var f=0;f<c;f++)this.attribute_list[f]=o.readUint32()}),l.createFullBoxCtor("txtC","TextConfigBox",function(o){this.config=o.readCString()}),l.createBoxCtor("tyco","TypeCombinationBox",function(o){var c=(this.size-this.hdr_size)/4;this.compatible_brands=[];for(var f=0;f<c;f++)this.compatible_brands[f]=o.readString(4)}),l.createFullBoxCtor("udes","UserDescriptionProperty",function(o){this.lang=o.readCString(),this.name=o.readCString(),this.description=o.readCString(),this.tags=o.readCString()}),l.createFullBoxCtor("uncC","UncompressedFrameConfigBox",function(o){var c;if(this.profile=o.readString(4),this.version!=1){if(this.version==0){for(this.component_count=o.readUint32(),this.component_index=[],this.component_bit_depth_minus_one=[],this.component_format=[],this.component_align_size=[],c=0;c<this.component_count;c++)this.component_index.push(o.readUint16()),this.component_bit_depth_minus_one.push(o.readUint8()),this.component_format.push(o.readUint8()),this.component_align_size.push(o.readUint8());this.sampling_type=o.readUint8(),this.interleave_type=o.readUint8(),this.block_size=o.readUint8();var f=o.readUint8();this.component_little_endian=f>>7&1,this.block_pad_lsb=f>>6&1,this.block_little_endian=f>>5&1,this.block_reversed=f>>4&1,this.pad_unknown=f>>3&1,this.pixel_size=o.readUint32(),this.row_align_size=o.readUint32(),this.tile_align_size=o.readUint32(),this.num_tile_cols_minus_one=o.readUint32(),this.num_tile_rows_minus_one=o.readUint32()}}}),l.createFullBoxCtor("url ","DataEntryUrlBox",function(o){this.flags!==1&&(this.location=o.readCString())}),l.createFullBoxCtor("urn ","DataEntryUrnBox",function(o){this.name=o.readCString(),this.size-this.hdr_size-this.name.length-1>0&&(this.location=o.readCString())}),l.createUUIDBox("a5d40b30e81411ddba2f0800200c9a66","LiveServerManifestBox",!0,!1,function(o){this.LiveServerManifest=o.readString(this.size-this.hdr_size).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}),l.createUUIDBox("d08a4f1810f34a82b6c832d8aba183d3","PiffProtectionSystemSpecificHeaderBox",!0,!1,function(o){this.system_id=l.parseHex16(o);var c=o.readUint32();c>0&&(this.data=o.readUint8Array(c))}),l.createUUIDBox("a2394f525a9b4f14a2446c427c648df4","PiffSampleEncryptionBox",!0,!1),l.createUUIDBox("8974dbce7be74c5184f97148f9882554","PiffTrackEncryptionBox",!0,!1,function(o){this.default_AlgorithmID=o.readUint24(),this.default_IV_size=o.readUint8(),this.default_KID=l.parseHex16(o)}),l.createUUIDBox("d4807ef2ca3946958e5426cb9e46a79f","TfrfBox",!0,!1,function(o){this.fragment_count=o.readUint8(),this.entries=[];for(var c=0;c<this.fragment_count;c++){var f={},m=0,S=0;this.version===1?(m=o.readUint64(),S=o.readUint64()):(m=o.readUint32(),S=o.readUint32()),f.absolute_time=m,f.absolute_duration=S,this.entries.push(f)}}),l.createUUIDBox("6d1d9b0542d544e680e2141daff757b2","TfxdBox",!0,!1,function(o){this.version===1?(this.absolute_time=o.readUint64(),this.duration=o.readUint64()):(this.absolute_time=o.readUint32(),this.duration=o.readUint32())}),l.createFullBoxCtor("vmhd","VideoMediaHeaderBox",function(o){this.graphicsmode=o.readUint16(),this.opcolor=o.readUint16Array(3)}),l.createFullBoxCtor("vpcC","VPCodecConfigurationRecord",function(o){var c;this.version===1?(this.profile=o.readUint8(),this.level=o.readUint8(),c=o.readUint8(),this.bitDepth=c>>4,this.chromaSubsampling=c>>1&7,this.videoFullRangeFlag=c&1,this.colourPrimaries=o.readUint8(),this.transferCharacteristics=o.readUint8(),this.matrixCoefficients=o.readUint8(),this.codecIntializationDataSize=o.readUint16(),this.codecIntializationData=o.readUint8Array(this.codecIntializationDataSize)):(this.profile=o.readUint8(),this.level=o.readUint8(),c=o.readUint8(),this.bitDepth=c>>4&15,this.colorSpace=c&15,c=o.readUint8(),this.chromaSubsampling=c>>4&15,this.transferFunction=c>>1&7,this.videoFullRangeFlag=c&1,this.codecIntializationDataSize=o.readUint16(),this.codecIntializationData=o.readUint8Array(this.codecIntializationDataSize))}),l.createBoxCtor("vttC","WebVTTConfigurationBox",function(o){this.text=o.readString(this.size-this.hdr_size)}),l.createFullBoxCtor("vvcC","VvcConfigurationBox",function(o){var c,f,m={held_bits:void 0,num_held_bits:0,stream_read_1_bytes:function(k){this.held_bits=k.readUint8(),this.num_held_bits=8},stream_read_2_bytes:function(k){this.held_bits=k.readUint16(),this.num_held_bits=16},extract_bits:function(k){var z=this.held_bits>>this.num_held_bits-k&(1<<k)-1;return this.num_held_bits-=k,z}};if(m.stream_read_1_bytes(o),m.extract_bits(5),this.lengthSizeMinusOne=m.extract_bits(2),this.ptl_present_flag=m.extract_bits(1),this.ptl_present_flag){m.stream_read_2_bytes(o),this.ols_idx=m.extract_bits(9),this.num_sublayers=m.extract_bits(3),this.constant_frame_rate=m.extract_bits(2),this.chroma_format_idc=m.extract_bits(2),m.stream_read_1_bytes(o),this.bit_depth_minus8=m.extract_bits(3),m.extract_bits(5);{if(m.stream_read_2_bytes(o),m.extract_bits(2),this.num_bytes_constraint_info=m.extract_bits(6),this.general_profile_idc=m.extract_bits(7),this.general_tier_flag=m.extract_bits(1),this.general_level_idc=o.readUint8(),m.stream_read_1_bytes(o),this.ptl_frame_only_constraint_flag=m.extract_bits(1),this.ptl_multilayer_enabled_flag=m.extract_bits(1),this.general_constraint_info=new Uint8Array(this.num_bytes_constraint_info),this.num_bytes_constraint_info){for(c=0;c<this.num_bytes_constraint_info-1;c++){var S=m.extract_bits(6);m.stream_read_1_bytes(o);var T=m.extract_bits(2);this.general_constraint_info[c]=S<<2|T}this.general_constraint_info[this.num_bytes_constraint_info-1]=m.extract_bits(6)}else m.extract_bits(6);if(this.num_sublayers>1){for(m.stream_read_1_bytes(o),this.ptl_sublayer_present_mask=0,f=this.num_sublayers-2;f>=0;--f){var b=m.extract_bits(1);this.ptl_sublayer_present_mask|=b<<f}for(f=this.num_sublayers;f<=8&&this.num_sublayers>1;++f)m.extract_bits(1);for(this.sublayer_level_idc=[],f=this.num_sublayers-2;f>=0;--f)this.ptl_sublayer_present_mask&1<<f&&(this.sublayer_level_idc[f]=o.readUint8())}if(this.ptl_num_sub_profiles=o.readUint8(),this.general_sub_profile_idc=[],this.ptl_num_sub_profiles)for(c=0;c<this.ptl_num_sub_profiles;c++)this.general_sub_profile_idc.push(o.readUint32())}this.max_picture_width=o.readUint16(),this.max_picture_height=o.readUint16(),this.avg_frame_rate=o.readUint16()}var A=12,I=13;this.nalu_arrays=[];var L=o.readUint8();for(c=0;c<L;c++){var w=[];this.nalu_arrays.push(w),m.stream_read_1_bytes(o),w.completeness=m.extract_bits(1),m.extract_bits(2),w.nalu_type=m.extract_bits(5);var R=1;for(w.nalu_type!=I&&w.nalu_type!=A&&(R=o.readUint16()),f=0;f<R;f++){var M=o.readUint16();w.push({data:o.readUint8Array(M),length:M})}}}),l.createFullBoxCtor("vvnC","VvcNALUConfigBox",function(o){var c=strm.readUint8();this.lengthSizeMinusOne=c&3}),l.SampleEntry.prototype.isVideo=function(){return!1},l.SampleEntry.prototype.isAudio=function(){return!1},l.SampleEntry.prototype.isSubtitle=function(){return!1},l.SampleEntry.prototype.isMetadata=function(){return!1},l.SampleEntry.prototype.isHint=function(){return!1},l.SampleEntry.prototype.getCodec=function(){return this.type.replace(".","")},l.SampleEntry.prototype.getWidth=function(){return""},l.SampleEntry.prototype.getHeight=function(){return""},l.SampleEntry.prototype.getChannelCount=function(){return""},l.SampleEntry.prototype.getSampleRate=function(){return""},l.SampleEntry.prototype.getSampleSize=function(){return""},l.VisualSampleEntry.prototype.isVideo=function(){return!0},l.VisualSampleEntry.prototype.getWidth=function(){return this.width},l.VisualSampleEntry.prototype.getHeight=function(){return this.height},l.AudioSampleEntry.prototype.isAudio=function(){return!0},l.AudioSampleEntry.prototype.getChannelCount=function(){return this.channel_count},l.AudioSampleEntry.prototype.getSampleRate=function(){return this.samplerate},l.AudioSampleEntry.prototype.getSampleSize=function(){return this.samplesize},l.SubtitleSampleEntry.prototype.isSubtitle=function(){return!0},l.MetadataSampleEntry.prototype.isMetadata=function(){return!0},l.decimalToHex=function(o,c){var f=Number(o).toString(16);for(c=typeof c>"u"||c===null?c=2:c;f.length<c;)f="0"+f;return f},l.avc1SampleEntry.prototype.getCodec=l.avc2SampleEntry.prototype.getCodec=l.avc3SampleEntry.prototype.getCodec=l.avc4SampleEntry.prototype.getCodec=function(){var o=l.SampleEntry.prototype.getCodec.call(this);return this.avcC?o+"."+l.decimalToHex(this.avcC.AVCProfileIndication)+l.decimalToHex(this.avcC.profile_compatibility)+l.decimalToHex(this.avcC.AVCLevelIndication):o},l.hev1SampleEntry.prototype.getCodec=l.hvc1SampleEntry.prototype.getCodec=function(){var o,c=l.SampleEntry.prototype.getCodec.call(this);if(this.hvcC){switch(c+=".",this.hvcC.general_profile_space){case 0:c+="";break;case 1:c+="A";break;case 2:c+="B";break;case 3:c+="C";break}c+=this.hvcC.general_profile_idc,c+=".";var f=this.hvcC.general_profile_compatibility,m=0;for(o=0;o<32&&(m|=f&1,o!=31);o++)m<<=1,f>>=1;c+=l.decimalToHex(m,0),c+=".",this.hvcC.general_tier_flag===0?c+="L":c+="H",c+=this.hvcC.general_level_idc;var S=!1,T="";for(o=5;o>=0;o--)(this.hvcC.general_constraint_indicator[o]||S)&&(T="."+l.decimalToHex(this.hvcC.general_constraint_indicator[o],0)+T,S=!0);c+=T}return c},l.vvc1SampleEntry.prototype.getCodec=l.vvi1SampleEntry.prototype.getCodec=function(){var o,c=l.SampleEntry.prototype.getCodec.call(this);if(this.vvcC){c+="."+this.vvcC.general_profile_idc,this.vvcC.general_tier_flag?c+=".H":c+=".L",c+=this.vvcC.general_level_idc;var f="";if(this.vvcC.general_constraint_info){var m=[],S=0;S|=this.vvcC.ptl_frame_only_constraint<<7,S|=this.vvcC.ptl_multilayer_enabled<<6;var T;for(o=0;o<this.vvcC.general_constraint_info.length;++o)S|=this.vvcC.general_constraint_info[o]>>2&63,m.push(S),S&&(T=o),S=this.vvcC.general_constraint_info[o]>>2&3;if(T===void 0)f=".CA";else{f=".C";var b="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",A=0,I=0;for(o=0;o<=T;++o)for(A=A<<8|m[o],I+=8;I>=5;){var L=A>>I-5&31;f+=b[L],I-=5,A&=(1<<I)-1}I&&(A<<=5-I,f+=b[A&31])}}c+=f}return c},l.mp4aSampleEntry.prototype.getCodec=function(){var o=l.SampleEntry.prototype.getCodec.call(this);if(this.esds&&this.esds.esd){var c=this.esds.esd.getOTI(),f=this.esds.esd.getAudioConfig();return o+"."+l.decimalToHex(c)+(f?"."+f:"")}else return o},l.stxtSampleEntry.prototype.getCodec=function(){var o=l.SampleEntry.prototype.getCodec.call(this);return this.mime_format?o+"."+this.mime_format:o},l.vp08SampleEntry.prototype.getCodec=l.vp09SampleEntry.prototype.getCodec=function(){var o=l.SampleEntry.prototype.getCodec.call(this),c=this.vpcC.level;c==0&&(c="00");var f=this.vpcC.bitDepth;return f==8&&(f="08"),o+".0"+this.vpcC.profile+"."+c+"."+f},l.av01SampleEntry.prototype.getCodec=function(){var o=l.SampleEntry.prototype.getCodec.call(this),c=this.av1C.seq_level_idx_0;c<10&&(c="0"+c);var f;return this.av1C.seq_profile===2&&this.av1C.high_bitdepth===1?f=this.av1C.twelve_bit===1?"12":"10":this.av1C.seq_profile<=2&&(f=this.av1C.high_bitdepth===1?"10":"08"),o+"."+this.av1C.seq_profile+"."+c+(this.av1C.seq_tier_0?"H":"M")+"."+f},l.Box.prototype.writeHeader=function(o,c){this.size+=8,this.size>n&&(this.size+=8),this.type==="uuid"&&(this.size+=16),e.debug("BoxWriter","Writing box "+this.type+" of size: "+this.size+" at position "+o.getPosition()+(c||"")),this.size>n?o.writeUint32(1):(this.sizePosition=o.getPosition(),o.writeUint32(this.size)),o.writeString(this.type,null,4),this.type==="uuid"&&o.writeUint8Array(this.uuid),this.size>n&&o.writeUint64(this.size)},l.FullBox.prototype.writeHeader=function(o){this.size+=4,l.Box.prototype.writeHeader.call(this,o," v="+this.version+" f="+this.flags),o.writeUint8(this.version),o.writeUint24(this.flags)},l.Box.prototype.write=function(o){this.type==="mdat"?this.data&&(this.size=this.data.length,this.writeHeader(o),o.writeUint8Array(this.data)):(this.size=this.data?this.data.length:0,this.writeHeader(o),this.data&&o.writeUint8Array(this.data))},l.ContainerBox.prototype.write=function(o){this.size=0,this.writeHeader(o);for(var c=0;c<this.boxes.length;c++)this.boxes[c]&&(this.boxes[c].write(o),this.size+=this.boxes[c].size);e.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),o.adjustUint32(this.sizePosition,this.size)},l.TrackReferenceTypeBox.prototype.write=function(o){this.size=this.track_ids.length*4,this.writeHeader(o),o.writeUint32Array(this.track_ids)},l.avcCBox.prototype.write=function(o){var c;for(this.size=7,c=0;c<this.SPS.length;c++)this.size+=2+this.SPS[c].length;for(c=0;c<this.PPS.length;c++)this.size+=2+this.PPS[c].length;for(this.ext&&(this.size+=this.ext.length),this.writeHeader(o),o.writeUint8(this.configurationVersion),o.writeUint8(this.AVCProfileIndication),o.writeUint8(this.profile_compatibility),o.writeUint8(this.AVCLevelIndication),o.writeUint8(this.lengthSizeMinusOne+252),o.writeUint8(this.SPS.length+224),c=0;c<this.SPS.length;c++)o.writeUint16(this.SPS[c].length),o.writeUint8Array(this.SPS[c].nalu);for(o.writeUint8(this.PPS.length),c=0;c<this.PPS.length;c++)o.writeUint16(this.PPS[c].length),o.writeUint8Array(this.PPS[c].nalu);this.ext&&o.writeUint8Array(this.ext)},l.co64Box.prototype.write=function(o){var c;for(this.version=0,this.flags=0,this.size=4+8*this.chunk_offsets.length,this.writeHeader(o),o.writeUint32(this.chunk_offsets.length),c=0;c<this.chunk_offsets.length;c++)o.writeUint64(this.chunk_offsets[c])},l.cslgBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=4*5,this.writeHeader(o),o.writeInt32(this.compositionToDTSShift),o.writeInt32(this.leastDecodeToDisplayDelta),o.writeInt32(this.greatestDecodeToDisplayDelta),o.writeInt32(this.compositionStartTime),o.writeInt32(this.compositionEndTime)},l.cttsBox.prototype.write=function(o){var c;for(this.version=0,this.flags=0,this.size=4+8*this.sample_counts.length,this.writeHeader(o),o.writeUint32(this.sample_counts.length),c=0;c<this.sample_counts.length;c++)o.writeUint32(this.sample_counts[c]),this.version===1?o.writeInt32(this.sample_offsets[c]):o.writeUint32(this.sample_offsets[c])},l.drefBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=4,this.writeHeader(o),o.writeUint32(this.entries.length);for(var c=0;c<this.entries.length;c++)this.entries[c].write(o),this.size+=this.entries[c].size;e.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),o.adjustUint32(this.sizePosition,this.size)},l.elngBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=this.extended_language.length,this.writeHeader(o),o.writeString(this.extended_language)},l.elstBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=4+12*this.entries.length,this.writeHeader(o),o.writeUint32(this.entries.length);for(var c=0;c<this.entries.length;c++){var f=this.entries[c];o.writeUint32(f.segment_duration),o.writeInt32(f.media_time),o.writeInt16(f.media_rate_integer),o.writeInt16(f.media_rate_fraction)}},l.emsgBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=4*4+this.message_data.length+(this.scheme_id_uri.length+1)+(this.value.length+1),this.writeHeader(o),o.writeCString(this.scheme_id_uri),o.writeCString(this.value),o.writeUint32(this.timescale),o.writeUint32(this.presentation_time_delta),o.writeUint32(this.event_duration),o.writeUint32(this.id),o.writeUint8Array(this.message_data)},l.ftypBox.prototype.write=function(o){this.size=8+4*this.compatible_brands.length,this.writeHeader(o),o.writeString(this.major_brand,null,4),o.writeUint32(this.minor_version);for(var c=0;c<this.compatible_brands.length;c++)o.writeString(this.compatible_brands[c],null,4)},l.hdlrBox.prototype.write=function(o){this.size=5*4+this.name.length+1,this.version=0,this.flags=0,this.writeHeader(o),o.writeUint32(0),o.writeString(this.handler,null,4),o.writeUint32(0),o.writeUint32(0),o.writeUint32(0),o.writeCString(this.name)},l.hvcCBox.prototype.write=function(o){var c,f;for(this.size=23,c=0;c<this.nalu_arrays.length;c++)for(this.size+=3,f=0;f<this.nalu_arrays[c].length;f++)this.size+=2+this.nalu_arrays[c][f].data.length;for(this.writeHeader(o),o.writeUint8(this.configurationVersion),o.writeUint8((this.general_profile_space<<6)+(this.general_tier_flag<<5)+this.general_profile_idc),o.writeUint32(this.general_profile_compatibility),o.writeUint8Array(this.general_constraint_indicator),o.writeUint8(this.general_level_idc),o.writeUint16(this.min_spatial_segmentation_idc+(15<<24)),o.writeUint8(this.parallelismType+252),o.writeUint8(this.chroma_format_idc+252),o.writeUint8(this.bit_depth_luma_minus8+248),o.writeUint8(this.bit_depth_chroma_minus8+248),o.writeUint16(this.avgFrameRate),o.writeUint8((this.constantFrameRate<<6)+(this.numTemporalLayers<<3)+(this.temporalIdNested<<2)+this.lengthSizeMinusOne),o.writeUint8(this.nalu_arrays.length),c=0;c<this.nalu_arrays.length;c++)for(o.writeUint8((this.nalu_arrays[c].completeness<<7)+this.nalu_arrays[c].nalu_type),o.writeUint16(this.nalu_arrays[c].length),f=0;f<this.nalu_arrays[c].length;f++)o.writeUint16(this.nalu_arrays[c][f].data.length),o.writeUint8Array(this.nalu_arrays[c][f].data)},l.kindBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=this.schemeURI.length+1+(this.value.length+1),this.writeHeader(o),o.writeCString(this.schemeURI),o.writeCString(this.value)},l.mdhdBox.prototype.write=function(o){this.size=4*4+2*2,this.flags=0,this.version=0,this.writeHeader(o),o.writeUint32(this.creation_time),o.writeUint32(this.modification_time),o.writeUint32(this.timescale),o.writeUint32(this.duration),o.writeUint16(this.language),o.writeUint16(0)},l.mehdBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=4,this.writeHeader(o),o.writeUint32(this.fragment_duration)},l.mfhdBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=4,this.writeHeader(o),o.writeUint32(this.sequence_number)},l.mvhdBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=23*4+2*2,this.writeHeader(o),o.writeUint32(this.creation_time),o.writeUint32(this.modification_time),o.writeUint32(this.timescale),o.writeUint32(this.duration),o.writeUint32(this.rate),o.writeUint16(this.volume<<8),o.writeUint16(0),o.writeUint32(0),o.writeUint32(0),o.writeUint32Array(this.matrix),o.writeUint32(0),o.writeUint32(0),o.writeUint32(0),o.writeUint32(0),o.writeUint32(0),o.writeUint32(0),o.writeUint32(this.next_track_id)},l.SampleEntry.prototype.writeHeader=function(o){this.size=8,l.Box.prototype.writeHeader.call(this,o),o.writeUint8(0),o.writeUint8(0),o.writeUint8(0),o.writeUint8(0),o.writeUint8(0),o.writeUint8(0),o.writeUint16(this.data_reference_index)},l.SampleEntry.prototype.writeFooter=function(o){for(var c=0;c<this.boxes.length;c++)this.boxes[c].write(o),this.size+=this.boxes[c].size;e.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),o.adjustUint32(this.sizePosition,this.size)},l.SampleEntry.prototype.write=function(o){this.writeHeader(o),o.writeUint8Array(this.data),this.size+=this.data.length,e.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),o.adjustUint32(this.sizePosition,this.size)},l.VisualSampleEntry.prototype.write=function(o){this.writeHeader(o),this.size+=2*7+6*4+32,o.writeUint16(0),o.writeUint16(0),o.writeUint32(0),o.writeUint32(0),o.writeUint32(0),o.writeUint16(this.width),o.writeUint16(this.height),o.writeUint32(this.horizresolution),o.writeUint32(this.vertresolution),o.writeUint32(0),o.writeUint16(this.frame_count),o.writeUint8(Math.min(31,this.compressorname.length)),o.writeString(this.compressorname,null,31),o.writeUint16(this.depth),o.writeInt16(-1),this.writeFooter(o)},l.AudioSampleEntry.prototype.write=function(o){this.writeHeader(o),this.size+=2*4+3*4,o.writeUint32(0),o.writeUint32(0),o.writeUint16(this.channel_count),o.writeUint16(this.samplesize),o.writeUint16(0),o.writeUint16(0),o.writeUint32(this.samplerate<<16),this.writeFooter(o)},l.stppSampleEntry.prototype.write=function(o){this.writeHeader(o),this.size+=this.namespace.length+1+this.schema_location.length+1+this.auxiliary_mime_types.length+1,o.writeCString(this.namespace),o.writeCString(this.schema_location),o.writeCString(this.auxiliary_mime_types),this.writeFooter(o)},l.SampleGroupEntry.prototype.write=function(o){o.writeUint8Array(this.data)},l.sbgpBox.prototype.write=function(o){this.version=1,this.flags=0,this.size=12+8*this.entries.length,this.writeHeader(o),o.writeString(this.grouping_type,null,4),o.writeUint32(this.grouping_type_parameter),o.writeUint32(this.entries.length);for(var c=0;c<this.entries.length;c++){var f=this.entries[c];o.writeInt32(f.sample_count),o.writeInt32(f.group_description_index)}},l.sgpdBox.prototype.write=function(o){var c,f;for(this.flags=0,this.size=12,c=0;c<this.entries.length;c++)f=this.entries[c],this.version===1&&(this.default_length===0&&(this.size+=4),this.size+=f.data.length);for(this.writeHeader(o),o.writeString(this.grouping_type,null,4),this.version===1&&o.writeUint32(this.default_length),this.version>=2&&o.writeUint32(this.default_sample_description_index),o.writeUint32(this.entries.length),c=0;c<this.entries.length;c++)f=this.entries[c],this.version===1&&this.default_length===0&&o.writeUint32(f.description_length),f.write(o)},l.sidxBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=4*4+2+2+12*this.references.length,this.writeHeader(o),o.writeUint32(this.reference_ID),o.writeUint32(this.timescale),o.writeUint32(this.earliest_presentation_time),o.writeUint32(this.first_offset),o.writeUint16(0),o.writeUint16(this.references.length);for(var c=0;c<this.references.length;c++){var f=this.references[c];o.writeUint32(f.reference_type<<31|f.referenced_size),o.writeUint32(f.subsegment_duration),o.writeUint32(f.starts_with_SAP<<31|f.SAP_type<<28|f.SAP_delta_time)}},l.smhdBox.prototype.write=function(o){this.version=0,this.flags=1,this.size=4,this.writeHeader(o),o.writeUint16(this.balance),o.writeUint16(0)},l.stcoBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=4+4*this.chunk_offsets.length,this.writeHeader(o),o.writeUint32(this.chunk_offsets.length),o.writeUint32Array(this.chunk_offsets)},l.stscBox.prototype.write=function(o){var c;for(this.version=0,this.flags=0,this.size=4+12*this.first_chunk.length,this.writeHeader(o),o.writeUint32(this.first_chunk.length),c=0;c<this.first_chunk.length;c++)o.writeUint32(this.first_chunk[c]),o.writeUint32(this.samples_per_chunk[c]),o.writeUint32(this.sample_description_index[c])},l.stsdBox.prototype.write=function(o){var c;for(this.version=0,this.flags=0,this.size=0,this.writeHeader(o),o.writeUint32(this.entries.length),this.size+=4,c=0;c<this.entries.length;c++)this.entries[c].write(o),this.size+=this.entries[c].size;e.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),o.adjustUint32(this.sizePosition,this.size)},l.stshBox.prototype.write=function(o){var c;for(this.version=0,this.flags=0,this.size=4+8*this.shadowed_sample_numbers.length,this.writeHeader(o),o.writeUint32(this.shadowed_sample_numbers.length),c=0;c<this.shadowed_sample_numbers.length;c++)o.writeUint32(this.shadowed_sample_numbers[c]),o.writeUint32(this.sync_sample_numbers[c])},l.stssBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=4+4*this.sample_numbers.length,this.writeHeader(o),o.writeUint32(this.sample_numbers.length),o.writeUint32Array(this.sample_numbers)},l.stszBox.prototype.write=function(o){var c,f=!0;if(this.version=0,this.flags=0,this.sample_sizes.length>0)for(c=0;c+1<this.sample_sizes.length;)if(this.sample_sizes[c+1]!==this.sample_sizes[0]){f=!1;break}else c++;else f=!1;this.size=8,f||(this.size+=4*this.sample_sizes.length),this.writeHeader(o),f?o.writeUint32(this.sample_sizes[0]):o.writeUint32(0),o.writeUint32(this.sample_sizes.length),f||o.writeUint32Array(this.sample_sizes)},l.sttsBox.prototype.write=function(o){var c;for(this.version=0,this.flags=0,this.size=4+8*this.sample_counts.length,this.writeHeader(o),o.writeUint32(this.sample_counts.length),c=0;c<this.sample_counts.length;c++)o.writeUint32(this.sample_counts[c]),o.writeUint32(this.sample_deltas[c])},l.tfdtBox.prototype.write=function(o){var c=Math.pow(2,32)-1;this.version=this.baseMediaDecodeTime>c?1:0,this.flags=0,this.size=4,this.version===1&&(this.size+=4),this.writeHeader(o),this.version===1?o.writeUint64(this.baseMediaDecodeTime):o.writeUint32(this.baseMediaDecodeTime)},l.tfhdBox.prototype.write=function(o){this.version=0,this.size=4,this.flags&l.TFHD_FLAG_BASE_DATA_OFFSET&&(this.size+=8),this.flags&l.TFHD_FLAG_SAMPLE_DESC&&(this.size+=4),this.flags&l.TFHD_FLAG_SAMPLE_DUR&&(this.size+=4),this.flags&l.TFHD_FLAG_SAMPLE_SIZE&&(this.size+=4),this.flags&l.TFHD_FLAG_SAMPLE_FLAGS&&(this.size+=4),this.writeHeader(o),o.writeUint32(this.track_id),this.flags&l.TFHD_FLAG_BASE_DATA_OFFSET&&o.writeUint64(this.base_data_offset),this.flags&l.TFHD_FLAG_SAMPLE_DESC&&o.writeUint32(this.default_sample_description_index),this.flags&l.TFHD_FLAG_SAMPLE_DUR&&o.writeUint32(this.default_sample_duration),this.flags&l.TFHD_FLAG_SAMPLE_SIZE&&o.writeUint32(this.default_sample_size),this.flags&l.TFHD_FLAG_SAMPLE_FLAGS&&o.writeUint32(this.default_sample_flags)},l.tkhdBox.prototype.write=function(o){this.version=0,this.size=4*18+2*4,this.writeHeader(o),o.writeUint32(this.creation_time),o.writeUint32(this.modification_time),o.writeUint32(this.track_id),o.writeUint32(0),o.writeUint32(this.duration),o.writeUint32(0),o.writeUint32(0),o.writeInt16(this.layer),o.writeInt16(this.alternate_group),o.writeInt16(this.volume<<8),o.writeUint16(0),o.writeInt32Array(this.matrix),o.writeUint32(this.width),o.writeUint32(this.height)},l.trexBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=4*5,this.writeHeader(o),o.writeUint32(this.track_id),o.writeUint32(this.default_sample_description_index),o.writeUint32(this.default_sample_duration),o.writeUint32(this.default_sample_size),o.writeUint32(this.default_sample_flags)},l.trunBox.prototype.write=function(o){this.version=0,this.size=4,this.flags&l.TRUN_FLAGS_DATA_OFFSET&&(this.size+=4),this.flags&l.TRUN_FLAGS_FIRST_FLAG&&(this.size+=4),this.flags&l.TRUN_FLAGS_DURATION&&(this.size+=4*this.sample_duration.length),this.flags&l.TRUN_FLAGS_SIZE&&(this.size+=4*this.sample_size.length),this.flags&l.TRUN_FLAGS_FLAGS&&(this.size+=4*this.sample_flags.length),this.flags&l.TRUN_FLAGS_CTS_OFFSET&&(this.size+=4*this.sample_composition_time_offset.length),this.writeHeader(o),o.writeUint32(this.sample_count),this.flags&l.TRUN_FLAGS_DATA_OFFSET&&(this.data_offset_position=o.getPosition(),o.writeInt32(this.data_offset)),this.flags&l.TRUN_FLAGS_FIRST_FLAG&&o.writeUint32(this.first_sample_flags);for(var c=0;c<this.sample_count;c++)this.flags&l.TRUN_FLAGS_DURATION&&o.writeUint32(this.sample_duration[c]),this.flags&l.TRUN_FLAGS_SIZE&&o.writeUint32(this.sample_size[c]),this.flags&l.TRUN_FLAGS_FLAGS&&o.writeUint32(this.sample_flags[c]),this.flags&l.TRUN_FLAGS_CTS_OFFSET&&(this.version===0?o.writeUint32(this.sample_composition_time_offset[c]):o.writeInt32(this.sample_composition_time_offset[c]))},l["url Box"].prototype.write=function(o){this.version=0,this.location?(this.flags=0,this.size=this.location.length+1):(this.flags=1,this.size=0),this.writeHeader(o),this.location&&o.writeCString(this.location)},l["urn Box"].prototype.write=function(o){this.version=0,this.flags=0,this.size=this.name.length+1+(this.location?this.location.length+1:0),this.writeHeader(o),o.writeCString(this.name),this.location&&o.writeCString(this.location)},l.vmhdBox.prototype.write=function(o){this.version=0,this.flags=1,this.size=8,this.writeHeader(o),o.writeUint16(this.graphicsmode),o.writeUint16Array(this.opcolor)},l.cttsBox.prototype.unpack=function(o){var c,f,m;for(m=0,c=0;c<this.sample_counts.length;c++)for(f=0;f<this.sample_counts[c];f++)o[m].pts=o[m].dts+this.sample_offsets[c],m++},l.sttsBox.prototype.unpack=function(o){var c,f,m;for(m=0,c=0;c<this.sample_counts.length;c++)for(f=0;f<this.sample_counts[c];f++)m===0?o[m].dts=0:o[m].dts=o[m-1].dts+this.sample_deltas[c],m++},l.stcoBox.prototype.unpack=function(o){var c;for(c=0;c<this.chunk_offsets.length;c++)o[c].offset=this.chunk_offsets[c]},l.stscBox.prototype.unpack=function(o){var c,f,m,S,T;for(S=0,T=0,c=0;c<this.first_chunk.length;c++)for(f=0;f<(c+1<this.first_chunk.length?this.first_chunk[c+1]:1/0);f++)for(T++,m=0;m<this.samples_per_chunk[c];m++){if(o[S])o[S].description_index=this.sample_description_index[c],o[S].chunk_index=T;else return;S++}},l.stszBox.prototype.unpack=function(o){var c;for(c=0;c<this.sample_sizes.length;c++)o[c].size=this.sample_sizes[c]},l.DIFF_BOXES_PROP_NAMES=["boxes","entries","references","subsamples","items","item_infos","extents","associations","subsegments","ranges","seekLists","seekPoints","esd","levels"],l.DIFF_PRIMITIVE_ARRAY_PROP_NAMES=["compatible_brands","matrix","opcolor","sample_counts","sample_deltas","first_chunk","samples_per_chunk","sample_sizes","chunk_offsets","sample_offsets","sample_description_index","sample_duration"],l.boxEqualFields=function(o,c){if(o&&!c)return!1;var f;for(f in o)if(!(l.DIFF_BOXES_PROP_NAMES.indexOf(f)>-1)){if(o[f]instanceof l.Box||c[f]instanceof l.Box)continue;if(typeof o[f]>"u"||typeof c[f]>"u")continue;if(typeof o[f]=="function"||typeof c[f]=="function")continue;if(o.subBoxNames&&o.subBoxNames.indexOf(f.slice(0,4))>-1||c.subBoxNames&&c.subBoxNames.indexOf(f.slice(0,4))>-1)continue;if(f==="data"||f==="start"||f==="size"||f==="creation_time"||f==="modification_time")continue;if(l.DIFF_PRIMITIVE_ARRAY_PROP_NAMES.indexOf(f)>-1)continue;if(o[f]!==c[f])return!1}return!0},l.boxEqual=function(o,c){if(!l.boxEqualFields(o,c))return!1;for(var f=0;f<l.DIFF_BOXES_PROP_NAMES.length;f++){var m=l.DIFF_BOXES_PROP_NAMES[f];if(o[m]&&c[m]&&!l.boxEqual(o[m],c[m]))return!1}return!0};var g=function(){};g.prototype.parseSample=function(o){var c,f,m=new t(o.buffer);for(c=[];!m.isEos();)f=l.parseOneBox(m,!1),f.code===l.OK&&f.box.type==="vttc"&&c.push(f.box);return c},g.prototype.getText=function(o,c,f){function m(L,w,R){return R=R||"0",L=L+"",L.length>=w?L:new Array(w-L.length+1).join(R)+L}function S(L){var w=Math.floor(L/3600),R=Math.floor((L-w*3600)/60),M=Math.floor(L-w*3600-R*60),k=Math.floor((L-w*3600-R*60-M)*1e3);return""+m(w,2)+":"+m(R,2)+":"+m(M,2)+"."+m(k,3)}for(var T=this.parseSample(f),b="",A=0;A<T.length;A++){var I=T[A];b+=S(o)+" --> "+S(c)+`\r
145
- `,b+=I.payl.text}return b};var y=function(){};y.prototype.parseSample=function(o){var c={},f;c.resources=[];var m=new t(o.data.buffer);if(!o.subsamples||o.subsamples.length===0)c.documentString=m.readString(o.data.length);else if(c.documentString=m.readString(o.subsamples[0].size),o.subsamples.length>1)for(f=1;f<o.subsamples.length;f++)c.resources[f]=m.readUint8Array(o.subsamples[f].size);return typeof DOMParser<"u"&&(c.document=new DOMParser().parseFromString(c.documentString,"application/xml")),c};var x=function(){};x.prototype.parseSample=function(o){var c,f=new t(o.data.buffer);return c=f.readString(o.data.length),c},x.prototype.parseConfig=function(o){var c,f=new t(o.buffer);return f.readUint32(),c=f.readCString(),c},r.VTTin4Parser=g,r.XMLSubtitlein4Parser=y,r.Textin4Parser=x;var v=function(o){this.stream=o||new a,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.items=[],this.entity_groups=[],this.onSidx=null,this.sidxSent=!1};v.prototype.setSegmentOptions=function(o,c,f){var m=this.getTrackById(o);if(m){var S={};this.fragmentedTracks.push(S),S.id=o,S.user=c,S.trak=m,m.nextSample=0,S.segmentStream=null,S.nb_samples=1e3,S.rapAlignement=!0,f&&(f.nbSamples&&(S.nb_samples=f.nbSamples),f.rapAlignement&&(S.rapAlignement=f.rapAlignement))}},v.prototype.unsetSegmentOptions=function(o){for(var c=-1,f=0;f<this.fragmentedTracks.length;f++){var m=this.fragmentedTracks[f];m.id==o&&(c=f)}c>-1&&this.fragmentedTracks.splice(c,1)},v.prototype.setExtractionOptions=function(o,c,f){var m=this.getTrackById(o);if(m){var S={};this.extractedTracks.push(S),S.id=o,S.user=c,S.trak=m,m.nextSample=0,S.nb_samples=1e3,S.samples=[],f&&f.nbSamples&&(S.nb_samples=f.nbSamples)}},v.prototype.unsetExtractionOptions=function(o){for(var c=-1,f=0;f<this.extractedTracks.length;f++){var m=this.extractedTracks[f];m.id==o&&(c=f)}c>-1&&this.extractedTracks.splice(c,1)},v.prototype.parse=function(){var o,c,f=!1;if(!(this.restoreParsePosition&&!this.restoreParsePosition()))for(;;)if(this.hasIncompleteMdat&&this.hasIncompleteMdat()){if(this.processIncompleteMdat())continue;return}else if(this.saveParsePosition&&this.saveParsePosition(),o=l.parseOneBox(this.stream,f),o.code===l.ERR_NOT_ENOUGH_DATA)if(this.processIncompleteBox){if(this.processIncompleteBox(o))continue;return}else return;else{var m;switch(c=o.box,m=c.type!=="uuid"?c.type:c.uuid,this.boxes.push(c),m){case"mdat":this.mdats.push(c);break;case"moof":this.moofs.push(c);break;case"moov":this.moovStartFound=!0,this.mdats.length===0&&(this.isProgressive=!0);default:this[m]!==void 0&&e.warn("ISOFile","Duplicate Box of type: "+m+", overriding previous occurrence"),this[m]=c;break}this.updateUsedBytes&&this.updateUsedBytes(c,o)}},v.prototype.checkBuffer=function(o){if(o==null)throw"Buffer must be defined and non empty";if(o.fileStart===void 0)throw"Buffer must have a fileStart property";return o.byteLength===0?(e.warn("ISOFile","Ignoring empty buffer (fileStart: "+o.fileStart+")"),this.stream.logBufferLevel(),!1):(e.info("ISOFile","Processing buffer (fileStart: "+o.fileStart+")"),o.usedBytes=0,this.stream.insertBuffer(o),this.stream.logBufferLevel(),this.stream.initialized()?!0:(e.warn("ISOFile","Not ready to start parsing"),!1))},v.prototype.appendBuffer=function(o,c){var f;if(this.checkBuffer(o))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(c),this.nextSeekPosition?(f=this.nextSeekPosition,this.nextSeekPosition=void 0):f=this.nextParsePosition,this.stream.getEndFilePositionAfter&&(f=this.stream.getEndFilePositionAfter(f))):this.nextParsePosition?f=this.nextParsePosition:f=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&&(e.info("ISOFile","Done processing buffer (fileStart: "+o.fileStart+") - next buffer to fetch should have a fileStart position of "+f),this.stream.logBufferLevel(),this.stream.cleanBuffers(),this.stream.logBufferLevel(!0),e.info("ISOFile","Sample data size in memory: "+this.getAllocatedSampleDataSize())),f},v.prototype.getInfo=function(){var o,c,f={},m,S,T,b,A=new Date("1904-01-01T00:00:00Z").getTime();if(this.moov)for(f.hasMoov=!0,f.duration=this.moov.mvhd.duration,f.timescale=this.moov.mvhd.timescale,f.isFragmented=this.moov.mvex!=null,f.isFragmented&&this.moov.mvex.mehd&&(f.fragment_duration=this.moov.mvex.mehd.fragment_duration),f.isProgressive=this.isProgressive,f.hasIOD=this.moov.iods!=null,f.brands=[],f.brands.push(this.ftyp.major_brand),f.brands=f.brands.concat(this.ftyp.compatible_brands),f.created=new Date(A+this.moov.mvhd.creation_time*1e3),f.modified=new Date(A+this.moov.mvhd.modification_time*1e3),f.tracks=[],f.audioTracks=[],f.videoTracks=[],f.subtitleTracks=[],f.metadataTracks=[],f.hintTracks=[],f.otherTracks=[],o=0;o<this.moov.traks.length;o++){if(m=this.moov.traks[o],b=m.mdia.minf.stbl.stsd.entries[0],S={},f.tracks.push(S),S.id=m.tkhd.track_id,S.name=m.mdia.hdlr.name,S.references=[],m.tref)for(c=0;c<m.tref.boxes.length;c++)T={},S.references.push(T),T.type=m.tref.boxes[c].type,T.track_ids=m.tref.boxes[c].track_ids;m.edts&&(S.edits=m.edts.elst.entries),S.created=new Date(A+m.tkhd.creation_time*1e3),S.modified=new Date(A+m.tkhd.modification_time*1e3),S.movie_duration=m.tkhd.duration,S.movie_timescale=f.timescale,S.layer=m.tkhd.layer,S.alternate_group=m.tkhd.alternate_group,S.volume=m.tkhd.volume,S.matrix=m.tkhd.matrix,S.track_width=m.tkhd.width/65536,S.track_height=m.tkhd.height/65536,S.timescale=m.mdia.mdhd.timescale,S.cts_shift=m.mdia.minf.stbl.cslg,S.duration=m.mdia.mdhd.duration,S.samples_duration=m.samples_duration,S.codec=b.getCodec(),S.kind=m.udta&&m.udta.kinds.length?m.udta.kinds[0]:{schemeURI:"",value:""},S.language=m.mdia.elng?m.mdia.elng.extended_language:m.mdia.mdhd.languageString,S.nb_samples=m.samples.length,S.size=m.samples_size,S.bitrate=S.size*8*S.timescale/S.samples_duration,b.isAudio()?(S.type="audio",f.audioTracks.push(S),S.audio={},S.audio.sample_rate=b.getSampleRate(),S.audio.channel_count=b.getChannelCount(),S.audio.sample_size=b.getSampleSize()):b.isVideo()?(S.type="video",f.videoTracks.push(S),S.video={},S.video.width=b.getWidth(),S.video.height=b.getHeight()):b.isSubtitle()?(S.type="subtitles",f.subtitleTracks.push(S)):b.isHint()?(S.type="metadata",f.hintTracks.push(S)):b.isMetadata()?(S.type="metadata",f.metadataTracks.push(S)):(S.type="metadata",f.otherTracks.push(S))}else f.hasMoov=!1;if(f.mime="",f.hasMoov&&f.tracks){for(f.videoTracks&&f.videoTracks.length>0?f.mime+='video/mp4; codecs="':f.audioTracks&&f.audioTracks.length>0?f.mime+='audio/mp4; codecs="':f.mime+='application/mp4; codecs="',o=0;o<f.tracks.length;o++)o!==0&&(f.mime+=","),f.mime+=f.tracks[o].codec;f.mime+='"; profiles="',f.mime+=this.ftyp.compatible_brands.join(),f.mime+='"'}return f},v.prototype.setNextSeekPositionFromSample=function(o){o&&(this.nextSeekPosition?this.nextSeekPosition=Math.min(o.offset+o.alreadyRead,this.nextSeekPosition):this.nextSeekPosition=o.offset+o.alreadyRead)},v.prototype.processSamples=function(o){var c,f;if(this.sampleProcessingStarted){if(this.isFragmentationInitialized&&this.onSegment!==null)for(c=0;c<this.fragmentedTracks.length;c++){var m=this.fragmentedTracks[c];for(f=m.trak;f.nextSample<f.samples.length&&this.sampleProcessingStarted;){e.debug("ISOFile","Creating media fragment on track #"+m.id+" for sample "+f.nextSample);var S=this.createFragment(m.id,f.nextSample,m.segmentStream);if(S)m.segmentStream=S,f.nextSample++;else break;if((f.nextSample%m.nb_samples===0||o||f.nextSample>=f.samples.length)&&(e.info("ISOFile","Sending fragmented data on track #"+m.id+" for samples ["+Math.max(0,f.nextSample-m.nb_samples)+","+(f.nextSample-1)+"]"),e.info("ISOFile","Sample data size in memory: "+this.getAllocatedSampleDataSize()),this.onSegment&&this.onSegment(m.id,m.user,m.segmentStream.buffer,f.nextSample,o||f.nextSample>=f.samples.length),m.segmentStream=null,m!==this.fragmentedTracks[c]))break}}if(this.onSamples!==null)for(c=0;c<this.extractedTracks.length;c++){var T=this.extractedTracks[c];for(f=T.trak;f.nextSample<f.samples.length&&this.sampleProcessingStarted;){e.debug("ISOFile","Exporting on track #"+T.id+" sample #"+f.nextSample);var b=this.getSample(f,f.nextSample);if(b)f.nextSample++,T.samples.push(b);else{this.setNextSeekPositionFromSample(f.samples[f.nextSample]);break}if((f.nextSample%T.nb_samples===0||f.nextSample>=f.samples.length)&&(e.debug("ISOFile","Sending samples on track #"+T.id+" for sample "+f.nextSample),this.onSamples&&this.onSamples(T.id,T.user,T.samples),T.samples=[],T!==this.extractedTracks[c]))break}}}},v.prototype.getBox=function(o){var c=this.getBoxes(o,!0);return c.length?c[0]:null},v.prototype.getBoxes=function(o,c){var f=[];return v._sweep.call(this,o,f,c),f},v._sweep=function(o,c,f){this.type&&this.type==o&&c.push(this);for(var m in this.boxes){if(c.length&&f)return;v._sweep.call(this.boxes[m],o,c,f)}},v.prototype.getTrackSamplesInfo=function(o){var c=this.getTrackById(o);if(c)return c.samples},v.prototype.getTrackSample=function(o,c){var f=this.getTrackById(o),m=this.getSample(f,c);return m},v.prototype.releaseUsedSamples=function(o,c){var f=0,m=this.getTrackById(o);m.lastValidSample||(m.lastValidSample=0);for(var S=m.lastValidSample;S<c;S++)f+=this.releaseSample(m,S);e.info("ISOFile","Track #"+o+" released samples up to "+c+" (released size: "+f+", remaining: "+this.samplesDataSize+")"),m.lastValidSample=c},v.prototype.start=function(){this.sampleProcessingStarted=!0,this.processSamples(!1)},v.prototype.stop=function(){this.sampleProcessingStarted=!1},v.prototype.flush=function(){e.info("ISOFile","Flushing remaining samples"),this.updateSampleLists(),this.processSamples(!0),this.stream.cleanBuffers(),this.stream.logBufferLevel(!0)},v.prototype.seekTrack=function(o,c,f){var m,S,T=1/0,b=0,A=0,I;if(f.samples.length===0)return e.info("ISOFile","No sample in track, cannot seek! Using time "+e.getDurationString(0,1)+" and offset: 0"),{offset:0,time:0};for(m=0;m<f.samples.length;m++){if(S=f.samples[m],m===0)A=0,I=S.timescale;else if(S.cts>o*S.timescale){A=m-1;break}c&&S.is_sync&&(b=m)}for(c&&(A=b),o=f.samples[A].cts,f.nextSample=A;f.samples[A].alreadyRead===f.samples[A].size&&f.samples[A+1];)A++;return T=f.samples[A].offset+f.samples[A].alreadyRead,e.info("ISOFile","Seeking to "+(c?"RAP":"")+" sample #"+f.nextSample+" on track "+f.tkhd.track_id+", time "+e.getDurationString(o,I)+" and offset: "+T),{offset:T,time:o/I}},v.prototype.getTrackDuration=function(o){var c;return o.samples?(c=o.samples[o.samples.length-1],(c.cts+c.duration)/c.timescale):1/0},v.prototype.seek=function(o,c){var f=this.moov,m,S,T,b={offset:1/0,time:1/0};if(this.moov){for(T=0;T<f.traks.length;T++)m=f.traks[T],!(o>this.getTrackDuration(m))&&(S=this.seekTrack(o,c,m),S.offset<b.offset&&(b.offset=S.offset),S.time<b.time&&(b.time=S.time));return e.info("ISOFile","Seeking at time "+e.getDurationString(b.time,1)+" needs a buffer with a fileStart position of "+b.offset),b.offset===1/0?b={offset:this.nextParsePosition,time:0}:b.offset=this.stream.getEndFilePositionAfter(b.offset),e.info("ISOFile","Adjusted seek position (after checking data already in buffer): "+b.offset),b}else throw"Cannot seek: moov not received!"},v.prototype.equal=function(o){for(var c=0;c<this.boxes.length&&c<o.boxes.length;){var f=this.boxes[c],m=o.boxes[c];if(!l.boxEqual(f,m))return!1;c++}return!0},r.ISOFile=v,v.prototype.lastBoxStartPosition=0,v.prototype.parsingMdat=null,v.prototype.nextParsePosition=0,v.prototype.discardMdatData=!1,v.prototype.processIncompleteBox=function(o){var c,f,m;return o.type==="mdat"?(c=new l[o.type+"Box"](o.size),this.parsingMdat=c,this.boxes.push(c),this.mdats.push(c),c.start=o.start,c.hdr_size=o.hdr_size,this.stream.addUsedBytes(c.hdr_size),this.lastBoxStartPosition=c.start+c.size,m=this.stream.seek(c.start+c.size,!1,this.discardMdatData),m?(this.parsingMdat=null,!0):(this.moovStartFound?this.nextParsePosition=this.stream.findEndContiguousBuf():this.nextParsePosition=c.start+c.size,!1)):(o.type==="moov"&&(this.moovStartFound=!0,this.mdats.length===0&&(this.isProgressive=!0)),f=this.stream.mergeNextBuffer?this.stream.mergeNextBuffer():!1,f?(this.nextParsePosition=this.stream.getEndPosition(),!0):(o.type?this.moovStartFound?this.nextParsePosition=this.stream.getEndPosition():this.nextParsePosition=this.stream.getPosition()+o.size:this.nextParsePosition=this.stream.getEndPosition(),!1))},v.prototype.hasIncompleteMdat=function(){return this.parsingMdat!==null},v.prototype.processIncompleteMdat=function(){var o,c;return o=this.parsingMdat,c=this.stream.seek(o.start+o.size,!1,this.discardMdatData),c?(e.debug("ISOFile","Found 'mdat' end in buffered data"),this.parsingMdat=null,!0):(this.nextParsePosition=this.stream.findEndContiguousBuf(),!1)},v.prototype.restoreParsePosition=function(){return this.stream.seek(this.lastBoxStartPosition,!0,this.discardMdatData)},v.prototype.saveParsePosition=function(){this.lastBoxStartPosition=this.stream.getPosition()},v.prototype.updateUsedBytes=function(o,c){this.stream.addUsedBytes&&(o.type==="mdat"?(this.stream.addUsedBytes(o.hdr_size),this.discardMdatData&&this.stream.addUsedBytes(o.size-o.hdr_size)):this.stream.addUsedBytes(o.size))},v.prototype.add=l.Box.prototype.add,v.prototype.addBox=l.Box.prototype.addBox,v.prototype.init=function(o){var c=o||{};this.add("ftyp").set("major_brand",c.brands&&c.brands[0]||"iso4").set("minor_version",0).set("compatible_brands",c.brands||["iso4"]);var f=this.add("moov");return f.add("mvhd").set("timescale",c.timescale||600).set("rate",c.rate||65536).set("creation_time",0).set("modification_time",0).set("duration",c.duration||0).set("volume",c.width?0:256).set("matrix",[65536,0,0,0,65536,0,0,0,1073741824]).set("next_track_id",1),f.add("mvex"),this},v.prototype.addTrack=function(o){this.moov||this.init(o);var c=o||{};c.width=c.width||320,c.height=c.height||320,c.id=c.id||this.moov.mvhd.next_track_id,c.type=c.type||"avc1";var f=this.moov.add("trak");this.moov.mvhd.next_track_id=c.id+1,f.add("tkhd").set("flags",l.TKHD_FLAG_ENABLED|l.TKHD_FLAG_IN_MOVIE|l.TKHD_FLAG_IN_PREVIEW).set("creation_time",0).set("modification_time",0).set("track_id",c.id).set("duration",c.duration||0).set("layer",c.layer||0).set("alternate_group",0).set("volume",1).set("matrix",[65536,0,0,0,65536,0,0,0,1073741824]).set("width",c.width<<16).set("height",c.height<<16);var m=f.add("mdia");m.add("mdhd").set("creation_time",0).set("modification_time",0).set("timescale",c.timescale||1).set("duration",c.media_duration||0).set("language",c.language||"und"),m.add("hdlr").set("handler",c.hdlr||"vide").set("name",c.name||"Track created with MP4Box.js"),m.add("elng").set("extended_language",c.language||"fr-FR");var S=m.add("minf");if(l[c.type+"SampleEntry"]!==void 0){var T=new l[c.type+"SampleEntry"];T.data_reference_index=1;var b="";for(var A in l.sampleEntryCodes)for(var I=l.sampleEntryCodes[A],L=0;L<I.length;L++)if(I.indexOf(c.type)>-1){b=A;break}switch(b){case"Visual":if(S.add("vmhd").set("graphicsmode",0).set("opcolor",[0,0,0]),T.set("width",c.width).set("height",c.height).set("horizresolution",72<<16).set("vertresolution",72<<16).set("frame_count",1).set("compressorname",c.type+" Compressor").set("depth",24),c.avcDecoderConfigRecord){var w=new l.avcCBox;w.parse(new t(c.avcDecoderConfigRecord)),T.addBox(w)}else if(c.hevcDecoderConfigRecord){var R=new l.hvcCBox;R.parse(new t(c.hevcDecoderConfigRecord)),T.addBox(R)}break;case"Audio":S.add("smhd").set("balance",c.balance||0),T.set("channel_count",c.channel_count||2).set("samplesize",c.samplesize||16).set("samplerate",c.samplerate||65536);break;case"Hint":S.add("hmhd");break;case"Subtitle":switch(S.add("sthd"),c.type){case"stpp":T.set("namespace",c.namespace||"nonamespace").set("schema_location",c.schema_location||"").set("auxiliary_mime_types",c.auxiliary_mime_types||"");break}break;case"Metadata":S.add("nmhd");break;case"System":S.add("nmhd");break;default:S.add("nmhd");break}c.description&&T.addBox(c.description),c.description_boxes&&c.description_boxes.forEach(function(k){T.addBox(k)}),S.add("dinf").add("dref").addEntry(new l["url Box"]().set("flags",1));var M=S.add("stbl");return M.add("stsd").addEntry(T),M.add("stts").set("sample_counts",[]).set("sample_deltas",[]),M.add("stsc").set("first_chunk",[]).set("samples_per_chunk",[]).set("sample_description_index",[]),M.add("stco").set("chunk_offsets",[]),M.add("stsz").set("sample_sizes",[]),this.moov.mvex.add("trex").set("track_id",c.id).set("default_sample_description_index",c.default_sample_description_index||1).set("default_sample_duration",c.default_sample_duration||0).set("default_sample_size",c.default_sample_size||0).set("default_sample_flags",c.default_sample_flags||0),this.buildTrakSampleLists(f),c.id}},l.Box.prototype.computeSize=function(o){var c=o||new s;c.endianness=s.BIG_ENDIAN,this.write(c)},v.prototype.addSample=function(o,c,f){var m=f||{},S={},T=this.getTrackById(o);if(T!==null){S.number=T.samples.length,S.track_id=T.tkhd.track_id,S.timescale=T.mdia.mdhd.timescale,S.description_index=m.sample_description_index?m.sample_description_index-1:0,S.description=T.mdia.minf.stbl.stsd.entries[S.description_index],S.data=c,S.size=c.byteLength,S.alreadyRead=S.size,S.duration=m.duration||1,S.cts=m.cts||0,S.dts=m.dts||0,S.is_sync=m.is_sync||!1,S.is_leading=m.is_leading||0,S.depends_on=m.depends_on||0,S.is_depended_on=m.is_depended_on||0,S.has_redundancy=m.has_redundancy||0,S.degradation_priority=m.degradation_priority||0,S.offset=0,S.subsamples=m.subsamples,T.samples.push(S),T.samples_size+=S.size,T.samples_duration+=S.duration,T.first_dts===void 0&&(T.first_dts=m.dts),this.processSamples();var b=this.createSingleSampleMoof(S);return this.addBox(b),b.computeSize(),b.trafs[0].truns[0].data_offset=b.size+8,this.add("mdat").data=new Uint8Array(c),S}},v.prototype.createSingleSampleMoof=function(o){var c=0;o.is_sync?c=1<<25:c=65536;var f=new l.moofBox;f.add("mfhd").set("sequence_number",this.nextMoofNumber),this.nextMoofNumber++;var m=f.add("traf"),S=this.getTrackById(o.track_id);return m.add("tfhd").set("track_id",o.track_id).set("flags",l.TFHD_FLAG_DEFAULT_BASE_IS_MOOF),m.add("tfdt").set("baseMediaDecodeTime",o.dts-(S.first_dts||0)),m.add("trun").set("flags",l.TRUN_FLAGS_DATA_OFFSET|l.TRUN_FLAGS_DURATION|l.TRUN_FLAGS_SIZE|l.TRUN_FLAGS_FLAGS|l.TRUN_FLAGS_CTS_OFFSET).set("data_offset",0).set("first_sample_flags",0).set("sample_count",1).set("sample_duration",[o.duration]).set("sample_size",[o.size]).set("sample_flags",[c]).set("sample_composition_time_offset",[o.cts-o.dts]),f},v.prototype.lastMoofIndex=0,v.prototype.samplesDataSize=0,v.prototype.resetTables=function(){var o,c,f,m,S,T,b,A;for(this.initial_duration=this.moov.mvhd.duration,this.moov.mvhd.duration=0,o=0;o<this.moov.traks.length;o++){c=this.moov.traks[o],c.tkhd.duration=0,c.mdia.mdhd.duration=0,f=c.mdia.minf.stbl.stco||c.mdia.minf.stbl.co64,f.chunk_offsets=[],m=c.mdia.minf.stbl.stsc,m.first_chunk=[],m.samples_per_chunk=[],m.sample_description_index=[],S=c.mdia.minf.stbl.stsz||c.mdia.minf.stbl.stz2,S.sample_sizes=[],T=c.mdia.minf.stbl.stts,T.sample_counts=[],T.sample_deltas=[],b=c.mdia.minf.stbl.ctts,b&&(b.sample_counts=[],b.sample_offsets=[]),A=c.mdia.minf.stbl.stss;var I=c.mdia.minf.stbl.boxes.indexOf(A);I!=-1&&(c.mdia.minf.stbl.boxes[I]=null)}},v.initSampleGroups=function(o,c,f,m,S){var T,b,A,I;function L(w,R,M){this.grouping_type=w,this.grouping_type_parameter=R,this.sbgp=M,this.last_sample_in_run=-1,this.entry_index=-1}for(c&&(c.sample_groups_info=[]),o.sample_groups_info||(o.sample_groups_info=[]),b=0;b<f.length;b++){for(I=f[b].grouping_type+"/"+f[b].grouping_type_parameter,A=new L(f[b].grouping_type,f[b].grouping_type_parameter,f[b]),c&&(c.sample_groups_info[I]=A),o.sample_groups_info[I]||(o.sample_groups_info[I]=A),T=0;T<m.length;T++)m[T].grouping_type===f[b].grouping_type&&(A.description=m[T],A.description.used=!0);if(S)for(T=0;T<S.length;T++)S[T].grouping_type===f[b].grouping_type&&(A.fragment_description=S[T],A.fragment_description.used=!0,A.is_fragment=!0)}if(c){if(S)for(b=0;b<S.length;b++)!S[b].used&&S[b].version>=2&&(I=S[b].grouping_type+"/0",A=new L(S[b].grouping_type,0),A.is_fragment=!0,c.sample_groups_info[I]||(c.sample_groups_info[I]=A))}else for(b=0;b<m.length;b++)!m[b].used&&m[b].version>=2&&(I=m[b].grouping_type+"/0",A=new L(m[b].grouping_type,0),o.sample_groups_info[I]||(o.sample_groups_info[I]=A))},v.setSampleGroupProperties=function(o,c,f,m){var S,T;c.sample_groups=[];for(S in m)if(c.sample_groups[S]={},c.sample_groups[S].grouping_type=m[S].grouping_type,c.sample_groups[S].grouping_type_parameter=m[S].grouping_type_parameter,f>=m[S].last_sample_in_run&&(m[S].last_sample_in_run<0&&(m[S].last_sample_in_run=0),m[S].entry_index++,m[S].entry_index<=m[S].sbgp.entries.length-1&&(m[S].last_sample_in_run+=m[S].sbgp.entries[m[S].entry_index].sample_count)),m[S].entry_index<=m[S].sbgp.entries.length-1?c.sample_groups[S].group_description_index=m[S].sbgp.entries[m[S].entry_index].group_description_index:c.sample_groups[S].group_description_index=-1,c.sample_groups[S].group_description_index!==0){var b;m[S].fragment_description?b=m[S].fragment_description:b=m[S].description,c.sample_groups[S].group_description_index>0?(c.sample_groups[S].group_description_index>65535?T=(c.sample_groups[S].group_description_index>>16)-1:T=c.sample_groups[S].group_description_index-1,b&&T>=0&&(c.sample_groups[S].description=b.entries[T])):b&&b.version>=2&&b.default_group_description_index>0&&(c.sample_groups[S].description=b.entries[b.default_group_description_index-1])}},v.process_sdtp=function(o,c,f){c&&(o?(c.is_leading=o.is_leading[f],c.depends_on=o.sample_depends_on[f],c.is_depended_on=o.sample_is_depended_on[f],c.has_redundancy=o.sample_has_redundancy[f]):(c.is_leading=0,c.depends_on=0,c.is_depended_on=0,c.has_redundancy=0))},v.prototype.buildSampleLists=function(){var o,c;for(o=0;o<this.moov.traks.length;o++)c=this.moov.traks[o],this.buildTrakSampleLists(c)},v.prototype.buildTrakSampleLists=function(o){var c,f,m,S,T,b,A,I,L,w,R,M,k,z,O,U,j,H,V,J,$,G,ie,ce;if(o.samples=[],o.samples_duration=0,o.samples_size=0,f=o.mdia.minf.stbl.stco||o.mdia.minf.stbl.co64,m=o.mdia.minf.stbl.stsc,S=o.mdia.minf.stbl.stsz||o.mdia.minf.stbl.stz2,T=o.mdia.minf.stbl.stts,b=o.mdia.minf.stbl.ctts,A=o.mdia.minf.stbl.stss,I=o.mdia.minf.stbl.stsd,L=o.mdia.minf.stbl.subs,M=o.mdia.minf.stbl.stdp,w=o.mdia.minf.stbl.sbgps,R=o.mdia.minf.stbl.sgpds,H=-1,V=-1,J=-1,$=-1,G=0,ie=0,ce=0,v.initSampleGroups(o,null,w,R),!(typeof S>"u")){for(c=0;c<S.sample_sizes.length;c++){var K={};K.number=c,K.track_id=o.tkhd.track_id,K.timescale=o.mdia.mdhd.timescale,K.alreadyRead=0,o.samples[c]=K,K.size=S.sample_sizes[c],o.samples_size+=K.size,c===0?(z=1,k=0,K.chunk_index=z,K.chunk_run_index=k,j=m.samples_per_chunk[k],U=0,k+1<m.first_chunk.length?O=m.first_chunk[k+1]-1:O=1/0):c<j?(K.chunk_index=z,K.chunk_run_index=k):(z++,K.chunk_index=z,U=0,z<=O||(k++,k+1<m.first_chunk.length?O=m.first_chunk[k+1]-1:O=1/0),K.chunk_run_index=k,j+=m.samples_per_chunk[k]),K.description_index=m.sample_description_index[K.chunk_run_index]-1,K.description=I.entries[K.description_index],K.offset=f.chunk_offsets[K.chunk_index-1]+U,U+=K.size,c>H&&(V++,H<0&&(H=0),H+=T.sample_counts[V]),c>0?(o.samples[c-1].duration=T.sample_deltas[V],o.samples_duration+=o.samples[c-1].duration,K.dts=o.samples[c-1].dts+o.samples[c-1].duration):K.dts=0,b?(c>=J&&($++,J<0&&(J=0),J+=b.sample_counts[$]),K.cts=o.samples[c].dts+b.sample_offsets[$]):K.cts=K.dts,A?(c==A.sample_numbers[G]-1?(K.is_sync=!0,G++):(K.is_sync=!1,K.degradation_priority=0),L&&L.entries[ie].sample_delta+ce==c+1&&(K.subsamples=L.entries[ie].subsamples,ce+=L.entries[ie].sample_delta,ie++)):K.is_sync=!0,v.process_sdtp(o.mdia.minf.stbl.sdtp,K,K.number),M?K.degradation_priority=M.priority[c]:K.degradation_priority=0,L&&L.entries[ie].sample_delta+ce==c&&(K.subsamples=L.entries[ie].subsamples,ce+=L.entries[ie].sample_delta),(w.length>0||R.length>0)&&v.setSampleGroupProperties(o,K,c,o.sample_groups_info)}c>0&&(o.samples[c-1].duration=Math.max(o.mdia.mdhd.duration-o.samples[c-1].dts,0),o.samples_duration+=o.samples[c-1].duration)}},v.prototype.updateSampleLists=function(){var o,c,f,m,S,T,b,A,I,L,w,R,M,k,z;if(this.moov!==void 0){for(;this.lastMoofIndex<this.moofs.length;)if(I=this.moofs[this.lastMoofIndex],this.lastMoofIndex++,I.type=="moof")for(L=I,o=0;o<L.trafs.length;o++){for(w=L.trafs[o],R=this.getTrackById(w.tfhd.track_id),M=this.getTrexById(w.tfhd.track_id),w.tfhd.flags&l.TFHD_FLAG_SAMPLE_DESC?m=w.tfhd.default_sample_description_index:m=M?M.default_sample_description_index:1,w.tfhd.flags&l.TFHD_FLAG_SAMPLE_DUR?S=w.tfhd.default_sample_duration:S=M?M.default_sample_duration:0,w.tfhd.flags&l.TFHD_FLAG_SAMPLE_SIZE?T=w.tfhd.default_sample_size:T=M?M.default_sample_size:0,w.tfhd.flags&l.TFHD_FLAG_SAMPLE_FLAGS?b=w.tfhd.default_sample_flags:b=M?M.default_sample_flags:0,w.sample_number=0,w.sbgps.length>0&&v.initSampleGroups(R,w,w.sbgps,R.mdia.minf.stbl.sgpds,w.sgpds),c=0;c<w.truns.length;c++){var O=w.truns[c];for(f=0;f<O.sample_count;f++){k={},k.moof_number=this.lastMoofIndex,k.number_in_traf=w.sample_number,w.sample_number++,k.number=R.samples.length,w.first_sample_index=R.samples.length,R.samples.push(k),k.track_id=R.tkhd.track_id,k.timescale=R.mdia.mdhd.timescale,k.description_index=m-1,k.description=R.mdia.minf.stbl.stsd.entries[k.description_index],k.size=T,O.flags&l.TRUN_FLAGS_SIZE&&(k.size=O.sample_size[f]),R.samples_size+=k.size,k.duration=S,O.flags&l.TRUN_FLAGS_DURATION&&(k.duration=O.sample_duration[f]),R.samples_duration+=k.duration,R.first_traf_merged||f>0?k.dts=R.samples[R.samples.length-2].dts+R.samples[R.samples.length-2].duration:(w.tfdt?k.dts=w.tfdt.baseMediaDecodeTime:k.dts=0,R.first_traf_merged=!0),k.cts=k.dts,O.flags&l.TRUN_FLAGS_CTS_OFFSET&&(k.cts=k.dts+O.sample_composition_time_offset[f]),z=b,O.flags&l.TRUN_FLAGS_FLAGS?z=O.sample_flags[f]:f===0&&O.flags&l.TRUN_FLAGS_FIRST_FLAG&&(z=O.first_sample_flags),k.is_sync=!(z>>16&1),k.is_leading=z>>26&3,k.depends_on=z>>24&3,k.is_depended_on=z>>22&3,k.has_redundancy=z>>20&3,k.degradation_priority=z&65535;var U=!!(w.tfhd.flags&l.TFHD_FLAG_BASE_DATA_OFFSET),j=!!(w.tfhd.flags&l.TFHD_FLAG_DEFAULT_BASE_IS_MOOF),H=!!(O.flags&l.TRUN_FLAGS_DATA_OFFSET),V=0;U?V=w.tfhd.base_data_offset:j||c===0?V=L.start:V=A,c===0&&f===0?H?k.offset=V+O.data_offset:k.offset=V:k.offset=A,A=k.offset+k.size,(w.sbgps.length>0||w.sgpds.length>0||R.mdia.minf.stbl.sbgps.length>0||R.mdia.minf.stbl.sgpds.length>0)&&v.setSampleGroupProperties(R,k,k.number_in_traf,w.sample_groups_info)}}if(w.subs){R.has_fragment_subsamples=!0;var J=w.first_sample_index;for(c=0;c<w.subs.entries.length;c++)J+=w.subs.entries[c].sample_delta,k=R.samples[J-1],k.subsamples=w.subs.entries[c].subsamples}}}},v.prototype.getSample=function(o,c){var f,m=o.samples[c];if(!this.moov)return null;if(!m.data)m.data=new Uint8Array(m.size),m.alreadyRead=0,this.samplesDataSize+=m.size,e.debug("ISOFile","Allocating sample #"+c+" on track #"+o.tkhd.track_id+" of size "+m.size+" (total: "+this.samplesDataSize+")");else if(m.alreadyRead==m.size)return m;for(;;){var S=this.stream.findPosition(!0,m.offset+m.alreadyRead,!1);if(S>-1){f=this.stream.buffers[S];var T=f.byteLength-(m.offset+m.alreadyRead-f.fileStart);if(m.size-m.alreadyRead<=T)return e.debug("ISOFile","Getting sample #"+c+" data (alreadyRead: "+m.alreadyRead+" offset: "+(m.offset+m.alreadyRead-f.fileStart)+" read size: "+(m.size-m.alreadyRead)+" full size: "+m.size+")"),s.memcpy(m.data.buffer,m.alreadyRead,f,m.offset+m.alreadyRead-f.fileStart,m.size-m.alreadyRead),f.usedBytes+=m.size-m.alreadyRead,this.stream.logBufferLevel(),m.alreadyRead=m.size,m;if(T===0)return null;e.debug("ISOFile","Getting sample #"+c+" partial data (alreadyRead: "+m.alreadyRead+" offset: "+(m.offset+m.alreadyRead-f.fileStart)+" read size: "+T+" full size: "+m.size+")"),s.memcpy(m.data.buffer,m.alreadyRead,f,m.offset+m.alreadyRead-f.fileStart,T),m.alreadyRead+=T,f.usedBytes+=T,this.stream.logBufferLevel()}else return null}},v.prototype.releaseSample=function(o,c){var f=o.samples[c];return f.data?(this.samplesDataSize-=f.size,f.data=null,f.alreadyRead=0,f.size):0},v.prototype.getAllocatedSampleDataSize=function(){return this.samplesDataSize},v.prototype.getCodecs=function(){var o,c="";for(o=0;o<this.moov.traks.length;o++){var f=this.moov.traks[o];o>0&&(c+=","),c+=f.mdia.minf.stbl.stsd.entries[0].getCodec()}return c},v.prototype.getTrexById=function(o){var c;if(!this.moov||!this.moov.mvex)return null;for(c=0;c<this.moov.mvex.trexs.length;c++){var f=this.moov.mvex.trexs[c];if(f.track_id==o)return f}return null},v.prototype.getTrackById=function(o){if(this.moov===void 0)return null;for(var c=0;c<this.moov.traks.length;c++){var f=this.moov.traks[c];if(f.tkhd.track_id==o)return f}return null},v.prototype.itemsDataSize=0,v.prototype.flattenItemInfo=function(){var o=this.items,c=this.entity_groups,f,m,S,T=this.meta;if(T!=null&&T.hdlr!==void 0&&T.iinf!==void 0){for(f=0;f<T.iinf.item_infos.length;f++)S={},S.id=T.iinf.item_infos[f].item_ID,o[S.id]=S,S.ref_to=[],S.name=T.iinf.item_infos[f].item_name,T.iinf.item_infos[f].protection_index>0&&(S.protection=T.ipro.protections[T.iinf.item_infos[f].protection_index-1]),T.iinf.item_infos[f].item_type?S.type=T.iinf.item_infos[f].item_type:S.type="mime",S.content_type=T.iinf.item_infos[f].content_type,S.content_encoding=T.iinf.item_infos[f].content_encoding,S.item_uri_type=T.iinf.item_infos[f].item_uri_type;if(T.grpl)for(f=0;f<T.grpl.boxes.length;f++)entity_group={},entity_group.id=T.grpl.boxes[f].group_id,entity_group.entity_ids=T.grpl.boxes[f].entity_ids,entity_group.type=T.grpl.boxes[f].type,c[entity_group.id]=entity_group;if(T.iloc)for(f=0;f<T.iloc.items.length;f++){var b=T.iloc.items[f];switch(S=o[b.item_ID],b.data_reference_index!==0&&(e.warn("Item storage with reference to other files: not supported"),S.source=T.dinf.boxes[b.data_reference_index-1]),b.construction_method){case 0:break;case 1:break;case 2:e.warn("Item storage with construction_method : not supported");break}for(S.extents=[],S.size=0,m=0;m<b.extents.length;m++)S.extents[m]={},S.extents[m].offset=b.extents[m].extent_offset+b.base_offset,b.construction_method==1&&(S.extents[m].offset+=T.idat.start+T.idat.hdr_size),S.extents[m].length=b.extents[m].extent_length,S.extents[m].alreadyRead=0,S.size+=S.extents[m].length}if(T.pitm&&(o[T.pitm.item_id].primary=!0),T.iref)for(f=0;f<T.iref.references.length;f++){var A=T.iref.references[f];for(m=0;m<A.references.length;m++)o[A.from_item_ID].ref_to.push({type:A.type,id:A.references[m]})}if(T.iprp)for(var I=0;I<T.iprp.ipmas.length;I++){var L=T.iprp.ipmas[I];for(f=0;f<L.associations.length;f++){var w=L.associations[f];if(S=o[w.id],S||(S=c[w.id]),S)for(S.properties===void 0&&(S.properties={},S.properties.boxes=[]),m=0;m<w.props.length;m++){var R=w.props[m];if(R.property_index>0&&R.property_index-1<T.iprp.ipco.boxes.length){var M=T.iprp.ipco.boxes[R.property_index-1];S.properties[M.type]=M,S.properties.boxes.push(M)}}}}}},v.prototype.getItem=function(o){var c,f;if(!this.meta)return null;if(f=this.items[o],!f.data&&f.size)f.data=new Uint8Array(f.size),f.alreadyRead=0,this.itemsDataSize+=f.size,e.debug("ISOFile","Allocating item #"+o+" of size "+f.size+" (total: "+this.itemsDataSize+")");else if(f.alreadyRead===f.size)return f;for(var m=0;m<f.extents.length;m++){var S=f.extents[m];if(S.alreadyRead!==S.length){var T=this.stream.findPosition(!0,S.offset+S.alreadyRead,!1);if(T>-1){c=this.stream.buffers[T];var b=c.byteLength-(S.offset+S.alreadyRead-c.fileStart);if(S.length-S.alreadyRead<=b)e.debug("ISOFile","Getting item #"+o+" extent #"+m+" data (alreadyRead: "+S.alreadyRead+" offset: "+(S.offset+S.alreadyRead-c.fileStart)+" read size: "+(S.length-S.alreadyRead)+" full extent size: "+S.length+" full item size: "+f.size+")"),s.memcpy(f.data.buffer,f.alreadyRead,c,S.offset+S.alreadyRead-c.fileStart,S.length-S.alreadyRead),c.usedBytes+=S.length-S.alreadyRead,this.stream.logBufferLevel(),f.alreadyRead+=S.length-S.alreadyRead,S.alreadyRead=S.length;else return e.debug("ISOFile","Getting item #"+o+" extent #"+m+" partial data (alreadyRead: "+S.alreadyRead+" offset: "+(S.offset+S.alreadyRead-c.fileStart)+" read size: "+b+" full extent size: "+S.length+" full item size: "+f.size+")"),s.memcpy(f.data.buffer,f.alreadyRead,c,S.offset+S.alreadyRead-c.fileStart,b),S.alreadyRead+=b,f.alreadyRead+=b,c.usedBytes+=b,this.stream.logBufferLevel(),null}else return null}}return f.alreadyRead===f.size?f:null},v.prototype.releaseItem=function(o){var c=this.items[o];if(c.data){this.itemsDataSize-=c.size,c.data=null,c.alreadyRead=0;for(var f=0;f<c.extents.length;f++){var m=c.extents[f];m.alreadyRead=0}return c.size}else return 0},v.prototype.processItems=function(o){for(var c in this.items){var f=this.items[c];this.getItem(f.id),o&&!f.sent&&(o(f),f.sent=!0,f.data=null)}},v.prototype.hasItem=function(o){for(var c in this.items){var f=this.items[c];if(f.name===o)return f.id}return-1},v.prototype.getMetaHandler=function(){return this.meta?this.meta.hdlr.handler:null},v.prototype.getPrimaryItem=function(){return!this.meta||!this.meta.pitm?null:this.getItem(this.meta.pitm.item_id)},v.prototype.itemToFragmentedTrackFile=function(o){var c=o||{},f=null;if(c.itemId?f=this.getItem(c.itemId):f=this.getPrimaryItem(),f==null)return null;var m=new v;m.discardMdatData=!1;var S={type:f.type,description_boxes:f.properties.boxes};f.properties.ispe&&(S.width=f.properties.ispe.image_width,S.height=f.properties.ispe.image_height);var T=m.addTrack(S);return T?(m.addSample(T,f.data),m):null},v.prototype.write=function(o){for(var c=0;c<this.boxes.length;c++)this.boxes[c].write(o)},v.prototype.createFragment=function(o,c,f){var m=this.getTrackById(o),S=this.getSample(m,c);if(S==null)return this.setNextSeekPositionFromSample(m.samples[c]),null;var T=f||new s;T.endianness=s.BIG_ENDIAN;var b=this.createSingleSampleMoof(S);b.write(T),b.trafs[0].truns[0].data_offset=b.size+8,e.debug("MP4Box","Adjusting data_offset with new value "+b.trafs[0].truns[0].data_offset),T.adjustUint32(b.trafs[0].truns[0].data_offset_position,b.trafs[0].truns[0].data_offset);var A=new l.mdatBox;return A.data=S.data,A.write(T),T},v.writeInitializationSegment=function(o,c,f,m){var S;e.debug("ISOFile","Generating initialization segment");var T=new s;T.endianness=s.BIG_ENDIAN,o.write(T);var b=c.add("mvex");for(f&&b.add("mehd").set("fragment_duration",f),S=0;S<c.traks.length;S++)b.add("trex").set("track_id",c.traks[S].tkhd.track_id).set("default_sample_description_index",1).set("default_sample_duration",m).set("default_sample_size",0).set("default_sample_flags",65536);return c.write(T),T.buffer},v.prototype.save=function(o){var c=new s;c.endianness=s.BIG_ENDIAN,this.write(c),c.save(o)},v.prototype.getBuffer=function(){var o=new s;return o.endianness=s.BIG_ENDIAN,this.write(o),o.buffer},v.prototype.initializeSegmentation=function(){var o,c,f,m;for(this.onSegment===null&&e.warn("MP4Box","No segmentation callback set!"),this.isFragmentationInitialized||(this.isFragmentationInitialized=!0,this.nextMoofNumber=0,this.resetTables()),c=[],o=0;o<this.fragmentedTracks.length;o++){var S=new l.moovBox;S.mvhd=this.moov.mvhd,S.boxes.push(S.mvhd),f=this.getTrackById(this.fragmentedTracks[o].id),S.boxes.push(f),S.traks.push(f),m={},m.id=f.tkhd.track_id,m.user=this.fragmentedTracks[o].user,m.buffer=v.writeInitializationSegment(this.ftyp,S,this.moov.mvex&&this.moov.mvex.mehd?this.moov.mvex.mehd.fragment_duration:void 0,this.moov.traks[o].samples.length>0?this.moov.traks[o].samples[0].duration:0),c.push(m)}return c},l.Box.prototype.printHeader=function(o){this.size+=8,this.size>n&&(this.size+=8),this.type==="uuid"&&(this.size+=16),o.log(o.indent+"size:"+this.size),o.log(o.indent+"type:"+this.type)},l.FullBox.prototype.printHeader=function(o){this.size+=4,l.Box.prototype.printHeader.call(this,o),o.log(o.indent+"version:"+this.version),o.log(o.indent+"flags:"+this.flags)},l.Box.prototype.print=function(o){this.printHeader(o)},l.ContainerBox.prototype.print=function(o){this.printHeader(o);for(var c=0;c<this.boxes.length;c++)if(this.boxes[c]){var f=o.indent;o.indent+=" ",this.boxes[c].print(o),o.indent=f}},v.prototype.print=function(o){o.indent="";for(var c=0;c<this.boxes.length;c++)this.boxes[c]&&this.boxes[c].print(o)},l.mvhdBox.prototype.print=function(o){l.FullBox.prototype.printHeader.call(this,o),o.log(o.indent+"creation_time: "+this.creation_time),o.log(o.indent+"modification_time: "+this.modification_time),o.log(o.indent+"timescale: "+this.timescale),o.log(o.indent+"duration: "+this.duration),o.log(o.indent+"rate: "+this.rate),o.log(o.indent+"volume: "+(this.volume>>8)),o.log(o.indent+"matrix: "+this.matrix.join(", ")),o.log(o.indent+"next_track_id: "+this.next_track_id)},l.tkhdBox.prototype.print=function(o){l.FullBox.prototype.printHeader.call(this,o),o.log(o.indent+"creation_time: "+this.creation_time),o.log(o.indent+"modification_time: "+this.modification_time),o.log(o.indent+"track_id: "+this.track_id),o.log(o.indent+"duration: "+this.duration),o.log(o.indent+"volume: "+(this.volume>>8)),o.log(o.indent+"matrix: "+this.matrix.join(", ")),o.log(o.indent+"layer: "+this.layer),o.log(o.indent+"alternate_group: "+this.alternate_group),o.log(o.indent+"width: "+this.width),o.log(o.indent+"height: "+this.height)};var _={};_.createFile=function(o,c){var f=o!==void 0?o:!0,m=new v(c);return m.discardMdatData=!f,m},r.createFile=_.createFile})(or);class Zh{constructor(e,t,s,n=0){this.segment=e,this.sourceFps=t,this.targetFps=s,this.sum=n,this.framesRequested=0}async getNextFrame(){var t;const e=this.sourceFps/this.targetFps;if(this.sum+=e,this.framesRequested+=1,this.sum<1&&this.lastFrame)return this.lastFrame;for(;this.sum>=2;){const s=await this.segment.getNextFrame();if(!s)return;s.close(),this.sum-=1}if(this.sum>=1||!this.lastFrame){this.sum-=1;const s=await this.segment.getNextFrame();return s?((t=this.lastFrame)==null||t.close(),this.lastFrame=s,s):void 0}throw new Error("Unreachable code")}getLastFrame(){return this.lastFrame}getSum(){return this.sum}getSegment(){return this.segment}getTime(e){return(this.framesRequested-e)/this.targetFps}}class Fu{constructor(e,t,s=0){this.file=e,this.setStatus=t,this.offset=s}write(e){const t=new ArrayBuffer(e.byteLength);new Uint8Array(t).set(e),t.fileStart=this.offset,this.offset+=t.byteLength,this.setStatus("fetch",(this.offset/1024**2).toFixed(1)+" MiB"),this.file.appendBuffer(t)}close(){this.setStatus("fetch","Done"),this.file.flush()}}const wS=30;class Jh{constructor(e,t,s,n,a=0){this.done=!1,this.currentFramePastSegmentEndTime=!1,this.abortController=new AbortController,this.responseFinished=!1,this.framesProcessed=0,this.framesDue=0,this.frameBuffer=[],this.encodedChunkQueue=[],this.readMore=async()=>{},this.uri=e,this.file=t,this.file.onSamples=this.onSamples.bind(this),this.edit=s[n],this.startTime=a;const h=Math.floor(this.startTime*this.edit.fps);this.framesProcessed+=h,this.decoder=new VideoDecoder({output:this.onFrame.bind(this),error(l){console.error(l)}})}async start(e){if(this.edit.mediaTime===-1){this.done=!0,this.responseFinished=!0,this.decoder.close();const d=this.edit.segmentDuration/this.file.getInfo().videoTracks[0].movie_timescale,p=Math.ceil(d*this.edit.fps),g=this.file.getInfo().videoTracks[0].track_height,y=this.file.getInfo().videoTracks[0].track_width,x=g*y*4,v=new ArrayBuffer(x),_=new Uint8Array(v);_.fill(0),this.frameBuffer=Array.from({length:p},()=>new VideoFrame(_,{timestamp:0,duration:1/this.edit.fps,codedHeight:g,codedWidth:y,format:"BGRA"}));return}this.decoder.configure(e);const t=this.file.getInfo().videoTracks[0],s=this.file.getTrackById(t.id),n=this.edit.mediaTime,a=this.startTime*t.timescale,l=(n+a)/t.timescale,u=this.file.seekTrack(l,!0,s);this.readMore=await this.startStreamingAtOffset(this.file,this.uri,u.offset)}async startStreamingAtOffset(e,t,s){return fetch(t,{headers:{Range:`bytes=${s}-`},signal:this.abortController.signal}).then(async n=>{if(!n.body)throw new Error("Response body is null");const a=n.body.getReader(),h=new Fu(e,()=>{},s);return async()=>a.read().then(({done:l,value:u})=>{if(l){this.responseFinished=!0,this.abortController.abort(),h.close();return}h.write(u)})})}onSamples(e,t,s){for(const n of s){const a=new EncodedVideoChunk({type:n.is_sync?"key":"delta",timestamp:1e6*n.cts/n.timescale,duration:1e6*n.duration/n.timescale,data:n.data});this.framesDue++,this.encodedChunkQueue.push(a);const h=this.file.getInfo().videoTracks[0],l=this.file.getTrackById(h.id);this.file.releaseSample(l,n.number)}}async decodeChunks(){for(;this.encodedChunkQueue.length>0&&this.decoder.decodeQueueSize<wS;){const e=this.encodedChunkQueue.shift();e&&this.decoder.decode(e)}if(this.done){this.currentFramePastSegmentEndTime=!0;return}if(this.responseFinished&&this.encodedChunkQueue.length===0){await this.flushDecoderWithRetry(),this.currentFramePastSegmentEndTime=!0;return}}async flushDecoderWithRetry(e=3,t=2e3){for(let s=0;s<e;s++){if(this.decoder.decodeQueueSize===0)return;try{await Promise.race([this.decoder.flush(),new Promise((n,a)=>setTimeout(()=>a(new Error("Flush timeout")),t))])}catch(n){if(s===e)throw n}}}async onFrame(e){this.framesDue--;const t=this.edit.mediaTime/this.file.getInfo().videoTracks[0].timescale,s=this.startTime+t,n=e.timestamp/1e6;if(n<s){e.close();return}const a=this.edit.segmentDuration/this.file.getInfo().videoTracks[0].movie_timescale,h=t+a;if(n>h){e.close(),this.done=!0,await this.decoder.flush();return}this.frameBuffer.push(e)}async populateBuffer(){for(;this.frameBuffer.length===0&&!this.currentFramePastSegmentEndTime;)this.responseFinished||await this.readMore(),await this.decodeChunks(),await new Promise(e=>setTimeout(e,0));if(this.frameBuffer.length===0&&this.framesDue>0){let e=200;for(;this.frameBuffer.length===0;)if(await new Promise(t=>setTimeout(t,10)),e--,this.done||e===0)return}}async getNextFrame(){await this.populateBuffer();const e=this.frameBuffer.shift();return e&&this.framesProcessed++,e}async close(){this.abortController.abort(),this.frameBuffer.forEach(e=>e.close());try{this.decoder.state==="configured"&&(await this.decoder.flush(),this.decoder.close())}catch{}}getFramesProcessed(){return this.framesProcessed}getStartTime(){return this.startTime}}function LS(r,e){const t=r.getTrackById(e.id);for(const s of t.mdia.minf.stbl.stsd.entries){const n=s.avcC||s.hvcC||s.vpcC||s.av1C;if(n){const a=new or.DataStream(void 0,0,or.DataStream.BIG_ENDIAN);return n.write(a),new Uint8Array(a.buffer,8)}}throw new Error("avcC, hvcC, vpcC, or av1C box not found")}function RS(r){return{mediaTime:r.media_time,segmentDuration:r.segment_duration,mediaRateInteger:r.media_rate_integer,mediaRateFraction:r.media_rate_fraction}}async function CS(r){return new Promise((e,t)=>{const s=or.createFile();let n=!1;const a=new AbortController;return s.onReady=h=>{var x;n=!0,a.abort();const l=h.videoTracks[0],u={codec:l.codec.startsWith("vp08")?"vp8":l.codec,codedHeight:l.video.height,codedWidth:l.video.width,description:LS(s,l)},d={mediaTime:0,segmentDuration:l.duration,mediaRateInteger:1,mediaRateFraction:0},p=(x=l.edits)==null?void 0:x.map(v=>RS(v)),y=(p!=null&&p.length?p:[d]).map(v=>{const _=l.duration/l.timescale,o=v.segmentDuration/l.movie_timescale,c=l.nb_samples*(o/_),f=v.mediaRateInteger+v.mediaRateFraction/65535,m=c/o*f;return{...v,fps:m}});s.setExtractionOptions(l.id),s.start(),e({file:s,edits:y,config:u})},fetch(r,{signal:a.signal}).then(async h=>{if(!h.body)throw new Error("Response body is null");const l=h.body.getReader(),u=new Fu(s,()=>{});for(;!n;)await l.read().then(({done:d,value:p})=>{if(d){s.flush(),a.abort(),t("Could not find moov");return}u.write(p)})})})}class PS{constructor(e,t,s){this.edits=[],this.nextSegment=0,this.uri=e,this.targetFps=t,this.startTime=s}async start(){const{file:e,edits:t,config:s}=await CS(this.uri);this.file=e,this.edits=t,this.decoderConfig=s}async getNextFrame(){var t;if(!this.sampler){let s=this.startTime;for(;this.nextSegment<this.edits.length;){const a=this.getSecondDurationOfSegment(this.edits[this.nextSegment]);if(s<a)break;s-=a,this.nextSegment++}if(this.nextSegment>=this.edits.length)throw new Error(`Timestamp ${this.startTime} is outside of the video, max timestamp is ${this.getDuration()}`);const n=new Jh(this.uri,this.file,this.edits,this.nextSegment,s);await n.start(this.decoderConfig),this.sampler=new Zh(n,this.edits[this.nextSegment].fps,this.targetFps,0),this.nextSegment++}let e=await this.sampler.getNextFrame();for(;!e&&this.nextSegment<this.edits.length;){this.sampler.getSegment().close(),(t=this.sampler.getLastFrame())==null||t.close();const s=new Jh(this.uri,this.file,this.edits,this.nextSegment,0);await s.start(this.decoderConfig),this.sampler=new Zh(s,this.edits[this.nextSegment].fps,this.targetFps,this.sampler.getSum()),this.nextSegment++,e=await this.sampler.getNextFrame()}if(!e&&(e=this.sampler.getLastFrame(),await this.sampler.getSegment().close(),!e))throw new Error("There are no frames in the video.");return e}getSecondDurationOfSegment(e){const t=e.mediaRateInteger+e.mediaRateFraction/65535;return e.segmentDuration/this.file.getInfo().videoTracks[0].movie_timescale/t}getDuration(){return this.edits.reduce((e,t)=>e+this.getSecondDurationOfSegment(t),0)}getTimeSubtractingFrames(e){const t=this.edits.slice(0,this.nextSegment-1).reduce((a,h)=>a+this.getSecondDurationOfSegment(h),0);if(!this.sampler)throw new Error("No current segment");const s=this.sampler.getSegment().getStartTime(),n=this.sampler.getTime(e);return t+s+n}getTime(){return this.getTimeSubtractingFrames(0)}getLastTime(){return this.getTimeSubtractingFrames(1)}getLastFrame(){var e;return(e=this.sampler)==null?void 0:e.getLastFrame()}close(){var e,t,s;(e=this.sampler)==null||e.getSegment().close(),(s=(t=this.sampler)==null?void 0:t.getLastFrame())==null||s.close(),this.file.flush()}}const ns=new Map;async function DS(r,e){const t=e+"-"+r,s=ns.get(t);s&&(s.close(),ns.delete(t))}async function kS(r,e,t,s){const n=e+"-"+r;let a=ns.get(n);const h=1/s,l=a==null?void 0:a.getDuration();l&&t>l&&(t=l);const u=a&&Math.abs(t-a.getLastTime())<h/2;if(a&&u){const d=a.getLastFrame();if(!d)throw new Error("No last frame");return d}return a&&t+h<a.getTime()&&(a.close(),ns.delete(n),a=void 0),a&&t>a.getTime()+h*1.5&&(a.close(),ns.delete(n),a=void 0),a||(a=new PS(e,s,t),await a.start(),ns.set(n,a)),a.getNextFrame()}var Yi=function(r,e,t,s){var n=arguments.length,a=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,h;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(r,e,t,s);else for(var l=r.length-1;l>=0;l--)(h=r[l])&&(a=(n<3?h(a):n>3?h(e,t,a):h(e,t))||a);return n>3&&a&&Object.defineProperty(e,t,a),a},hi;let vt=hi=class extends qe{constructor(e){super(e),this.detectedFileType="unknown",this.fileTypeWasDetected=!1,this.lastFrame=null}desiredSize(){const e=super.desiredSize();if(e.x===null&&e.y===null){const t=this.video();return{x:t.videoWidth,y:t.videoHeight}}return e}mediaElement(){return this.video()}seekedMedia(){return this.seekedVideo()}fastSeekedMedia(){return this.fastSeekedVideo()}video(){const e=this.src(),t=`${this.key}/${e||"pending"}`;let s=hi.pool[t];if(s){if(e&&e!=="undefined"&&s.src!==e){try{if(new URL(e,window.location.origin).pathname.endsWith(".m3u8")){const l=new Qt;l.loadSource(e),l.attachMedia(s)}else s.src=e}catch{s.src=e}delete hi.pool[t];const a=`${this.key}/${e}`;hi.pool[a]=s}}else{if(s=document.createElement("video"),s.crossOrigin="anonymous",e&&e!=="undefined")try{if(new URL(e,window.location.origin).pathname.endsWith(".m3u8")){const h=new Qt;h.loadSource(e),h.attachMedia(s)}else s.src=e}catch{s.src=e}hi.pool[t]=s}return(!e||e==="undefined")&&ye.collectPromise(new Promise(a=>{const h=()=>{const l=this.src();l&&l!=="undefined"?a():setTimeout(h,10)};h()})),this.waitForCanPlayNecessary(s)&&ye.collectPromise(new Promise(a=>{this.waitForCanPlay(s,a)})),s}seekedVideo(){const e=this.video(),t=this.clampTime(this.time());return e.playbackRate=this.playbackRate(),e.paused||e.pause(),this.lastTime===t||this.setCurrentTime(t),e}fastSeekedVideo(){const e=this.video(),t=this.clampTime(this.time());if(e.playbackRate=this.playbackRate(),this.lastTime===t)return e;const s=this.playing()&&t<e.duration&&e.playbackRate>0;return s?e.paused&&ye.collectPromise(e.play()):e.paused||e.pause(),Math.abs(e.currentTime-t)>1?this.setCurrentTime(t):s||(e.currentTime=t),e}async webcodecSeekedVideo(){const e=this.video(),t=this.clampTime(this.time());if(e.playbackRate=this.playbackRate(),this.lastFrame&&this.lastTime===t)return this.lastFrame;const s=this.view().fps()/this.playbackRate();return kS(this.key,e.src,t,s)}async ffmpegSeekedVideo(){const e=this.video(),t=this.clampTime(this.time()),s=this.getDuration();if(e.playbackRate=this.playbackRate(),this.lastFrame&&this.lastTime===t)return this.lastFrame;const n=this.view().fps()/this.playbackRate();if(!hi.imageCommunication)throw new Error("ServerSeekedVideo can only be used with HMR.");const a=await hi.imageCommunication.getFrame(this.key,e.src,t,s,n);return this.lastFrame=a,this.lastTime=t,a}async seekFunction(){const e=this.view().playbackState();return e===tt.Playing||e===tt.Presenting?this.fastSeekedVideo():e===tt.Paused?this.seekedVideo():this.decoder()==="slow"?this.seekedVideo():this.decoder()==="ffmpeg"?this.ffmpegSeekedVideo():this.decoder()==="web"?this.webcodecSeekedVideo():(this.fileTypeWasDetected||this.detectFileType(),this.detectedFileType==="webm"?this.ffmpegSeekedVideo():this.detectedFileType==="hls"?this.seekedVideo():this.webcodecSeekedVideo())}async draw(e){this.autoPlayBasedOnTwick(),this.drawShape(e);const t=this.alpha();if(t>0){const s=await this.seekFunction(),n=pe.fromSizeCentered(this.computedSize());e.save(),e.clip(this.getPath()),t<1&&(e.globalAlpha*=t),e.imageSmoothingEnabled=this.smoothing(),Zc(e,s,n),e.restore()}this.clip()&&e.clip(this.getPath()),await this.drawChildren(e)}applyFlex(){super.applyFlex();try{const e=this.video();e&&e.videoWidth>0&&e.videoHeight>0&&(this.element.style.aspectRatio=(this.ratio()??e.videoWidth/e.videoHeight).toString())}catch{}}remove(){return super.remove(),DS(this.key,this.src()),this}handleUnknownFileType(e){console.warn(`WARNING: Could not detect file type of video (${e}), will default to using mp4 decoder. If your video file is not an mp4 file, this will lead to an error - to fix this, reencode your video as an mp4 file (better performance) or specify a different decoder: https://docs.re.video/common-issues/slow-rendering#use-mp4-decoder`),this.detectedFileType="unknown",this.fileTypeWasDetected=!0}detectFileType(){return ye.collectPromise((async()=>{var a;const e=this.src(),t=(a=e.split("?")[0].split(".").pop())==null?void 0:a.toLowerCase();if(t==="mp4"||t==="webm"||t==="mov"){this.detectedFileType=t,this.fileTypeWasDetected=!0;return}if(t==="m3u8"){this.detectedFileType="hls",this.fileTypeWasDetected=!0;return}if(!e.startsWith("http://")&&!e.startsWith("https://")){this.handleUnknownFileType(e);return}const n=(await fetch(e,{method:"HEAD"})).headers.get("Content-Type");if(!n){this.handleUnknownFileType(e);return}if(n.includes("video/mp4")){this.detectedFileType="mp4",this.fileTypeWasDetected=!0;return}if(n.includes("video/webm")){this.detectedFileType="webm",this.fileTypeWasDetected=!0;return}if(n.includes("video/quicktime")){this.detectedFileType="mov",this.fileTypeWasDetected=!0;return}if(n.includes("application/vnd.apple.mpegurl")||n.includes("application/x-mpegURL")){this.detectedFileType="hls",this.fileTypeWasDetected=!0;return}this.handleUnknownFileType(e)})())}};vt.pool={};vt.imageCommunication=null;Yi([W(1),N()],vt.prototype,"alpha",void 0);Yi([W(!0),N()],vt.prototype,"smoothing",void 0);Yi([W(null),N()],vt.prototype,"decoder",void 0);Yi([te()],vt.prototype,"video",null);Yi([te()],vt.prototype,"seekedVideo",null);Yi([te()],vt.prototype,"fastSeekedVideo",null);vt=hi=Yi([ut("Video")],vt);class MS extends e0{constructor(e){super(e),this.view=null,this.registeredNodes=new Map,this.nodeCounters=new Map,this.assetHash=Date.now().toString(),this.recreateView()}getView(){return this.view}next(){var e;return(e=this.getView())==null||e.playbackState(this.playback.state).globalTime(this.playback.time),super.next()}async draw(e){e.save(),this.renderLifecycle.dispatch([Mt.BeforeRender,e]),e.save(),this.renderLifecycle.dispatch([Mt.BeginRender,e]),this.getView().playbackState(this.playback.state).globalTime(this.playback.time).fps(this.playback.fps),await this.getView().render(e),this.renderLifecycle.dispatch([Mt.FinishRender,e]),e.restore(),this.renderLifecycle.dispatch([Mt.AfterRender,e]),e.restore()}reset(e){for(const t of this.registeredNodes.keys())try{this.registeredNodes.get(t).dispose()}catch(s){this.logger.error(s)}return this.registeredNodes.clear(),this.registeredNodes=new Map,this.nodeCounters.clear(),this.recreateView(),super.reset(e)}inspectPosition(e,t){const s=this.getNodeByPosition(e,t);return s==null?void 0:s.key}getNodeByPosition(e,t){return this.execute(()=>this.getView().hit(new C(e,t))??null)}validateInspection(e){var t;return((t=this.getNode(e))==null?void 0:t.key)??null}inspectAttributes(e){const t=this.getNode(e);if(!t)return null;const s={stack:t.creationStack,key:t.key};for(const{key:n,meta:a,signal:h}of t)a.inspectable&&(s[n]=h());return s}drawOverlay(e,t,s){const n=this.getNode(e);n&&this.execute(()=>{n.drawOverlay(s,t.multiply(n.localToWorld()))})}transformMousePosition(e,t){return Nt(new C(e,t),this.getView().localToParent().inverse())}registerNode(e,t){var h;const s=((h=e.constructor)==null?void 0:h.name)??"unknown",n=(this.nodeCounters.get(s)??0)+1;this.nodeCounters.set(s,n),t&&this.registeredNodes.has(t)&&(Ue().error({message:`Duplicated node key: "${t}".`,inspect:t,stack:new Error().stack}),t=void 0),t??(t=`${this.name}/${s}[${n}]`),this.registeredNodes.set(t,e);const a=this.registeredNodes;return[t,()=>a.delete(t)]}getNode(e){return typeof e!="string"?null:this.registeredNodes.get(e)??null}*getDetachedNodes(){for(const e of this.registeredNodes.values())!e.parent()&&e!==this.view&&(yield e)}getMediaAssets(){const e=Array.from(this.registeredNodes.values()).filter(n=>n instanceof vt).filter(n=>n.isPlaying()),t=Array.from(this.registeredNodes.values()).filter(n=>n instanceof ti).filter(n=>n.isPlaying()),s=[];return s.push(...e.map(n=>({key:n.key,type:"video",src:n.src(),decoder:n.decoder(),playbackRate:typeof n.playbackRate=="function"?n.playbackRate():n.playbackRate,volume:n.getVolume(),currentTime:n.getCurrentTime(),duration:n.getDuration()}))),s.push(...t.map(n=>({key:n.key,type:"audio",src:n.src(),playbackRate:typeof n.playbackRate=="function"?n.playbackRate():n.playbackRate,volume:n.getVolume(),currentTime:n.getCurrentTime(),duration:n.getDuration()}))),s}stopAllMedia(){const e=Array.from(this.registeredNodes.values()).filter(t=>t instanceof qe).filter(t=>t.isPlaying());for(const t of e)t.dispose()}adjustVolume(e){const t=Array.from(this.registeredNodes.values()).filter(s=>s instanceof qe);for(const s of t)s.setVolume(s.getVolume()*e)}recreateView(){this.execute(()=>{const e=this.getSize();this.view=new ii({position:e.scale(this.resolutionScale/2),scale:this.resolutionScale,assetHash:this.assetHash,size:e})})}}function FS(r,e){return{klass:MS,name:r,config:e,stack:new Error().stack,plugins:["@twick/2d/editor"]}}const Uu="#000000",Ou={x:0,y:0},mi="easeInOut",Ls={VIDEO:"video",AUDIO:"audio",CAPTION:"caption",SCENE:"scene",ELEMENT:"element"},ec={highlight_bg:{rect:{alignItems:"center",gap:2},word:{lineWidth:.35,stroke:"#000000",fontWeight:700,shadowOffset:[-3,3],shadowColor:"#000000",fill:"#ffffff",fontFamily:"Bangers",bgColor:"#444444",bgOffsetWidth:30,bgOffsetHeight:8,fontSize:50}},word_by_word:{rect:{alignItems:"center",justifyContent:"center",gap:8},word:{lineWidth:.35,stroke:"#000000",fontWeight:700,strokeFirst:!0,shadowOffset:[-2,2],shadowColor:"#000000",shadowBlur:5,fontFamily:"Bangers",fill:"#FFFFFF",bgOffsetWidth:20,bgOffsetHeight:10,fontSize:50}},word_by_word_with_bg:{rect:{alignItems:"center",gap:8,padding:[10,20],radius:10},word:{lineWidth:.35,stroke:"#000000",fontWeight:700,strokeFirst:!0,shadowOffset:[-2,2],shadowColor:"#000000",shadowBlur:5,fontFamily:"Bangers",fill:"#FFFFFF",bgOffsetWidth:20,bgOffsetHeight:10,fontSize:50}}},US={text:"#000000",bgColor:"#444444"},OS={family:"Poppins",size:48,weight:400},BS="#FFFFFF00",tc={VIDEO:"video",IMAGE:"image"},Ia={CONTAIN:"contain",COVER:"cover",FILL:"fill"},Xe={SATURATED:"saturated",BRIGHT:"bright",VIBRANT:"vibrant",RETRO:"retro",BLACK_WHITE:"blackWhite",COOL:"cool",WARM:"warm",CINEMATIC:"cinematic",SOFT_GLOW:"softGlow",MOODY:"moody",DREAMY:"dreamy",INVERTED:"inverted",VINTAGE:"vintage",DRAMATIC:"dramatic",FADED:"faded"},ic={PLAYER_UPDATE:"twick:playerUpdate"};function nn(r,e){console.log(`[Visualizer] ${r}`,e||"")}const NS={name:"audio",*create({containerRef:r,element:e,view:t}){const s=Oe();yield*oe(e==null?void 0:e.s),yield r().add(ke(ti,{ref:s,play:!0,...e.props},e.id)),yield*oe(Math.max(0,e.e-e.s)),yield s().play(!1),yield s().remove()}};function $S({t:r,s:e,e:t}){const s=r.split(" "),n=t-e,a=s.join("").length;let h=e;return s.map(l=>{const u=l.length/a*n,d=h,p=d+u;return h=p,{t:l,s:parseFloat(d.toFixed(2)),e:parseFloat(p.toFixed(2))}})}const Bu=r=>{let e=r.replace(/^#/,"");if(e.length===3&&(e=e.split("").map(h=>h+h).join("")),e.length!==6)throw new Error("Invalid hex color");const t=parseInt(e,16),s=t>>16&255,n=t>>8&255,a=t&255;return{r:s,g:n,b:a}},GS={name:"caption",*create({containerRef:r,caption:e}){var a,h,l,u,d,p;const t=$S(e);let s=0;t!=null&&t.length&&(s=t[0].s);let n={refs:[],props:[],idx:0,prevTime:s};for(const g of t){n.props.push(e.props);const y=Oe(),x=e.props;if(r().add(ke($t,{ref:y,...x,text:g.t,opacity:0})),e.capStyle=="highlight_bg"){const v=Oe(),_=Oe(),o=new we({...Bu(x.colors.bgColor),a:(x==null?void 0:x.bgOpacity)??1});r().add(ke(je,{ref:v,fill:o,width:y().width()+(x.bgOffsetWidth??30),height:y().height()+(x.bgOffsetHeight??10),margin:x.bgMargin??[0,-5],radius:x.bgRadius??10,padding:x.bgPadding??[0,15],opacity:0,alignItems:"center",justifyContent:"center",layout:!0,children:ke($t,{ref:_,...x,text:g.t})})),y().remove(),n.refs.push({bgRef:v,textRef:_})}else n.refs.push({textRef:y});n.prevTime=g.e,n.idx=n.idx+1}n.prevTime=s,n.idx=0;for(const g of t)e.capStyle=="highlight_bg"?(yield*(h=(a=n.refs[n.idx])==null?void 0:a.bgRef)==null?void 0:h.call(a).opacity(1,0),yield*oe(Math.max(0,g.e-g.s)),yield*(u=(l=n.refs[n.idx])==null?void 0:l.bgRef)==null?void 0:u.call(l).fill(BS,0)):(yield*(p=(d=n.refs[n.idx])==null?void 0:d.textRef)==null?void 0:p.call(d).opacity(1,0),yield*oe(Math.max(0,g.e-g.s))),n.prevTime=g.e,n.idx=n.idx+1}},zS={name:"elastic",*run({elementRef:r,duration:e,delay:t}){t&&(yield*oe(t)),r().scale(0),yield*r().scale(1,e,dc)}},HS={name:"erase",*run({elementRef:r,duration:e,delay:t,bufferTime:s=.1}){const n=r().text(),a=r().size();r().setText(""),r().size(a),r().textAlign("left"),t&&(yield*oe(t));let h=(e-s)/n.length;yield*oe(h);for(let l=n.length;l>=0;l--)yield*oe(h),r().setText(n.substring(0,l))}},VS={name:"stream-word",*run({elementRef:r,duration:e,delay:t,bufferTime:s=.1}){const n=r().text(),a=r().size(),h=n.split(" ");r().setText(""),r().size(a),t&&(yield*oe(t)),r().textAlign("left");let l=(e-s)/h.length;for(let u=0;u<h.length;u++)yield*oe(l),r().setText(h.slice(0,u+1).join(" "))}},KS={name:"typewriter",*run({elementRef:r,duration:e,delay:t,bufferTime:s=.1}){const n=r().text(),a=r().size();r().setText(""),r().size(a),r().textAlign("left"),t&&(yield*oe(t));let h=(e-s)/n.length;yield*oe(h);for(let l=0;l<n.length;l++)yield*oe(h),r().setText(n.substring(0,l+1))}};class YS{constructor(){this.effects=new Map}register(e){this.effects.set(e.name,e)}get(e){return this.effects.get(e)}list(){return Array.from(this.effects.keys())}}const WS=()=>{Cs.register(KS),Cs.register(VS),Cs.register(HS),Cs.register(zS)},Cs=new YS;WS();const jS={name:"blur",*run({elementRef:r,containerRef:e,interval:t,duration:s,intensity:n=25,animate:a}){const h=e??r;let l=Math.min(t,s);a==="enter"?(h().filters.blur(n),yield*h().filters.blur(0,l)):a==="exit"?(yield*oe(s-l),yield*h().filters.blur(n,l)):a==="both"&&(l=Math.min(t,s/2),h().filters.blur(n),yield*h().filters.blur(0,l),yield*oe(s-l),yield*h().filters.blur(n,l))}};function Ot(r){switch(r){case"easeInSine":return af;case"easeOutSine":return of;case"easeInOutSine":return lf;case"easeInQuad":return hf;case"easeOutQuad":return cf;case"easeInOutQuad":return df;case"easeInCubic":return uf;case"easeOutCubic":return ff;case"easeInOutCubic":return Bs;case"easeInQuart":return pf;case"easeOutQuart":return gf;case"easeInOutQuart":return mf;case"easeInQuint":return yf;case"easeOutQuint":return vf;case"easeInOutQuint":return xf;case"easeInExpo":return Sf;case"easeOutExpo":return hc;case"easeInOutExpo":return _f;case"easeInCirc":return Ef;case"easeOutCirc":return Tf;case"easeInOutCirc":return bf;case"easeInBack":return kf;case"easeOutBack":return Mf;case"easeInOutBack":return Ff;case"easeInElastic":return Nf;case"easeOutElastic":return dc;case"easeInOutElastic":return $f;case"easeInBounce":return Uf;case"easeOutBounce":return Of;case"easeInOutBounce":return Bf;default:return cc}}const qS={name:"breathe",*run({elementRef:r,containerRef:e,mode:t,duration:s,intensity:n=.5}){const a=e??r,h=a().scale();t==="in"&&(yield*a().scale(new C(h.x*n,h.y*n),s,Ot("easeInSine"))),t==="out"&&(a().scale(new C(h.x*n,h.y*n)),yield*a().scale(new C(h.x,h.y),s,Ot("easeOutSine")))}},XS={name:"fade",*run({elementRef:r,containerRef:e,interval:t,duration:s,animate:n}){const a=e??r;let h=Math.min(t,s);n==="enter"?(a().opacity(0),yield*a().opacity(1,h)):n==="exit"?(yield*oe(s-h),yield*a().opacity(0,h)):n==="both"&&(h=Math.min(t,s/2),a().opacity(0),yield*a().opacity(1,h),yield*oe(s-h),yield*a().opacity(0,h))}},QS={name:"photo-rise",*run({elementRef:r,containerRef:e,direction:t,duration:s,intensity:n=200}){if(e){const a=r().position();t==="up"?(r().y(a.y+n),yield*r().y(a.y,s)):t==="down"?(r().y(a.y-n),yield*r().y(a.y,s)):t==="left"?(r().x(a.x+n),yield*r().x(a.x,s)):t==="right"&&(r().x(a.x-n),yield*r().x(a.x,s))}}},ZS={name:"photo-zoom",*run({elementRef:r,containerRef:e,mode:t,duration:s,intensity:n=1.5}){if(e){const a=r().scale();t==="in"&&(yield r().scale(new C(a.x*n,a.y*n)),yield*r().scale(new C(a.x,a.y),s)),t==="out"&&(r().scale(new C(a.x,a.y)),yield*r().scale(new C(a.x*n,a.y*n),s))}}},JS={name:"rise",*run({elementRef:r,containerRef:e,interval:t=.25,duration:s,animate:n,direction:a,intensity:h=200}){const l=e??r,u=l().position();let d=Math.min(t,s);n==="enter"?(l().opacity(0),a==="up"?(l().y(u.y+h),yield*Se(l().opacity(1,d/4),l().y(u.y,d))):a==="down"&&(l().y(u.y-h),yield*Se(l().opacity(1,d/4),l().y(u.y,d)))):n==="exit"?(yield*oe(s-d),a==="up"?yield*Se(Fi(3*d/4,l().opacity(0,d/4)),l().y(u.y-h,d)):a==="down"&&(yield*Se(Fi(3*d/4,l().opacity(0,d/4)),l().y(u.y+h,d)))):n==="both"&&(d=Math.min(t,s/2),l().opacity(0),a==="up"?(l().y(u.y+h),yield*Se(l().opacity(1,d/4),l().y(u.y,d)),yield*oe(s-d),yield*Se(Fi(3*d/4,l().opacity(0,d/4)),l().y(u.y-h,d))):a==="down"&&(l().y(u.y-h),yield*Se(l().opacity(1,d/4),l().y(u.y,d)),yield*oe(s-d),yield*Se(Fi(3*d/4,l().opacity(0,d/4)),l().y(u.y+h,d))))}},e_={name:"succession",*run({elementRef:r,containerRef:e,interval:t,duration:s,animate:n}){const a=e??r,h=a().scale();let l=Math.min(t,s);n==="enter"?(a().opacity(0),a().scale(new C(h.x/2,h.y/2)),yield*Se(a().scale(h,l),a().opacity(1,l/2))):n==="exit"?(yield*oe(s-l),yield*Se(a().scale(new C(h.x/2,h.y/2),l),Fi(l/2,a().opacity(0,l/2)))):n==="both"&&(l=Math.min(t,s/2),a().opacity(0),a().scale(new C(h.x/2,h.y/2)),yield*Se(a().scale(h,l),a().opacity(1,l/2)),yield*oe(s-l),yield*Se(a().scale(new C(h.x/2,h.y/2),l),Fi(l/2,a().opacity(0,l/2))))}};class t_{constructor(){this.animations=new Map}register(e){this.animations.set(e.name,e)}get(e){return this.animations.get(e)}list(){return Array.from(this.animations.keys())}}const i_=()=>{ci.register(XS),ci.register(JS),ci.register(qS),ci.register(e_),ci.register(jS),ci.register(ZS),ci.register(QS)},ci=new t_;i_();const s_={name:"circle",*run({containerRef:r,elementRef:e,initFrameState:t,frameEffect:s}){yield*oe(s.s);const n=s.props,a=[];a.push(r().size({x:n.frameSize[0],y:n.frameSize[1]},n.transitionDuration,Ot(n.transitionEasing??mi))),a.push(r().position(n.framePosition??{x:0,y:0},n.transitionDuration,Ot(n.transitionEasing??mi))),a.push(e().position(n.elementPosition??Ou,n.transitionDuration,Ot(n.transitionEasing??mi))),a.push(r().radius(n.frameSize[0]/2,n.transitionDuration,Ot(n.transitionEasing??mi))),n.objectFit&&a.push(rn({elementRef:e,containerSize:{x:n.frameSize[0],y:n.frameSize[1]},elementSize:t.element.size,objectFit:n.objectFit})),yield*Se(...a)}},n_={name:"rect",*run({containerRef:r,elementRef:e,initFrameState:t,frameEffect:s}){yield*oe(s.s);const n=s.props,a=[];a.push(r().size(n.frameSize,n.transitionDuration,Ot(n.transitionEasing??mi))),a.push(r().position(n.framePosition??{x:0,y:0},n.transitionDuration,Ot(n.transitionEasing??mi))),a.push(e().position(n.elementPosition??Ou,n.transitionDuration,Ot(n.transitionEasing??mi))),a.push(r().radius(n.radius??0,n.transitionDuration,Ot(n.transitionEasing??mi))),n.objectFit&&a.push(rn({elementRef:e,containerSize:{x:n.frameSize[0],y:n.frameSize[1]},elementSize:t.element.size,objectFit:n.objectFit})),yield*Se(...a)}};class r_{constructor(){this.frameEffects=new Map}register(e){this.frameEffects.set(e.name,e)}get(e){return this.frameEffects.get(e)}list(){return Array.from(this.frameEffects.keys())}}const a_=()=>{ao.register(s_),ao.register(n_)},ao=new r_;a_();function*rn({containerSize:r,elementSize:e,elementRef:t,objectFit:s}){const n=r.x/r.y,a=e.x/e.y;switch(s){case Ia.CONTAIN:a>n?(yield t().size({x:r.x,y:r.x/a}),yield t().scale(r.x/e.x,r.x*a/e.y)):(yield t().size({x:r.y*a,y:r.y}),yield t().scale(r.y*a/e.x,r.y/e.y));break;case Ia.COVER:a>n?(yield t().size({x:r.y*a,y:r.y}),yield t().scale(r.y*a/e.x,r.y/e.y)):(yield t().size({x:r.x,y:r.x/a}),yield t().scale(r.x/e.x,r.x*a/e.y));break;case Ia.FILL:yield t().size(r),yield t().scale(r.x/e.x,r.x/e.y);break}}function*o_({elementRef:r,element:e}){if(yield r(),e.textEffect){const t=Cs.get(e.textEffect.name);t&&(yield*t.run({elementRef:r,duration:e.e-e.s,...e.textEffect}))}}function*Ts({elementRef:r,containerRef:e,element:t,view:s}){if(yield r(),t.animation){const n=ci.get(t.animation.name);n&&(yield*n.run({elementRef:r,containerRef:e,view:s,duration:t.e-t.s,...t.animation}))}}function*Nu({containerRef:r,elementRef:e,element:t}){var n;const s=l_({containerRef:r,elementRef:e});for(let a=0;a<((n=t==null?void 0:t.frameEffects)==null?void 0:n.length);a++){const h=t.frameEffects[a],l=a===t.frameEffects.length-1||t.frameEffects[a+1].s!==h.e,u=ao.get(h.name);u&&(yield*u.run({containerRef:r,elementRef:e,initFrameState:s,frameEffect:h}),l&&(yield*h_({containerRef:r,elementRef:e,duration:h.e-h.s,element:t,initProps:s})))}}function l_({containerRef:r,elementRef:e}){return{frame:{size:r().size(),pos:r().position(),radius:r().radius(),scale:r().scale(),rotation:r().rotation()},element:{size:r().size(),pos:e().position(),scale:e().scale()}}}function*h_({containerRef:r,elementRef:e,duration:t,element:s,initProps:n}){yield*oe(t),nn(`restoreFrameState: ${JSON.stringify(n)}`);let a=[];a.push(r().size(n.frame.size)),a.push(r().position(n.frame.pos)),a.push(r().scale(n.frame.scale)),a.push(r().rotation(n.frame.rotation)),a.push(r().radius(n.frame.radius)),a.push(e().size(n.element.size)),a.push(e().position(n.element.pos)),a.push(e().scale(n.element.scale)),a.push(rn({elementRef:e,containerSize:n.frame.size,elementSize:n.element.size,objectFit:s.objectFit??"none"})),yield*Se(...a)}const c_={name:"circle",*create({containerRef:r,element:e,view:t}){const s=Oe();yield*oe(e==null?void 0:e.s),yield r().add(ke(Gi,{ref:s,...e.props},e.id)),yield*Se(Ts({elementRef:s,element:e,view:t}),oe(Math.max(0,e.e-e.s))),yield s().remove()}},d_={name:"icon",*create({containerRef:r,element:e,view:t}){const s=Oe();yield*oe(e==null?void 0:e.s),yield r().add(ke(Ir,{ref:s,...e.props},e.id)),yield*Se(Ts({elementRef:s,element:e,view:t}),oe(Math.max(0,e.e-e.s))),yield s().remove()}},$u=(r,e)=>{switch(e){case Xe.SATURATED:r().filters.saturate(1.4),r().filters.contrast(1.1);break;case Xe.BRIGHT:r().filters.brightness(1.3),r().filters.contrast(1.05);break;case Xe.VIBRANT:r().filters.saturate(1.6),r().filters.brightness(1.15),r().filters.contrast(1.1);break;case Xe.RETRO:r().filters.sepia(.8),r().filters.contrast(1.3),r().filters.brightness(.85),r().filters.saturate(.8);break;case Xe.BLACK_WHITE:r().filters.grayscale(1),r().filters.contrast(1.25),r().filters.brightness(1.05);break;case Xe.COOL:r().filters.hue(15),r().filters.brightness(1.1),r().filters.saturate(1.3),r().filters.contrast(1.05);break;case Xe.WARM:r().filters.hue(-15),r().filters.brightness(1.15),r().filters.saturate(1.3),r().filters.contrast(1.05);break;case Xe.CINEMATIC:r().filters.contrast(1.4),r().filters.brightness(.95),r().filters.saturate(.85),r().filters.sepia(.2);break;case Xe.SOFT_GLOW:r().filters.brightness(1.2),r().filters.contrast(.95),r().filters.blur(1.2),r().filters.saturate(1.1);break;case Xe.MOODY:r().filters.brightness(1.05),r().filters.contrast(1.4),r().filters.saturate(.65),r().filters.sepia(.2);break;case Xe.DREAMY:r().filters.brightness(1.3),r().filters.blur(2),r().filters.saturate(1.4),r().filters.contrast(.95);break;case Xe.INVERTED:r().filters.invert(1),r().filters.hue(180);break;case Xe.VINTAGE:r().filters.sepia(.4),r().filters.saturate(1.4),r().filters.contrast(1.2),r().filters.brightness(1.1);break;case Xe.DRAMATIC:r().filters.contrast(1.5),r().filters.brightness(.9),r().filters.saturate(1.2);break;case Xe.FADED:r().filters.opacity(.9),r().filters.brightness(1.2),r().filters.saturate(.8),r().filters.contrast(.9);break}},Gu={name:"image",*create({containerRef:r,element:e,view:t}){var a;yield*oe(e==null?void 0:e.s);const s=Oe(),n=Oe();yield r().add(ke(je,{ref:s,...e.frame,children:ke(mt,{ref:n,...e.props},`child-${e.id}`)},e.id)),s()&&(yield rn({elementRef:n,containerSize:s().size(),elementSize:n().size(),objectFit:e.objectFit}),(a=e==null?void 0:e.props)!=null&&a.mediaFilter&&$u(n,e.props.mediaFilter),yield*Se(Ts({elementRef:n,containerRef:s,element:e,view:t}),Nu({containerRef:s,elementRef:n,element:e}),oe(Math.max(0,e.e-e.s))),yield n().remove(),yield s().remove())}},u_={name:"rect",*create({containerRef:r,element:e,view:t}){const s=Oe();yield*oe(e==null?void 0:e.s),nn(`RectElement: ${JSON.stringify(e)}`),yield r().add(ke(je,{ref:s,...e.props},e.id)),yield*Se(Ts({elementRef:s,element:e,view:t}),oe(Math.max(0,e.e-e.s))),yield s().remove()}},zu={name:"video",*create({containerRef:r,element:e,view:t}){var a;yield*oe(e==null?void 0:e.s);const s=Oe(),n=Oe();yield r().add(ke(je,{ref:s,...e.frame,children:ke(vt,{ref:n,play:!0,...e.props},`child-${e.id}`)},e.id)),s()&&(yield rn({elementRef:n,containerSize:s().size(),elementSize:n().size(),objectFit:e.objectFit}),(a=e==null?void 0:e.props)!=null&&a.mediaFilter&&$u(n,e.props.mediaFilter),yield*Se(Ts({elementRef:n,containerRef:s,element:e,view:t}),Nu({containerRef:s,elementRef:n,element:e}),oe(Math.max(0,e.e-e.s))),yield n().play(!1),yield n().remove(),yield s().remove())}},f_={name:"scene",*create({containerRef:r,element:e,view:t}){yield*oe(e==null?void 0:e.s);const s=Oe();nn(`SceneElement: ${JSON.stringify(e)}`),yield r().add(ke(je,{ref:s,fill:e.backgroundColor??Uu,size:"100%"})),e.type===tc.IMAGE?yield*Gu.create({containerRef:r,element:e,view:t}):e.type===tc.VIDEO&&(yield*zu.create({containerRef:r,element:e,view:t})),yield s().remove()}},p_={name:"text",*create({containerRef:r,element:e,view:t}){const s=Oe();yield*oe(e==null?void 0:e.s),yield r().add(ke($t,{ref:s,text:e.t,...e.props},e.id)),yield*Se(Ts({elementRef:s,element:e,view:t}),o_({elementRef:s,element:e}),oe(Math.max(0,e.e-e.s))),yield s().remove()}};class g_{constructor(){this.elements=new Map}register(e){this.elements.set(e.name,e)}get(e){return this.elements.get(e)}list(){return Array.from(this.elements.keys())}}const m_=()=>{ht.register(zu),ht.register(GS),ht.register(f_),ht.register(Gu),ht.register(p_),ht.register(NS),ht.register(c_),ht.register(d_),ht.register(u_)},ht=new g_;m_();function*y_({view:r,track:e}){var n;const t=Oe();let s=0;r.add(ke(Q,{size:"100%",ref:t,layout:!0}));for(const a of e.elements||[])yield*oe((a==null?void 0:a.s)-s),yield*(n=ht.get("video"))==null?void 0:n.create({containerRef:t,element:a,view:r}),s=a.e;yield t().remove()}function*v_({view:r,track:e}){let t=0;for(const s of e.elements){const n=Oe();yield*oe((s==null?void 0:s.s)-t),t=s==null?void 0:s.e,nn(`Adding audio element ${s.id}`),r.add(ke(ti,{ref:n,...s.props},s.id)),yield*oe(Math.max(0,s.e-s.s)),yield n().playing(!1),yield n().remove()}}function*x_({view:r,track:e}){var l;let t=0;const s=Oe();r.add(ke(Q,{size:"100%",ref:s}));const n=e==null?void 0:e.props,a=(n==null?void 0:n.applyToAll)??!1,h=(ec[(n==null?void 0:n.capStyle)??""]||{}).word||{};for(const u of e.elements){const d=u.props,p=(ec[(d==null?void 0:d.capStyle)??(n==null?void 0:n.capStyle)??""]||{}).rect||{},g={...p,justifyContent:p.justifyContent,alignItems:p.alignItems},y=a?n==null?void 0:n.colors:(d==null?void 0:d.colors)??(n==null?void 0:n.colors)??US,x={...h,...(n==null?void 0:n.captionProps)||{},colors:y,font:a?n==null?void 0:n.font:(d==null?void 0:d.font)??(n==null?void 0:n.font)??OS,fill:y.text,bgColor:y.bgColor,bgOpacity:(n==null?void 0:n.bgOpacity)??1};yield*oe((u==null?void 0:u.s)-t);const v=Oe();if(s().add(ke(je,{ref:v,...g,x:a?n==null?void 0:n.x:(d==null?void 0:d.x)??(n==null?void 0:n.x),y:a?n==null?void 0:n.y:(d==null?void 0:d.y)??(n==null?void 0:n.y),layout:!0},u.id)),(n==null?void 0:n.capStyle)==="word_by_word_with_bg"){const _=new we({...Bu(x.bgColor),a:(x==null?void 0:x.bgOpacity)??1});v().fill(_)}yield*(l=ht.get("caption"))==null?void 0:l.create({containerRef:v,caption:{...u,t:u.t??"",capStyle:(d==null?void 0:d.capStyle)??(n==null?void 0:n.capStyle),props:x},view:r}),t=u.e,yield v().remove()}}function*S_({view:r,track:e}){var s;const t=Oe();r.add(ke(Q,{size:"100%",ref:t,layout:!0}));for(const n of e.elements||[])yield*(s=ht.get("scene"))==null?void 0:s.create({containerRef:t,element:n,view:r});yield t().remove()}function*__({view:r,track:e}){var n;const t=Oe();r.add(ke(Q,{size:"100%",ref:t}));const s=[];try{for(const a of e.elements)s.push((n=ht.get(a.type))==null?void 0:n.create({containerRef:t,element:a,view:r}))}catch(a){nn("Error creating element track",a)}yield*Se(...s),yield t().remove()}const sc=(r,e)=>{if(typeof window<"u"){const t=new CustomEvent(r,e);return window.dispatchEvent(t)}},E_=FS("scene",function*(r){const e=zn().variables.get("input",null)(),t=zn().variables.get("playerId",null)();if(e)if(console.log("Scene updated",{playerId:t,input:e}),yield r.add(ke(je,{fill:e.backgroundColor??Uu,size:"100%"})),e.tracks){const s=[];for(const n of e.tracks)switch(n.type){case Ls.VIDEO:s.push(y_({view:r,track:n}));break;case Ls.AUDIO:s.push(v_({view:r,track:n}));break;case Ls.CAPTION:s.push(x_({view:r,track:n}));break;case Ls.SCENE:s.push(S_({view:r,track:n}));break;case Ls.ELEMENT:s.push(__({view:r,track:n}));break}yield*Se(...s),sc(ic.PLAYER_UPDATE,{detail:{status:"ready",playerId:t,message:"All elements created"}})}else sc(ic.PLAYER_UPDATE,{detail:{status:"ready",playerId:t,message:"No elements to create"}})}),G_=Bg({scenes:[E_]});export{G_ as default};
145
+ `,b+=I.payl.text}return b};var y=function(){};y.prototype.parseSample=function(o){var c={},f;c.resources=[];var m=new t(o.data.buffer);if(!o.subsamples||o.subsamples.length===0)c.documentString=m.readString(o.data.length);else if(c.documentString=m.readString(o.subsamples[0].size),o.subsamples.length>1)for(f=1;f<o.subsamples.length;f++)c.resources[f]=m.readUint8Array(o.subsamples[f].size);return typeof DOMParser<"u"&&(c.document=new DOMParser().parseFromString(c.documentString,"application/xml")),c};var x=function(){};x.prototype.parseSample=function(o){var c,f=new t(o.data.buffer);return c=f.readString(o.data.length),c},x.prototype.parseConfig=function(o){var c,f=new t(o.buffer);return f.readUint32(),c=f.readCString(),c},r.VTTin4Parser=g,r.XMLSubtitlein4Parser=y,r.Textin4Parser=x;var v=function(o){this.stream=o||new a,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.items=[],this.entity_groups=[],this.onSidx=null,this.sidxSent=!1};v.prototype.setSegmentOptions=function(o,c,f){var m=this.getTrackById(o);if(m){var S={};this.fragmentedTracks.push(S),S.id=o,S.user=c,S.trak=m,m.nextSample=0,S.segmentStream=null,S.nb_samples=1e3,S.rapAlignement=!0,f&&(f.nbSamples&&(S.nb_samples=f.nbSamples),f.rapAlignement&&(S.rapAlignement=f.rapAlignement))}},v.prototype.unsetSegmentOptions=function(o){for(var c=-1,f=0;f<this.fragmentedTracks.length;f++){var m=this.fragmentedTracks[f];m.id==o&&(c=f)}c>-1&&this.fragmentedTracks.splice(c,1)},v.prototype.setExtractionOptions=function(o,c,f){var m=this.getTrackById(o);if(m){var S={};this.extractedTracks.push(S),S.id=o,S.user=c,S.trak=m,m.nextSample=0,S.nb_samples=1e3,S.samples=[],f&&f.nbSamples&&(S.nb_samples=f.nbSamples)}},v.prototype.unsetExtractionOptions=function(o){for(var c=-1,f=0;f<this.extractedTracks.length;f++){var m=this.extractedTracks[f];m.id==o&&(c=f)}c>-1&&this.extractedTracks.splice(c,1)},v.prototype.parse=function(){var o,c,f=!1;if(!(this.restoreParsePosition&&!this.restoreParsePosition()))for(;;)if(this.hasIncompleteMdat&&this.hasIncompleteMdat()){if(this.processIncompleteMdat())continue;return}else if(this.saveParsePosition&&this.saveParsePosition(),o=l.parseOneBox(this.stream,f),o.code===l.ERR_NOT_ENOUGH_DATA)if(this.processIncompleteBox){if(this.processIncompleteBox(o))continue;return}else return;else{var m;switch(c=o.box,m=c.type!=="uuid"?c.type:c.uuid,this.boxes.push(c),m){case"mdat":this.mdats.push(c);break;case"moof":this.moofs.push(c);break;case"moov":this.moovStartFound=!0,this.mdats.length===0&&(this.isProgressive=!0);default:this[m]!==void 0&&e.warn("ISOFile","Duplicate Box of type: "+m+", overriding previous occurrence"),this[m]=c;break}this.updateUsedBytes&&this.updateUsedBytes(c,o)}},v.prototype.checkBuffer=function(o){if(o==null)throw"Buffer must be defined and non empty";if(o.fileStart===void 0)throw"Buffer must have a fileStart property";return o.byteLength===0?(e.warn("ISOFile","Ignoring empty buffer (fileStart: "+o.fileStart+")"),this.stream.logBufferLevel(),!1):(e.info("ISOFile","Processing buffer (fileStart: "+o.fileStart+")"),o.usedBytes=0,this.stream.insertBuffer(o),this.stream.logBufferLevel(),this.stream.initialized()?!0:(e.warn("ISOFile","Not ready to start parsing"),!1))},v.prototype.appendBuffer=function(o,c){var f;if(this.checkBuffer(o))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(c),this.nextSeekPosition?(f=this.nextSeekPosition,this.nextSeekPosition=void 0):f=this.nextParsePosition,this.stream.getEndFilePositionAfter&&(f=this.stream.getEndFilePositionAfter(f))):this.nextParsePosition?f=this.nextParsePosition:f=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&&(e.info("ISOFile","Done processing buffer (fileStart: "+o.fileStart+") - next buffer to fetch should have a fileStart position of "+f),this.stream.logBufferLevel(),this.stream.cleanBuffers(),this.stream.logBufferLevel(!0),e.info("ISOFile","Sample data size in memory: "+this.getAllocatedSampleDataSize())),f},v.prototype.getInfo=function(){var o,c,f={},m,S,T,b,A=new Date("1904-01-01T00:00:00Z").getTime();if(this.moov)for(f.hasMoov=!0,f.duration=this.moov.mvhd.duration,f.timescale=this.moov.mvhd.timescale,f.isFragmented=this.moov.mvex!=null,f.isFragmented&&this.moov.mvex.mehd&&(f.fragment_duration=this.moov.mvex.mehd.fragment_duration),f.isProgressive=this.isProgressive,f.hasIOD=this.moov.iods!=null,f.brands=[],f.brands.push(this.ftyp.major_brand),f.brands=f.brands.concat(this.ftyp.compatible_brands),f.created=new Date(A+this.moov.mvhd.creation_time*1e3),f.modified=new Date(A+this.moov.mvhd.modification_time*1e3),f.tracks=[],f.audioTracks=[],f.videoTracks=[],f.subtitleTracks=[],f.metadataTracks=[],f.hintTracks=[],f.otherTracks=[],o=0;o<this.moov.traks.length;o++){if(m=this.moov.traks[o],b=m.mdia.minf.stbl.stsd.entries[0],S={},f.tracks.push(S),S.id=m.tkhd.track_id,S.name=m.mdia.hdlr.name,S.references=[],m.tref)for(c=0;c<m.tref.boxes.length;c++)T={},S.references.push(T),T.type=m.tref.boxes[c].type,T.track_ids=m.tref.boxes[c].track_ids;m.edts&&(S.edits=m.edts.elst.entries),S.created=new Date(A+m.tkhd.creation_time*1e3),S.modified=new Date(A+m.tkhd.modification_time*1e3),S.movie_duration=m.tkhd.duration,S.movie_timescale=f.timescale,S.layer=m.tkhd.layer,S.alternate_group=m.tkhd.alternate_group,S.volume=m.tkhd.volume,S.matrix=m.tkhd.matrix,S.track_width=m.tkhd.width/65536,S.track_height=m.tkhd.height/65536,S.timescale=m.mdia.mdhd.timescale,S.cts_shift=m.mdia.minf.stbl.cslg,S.duration=m.mdia.mdhd.duration,S.samples_duration=m.samples_duration,S.codec=b.getCodec(),S.kind=m.udta&&m.udta.kinds.length?m.udta.kinds[0]:{schemeURI:"",value:""},S.language=m.mdia.elng?m.mdia.elng.extended_language:m.mdia.mdhd.languageString,S.nb_samples=m.samples.length,S.size=m.samples_size,S.bitrate=S.size*8*S.timescale/S.samples_duration,b.isAudio()?(S.type="audio",f.audioTracks.push(S),S.audio={},S.audio.sample_rate=b.getSampleRate(),S.audio.channel_count=b.getChannelCount(),S.audio.sample_size=b.getSampleSize()):b.isVideo()?(S.type="video",f.videoTracks.push(S),S.video={},S.video.width=b.getWidth(),S.video.height=b.getHeight()):b.isSubtitle()?(S.type="subtitles",f.subtitleTracks.push(S)):b.isHint()?(S.type="metadata",f.hintTracks.push(S)):b.isMetadata()?(S.type="metadata",f.metadataTracks.push(S)):(S.type="metadata",f.otherTracks.push(S))}else f.hasMoov=!1;if(f.mime="",f.hasMoov&&f.tracks){for(f.videoTracks&&f.videoTracks.length>0?f.mime+='video/mp4; codecs="':f.audioTracks&&f.audioTracks.length>0?f.mime+='audio/mp4; codecs="':f.mime+='application/mp4; codecs="',o=0;o<f.tracks.length;o++)o!==0&&(f.mime+=","),f.mime+=f.tracks[o].codec;f.mime+='"; profiles="',f.mime+=this.ftyp.compatible_brands.join(),f.mime+='"'}return f},v.prototype.setNextSeekPositionFromSample=function(o){o&&(this.nextSeekPosition?this.nextSeekPosition=Math.min(o.offset+o.alreadyRead,this.nextSeekPosition):this.nextSeekPosition=o.offset+o.alreadyRead)},v.prototype.processSamples=function(o){var c,f;if(this.sampleProcessingStarted){if(this.isFragmentationInitialized&&this.onSegment!==null)for(c=0;c<this.fragmentedTracks.length;c++){var m=this.fragmentedTracks[c];for(f=m.trak;f.nextSample<f.samples.length&&this.sampleProcessingStarted;){e.debug("ISOFile","Creating media fragment on track #"+m.id+" for sample "+f.nextSample);var S=this.createFragment(m.id,f.nextSample,m.segmentStream);if(S)m.segmentStream=S,f.nextSample++;else break;if((f.nextSample%m.nb_samples===0||o||f.nextSample>=f.samples.length)&&(e.info("ISOFile","Sending fragmented data on track #"+m.id+" for samples ["+Math.max(0,f.nextSample-m.nb_samples)+","+(f.nextSample-1)+"]"),e.info("ISOFile","Sample data size in memory: "+this.getAllocatedSampleDataSize()),this.onSegment&&this.onSegment(m.id,m.user,m.segmentStream.buffer,f.nextSample,o||f.nextSample>=f.samples.length),m.segmentStream=null,m!==this.fragmentedTracks[c]))break}}if(this.onSamples!==null)for(c=0;c<this.extractedTracks.length;c++){var T=this.extractedTracks[c];for(f=T.trak;f.nextSample<f.samples.length&&this.sampleProcessingStarted;){e.debug("ISOFile","Exporting on track #"+T.id+" sample #"+f.nextSample);var b=this.getSample(f,f.nextSample);if(b)f.nextSample++,T.samples.push(b);else{this.setNextSeekPositionFromSample(f.samples[f.nextSample]);break}if((f.nextSample%T.nb_samples===0||f.nextSample>=f.samples.length)&&(e.debug("ISOFile","Sending samples on track #"+T.id+" for sample "+f.nextSample),this.onSamples&&this.onSamples(T.id,T.user,T.samples),T.samples=[],T!==this.extractedTracks[c]))break}}}},v.prototype.getBox=function(o){var c=this.getBoxes(o,!0);return c.length?c[0]:null},v.prototype.getBoxes=function(o,c){var f=[];return v._sweep.call(this,o,f,c),f},v._sweep=function(o,c,f){this.type&&this.type==o&&c.push(this);for(var m in this.boxes){if(c.length&&f)return;v._sweep.call(this.boxes[m],o,c,f)}},v.prototype.getTrackSamplesInfo=function(o){var c=this.getTrackById(o);if(c)return c.samples},v.prototype.getTrackSample=function(o,c){var f=this.getTrackById(o),m=this.getSample(f,c);return m},v.prototype.releaseUsedSamples=function(o,c){var f=0,m=this.getTrackById(o);m.lastValidSample||(m.lastValidSample=0);for(var S=m.lastValidSample;S<c;S++)f+=this.releaseSample(m,S);e.info("ISOFile","Track #"+o+" released samples up to "+c+" (released size: "+f+", remaining: "+this.samplesDataSize+")"),m.lastValidSample=c},v.prototype.start=function(){this.sampleProcessingStarted=!0,this.processSamples(!1)},v.prototype.stop=function(){this.sampleProcessingStarted=!1},v.prototype.flush=function(){e.info("ISOFile","Flushing remaining samples"),this.updateSampleLists(),this.processSamples(!0),this.stream.cleanBuffers(),this.stream.logBufferLevel(!0)},v.prototype.seekTrack=function(o,c,f){var m,S,T=1/0,b=0,A=0,I;if(f.samples.length===0)return e.info("ISOFile","No sample in track, cannot seek! Using time "+e.getDurationString(0,1)+" and offset: 0"),{offset:0,time:0};for(m=0;m<f.samples.length;m++){if(S=f.samples[m],m===0)A=0,I=S.timescale;else if(S.cts>o*S.timescale){A=m-1;break}c&&S.is_sync&&(b=m)}for(c&&(A=b),o=f.samples[A].cts,f.nextSample=A;f.samples[A].alreadyRead===f.samples[A].size&&f.samples[A+1];)A++;return T=f.samples[A].offset+f.samples[A].alreadyRead,e.info("ISOFile","Seeking to "+(c?"RAP":"")+" sample #"+f.nextSample+" on track "+f.tkhd.track_id+", time "+e.getDurationString(o,I)+" and offset: "+T),{offset:T,time:o/I}},v.prototype.getTrackDuration=function(o){var c;return o.samples?(c=o.samples[o.samples.length-1],(c.cts+c.duration)/c.timescale):1/0},v.prototype.seek=function(o,c){var f=this.moov,m,S,T,b={offset:1/0,time:1/0};if(this.moov){for(T=0;T<f.traks.length;T++)m=f.traks[T],!(o>this.getTrackDuration(m))&&(S=this.seekTrack(o,c,m),S.offset<b.offset&&(b.offset=S.offset),S.time<b.time&&(b.time=S.time));return e.info("ISOFile","Seeking at time "+e.getDurationString(b.time,1)+" needs a buffer with a fileStart position of "+b.offset),b.offset===1/0?b={offset:this.nextParsePosition,time:0}:b.offset=this.stream.getEndFilePositionAfter(b.offset),e.info("ISOFile","Adjusted seek position (after checking data already in buffer): "+b.offset),b}else throw"Cannot seek: moov not received!"},v.prototype.equal=function(o){for(var c=0;c<this.boxes.length&&c<o.boxes.length;){var f=this.boxes[c],m=o.boxes[c];if(!l.boxEqual(f,m))return!1;c++}return!0},r.ISOFile=v,v.prototype.lastBoxStartPosition=0,v.prototype.parsingMdat=null,v.prototype.nextParsePosition=0,v.prototype.discardMdatData=!1,v.prototype.processIncompleteBox=function(o){var c,f,m;return o.type==="mdat"?(c=new l[o.type+"Box"](o.size),this.parsingMdat=c,this.boxes.push(c),this.mdats.push(c),c.start=o.start,c.hdr_size=o.hdr_size,this.stream.addUsedBytes(c.hdr_size),this.lastBoxStartPosition=c.start+c.size,m=this.stream.seek(c.start+c.size,!1,this.discardMdatData),m?(this.parsingMdat=null,!0):(this.moovStartFound?this.nextParsePosition=this.stream.findEndContiguousBuf():this.nextParsePosition=c.start+c.size,!1)):(o.type==="moov"&&(this.moovStartFound=!0,this.mdats.length===0&&(this.isProgressive=!0)),f=this.stream.mergeNextBuffer?this.stream.mergeNextBuffer():!1,f?(this.nextParsePosition=this.stream.getEndPosition(),!0):(o.type?this.moovStartFound?this.nextParsePosition=this.stream.getEndPosition():this.nextParsePosition=this.stream.getPosition()+o.size:this.nextParsePosition=this.stream.getEndPosition(),!1))},v.prototype.hasIncompleteMdat=function(){return this.parsingMdat!==null},v.prototype.processIncompleteMdat=function(){var o,c;return o=this.parsingMdat,c=this.stream.seek(o.start+o.size,!1,this.discardMdatData),c?(e.debug("ISOFile","Found 'mdat' end in buffered data"),this.parsingMdat=null,!0):(this.nextParsePosition=this.stream.findEndContiguousBuf(),!1)},v.prototype.restoreParsePosition=function(){return this.stream.seek(this.lastBoxStartPosition,!0,this.discardMdatData)},v.prototype.saveParsePosition=function(){this.lastBoxStartPosition=this.stream.getPosition()},v.prototype.updateUsedBytes=function(o,c){this.stream.addUsedBytes&&(o.type==="mdat"?(this.stream.addUsedBytes(o.hdr_size),this.discardMdatData&&this.stream.addUsedBytes(o.size-o.hdr_size)):this.stream.addUsedBytes(o.size))},v.prototype.add=l.Box.prototype.add,v.prototype.addBox=l.Box.prototype.addBox,v.prototype.init=function(o){var c=o||{};this.add("ftyp").set("major_brand",c.brands&&c.brands[0]||"iso4").set("minor_version",0).set("compatible_brands",c.brands||["iso4"]);var f=this.add("moov");return f.add("mvhd").set("timescale",c.timescale||600).set("rate",c.rate||65536).set("creation_time",0).set("modification_time",0).set("duration",c.duration||0).set("volume",c.width?0:256).set("matrix",[65536,0,0,0,65536,0,0,0,1073741824]).set("next_track_id",1),f.add("mvex"),this},v.prototype.addTrack=function(o){this.moov||this.init(o);var c=o||{};c.width=c.width||320,c.height=c.height||320,c.id=c.id||this.moov.mvhd.next_track_id,c.type=c.type||"avc1";var f=this.moov.add("trak");this.moov.mvhd.next_track_id=c.id+1,f.add("tkhd").set("flags",l.TKHD_FLAG_ENABLED|l.TKHD_FLAG_IN_MOVIE|l.TKHD_FLAG_IN_PREVIEW).set("creation_time",0).set("modification_time",0).set("track_id",c.id).set("duration",c.duration||0).set("layer",c.layer||0).set("alternate_group",0).set("volume",1).set("matrix",[65536,0,0,0,65536,0,0,0,1073741824]).set("width",c.width<<16).set("height",c.height<<16);var m=f.add("mdia");m.add("mdhd").set("creation_time",0).set("modification_time",0).set("timescale",c.timescale||1).set("duration",c.media_duration||0).set("language",c.language||"und"),m.add("hdlr").set("handler",c.hdlr||"vide").set("name",c.name||"Track created with MP4Box.js"),m.add("elng").set("extended_language",c.language||"fr-FR");var S=m.add("minf");if(l[c.type+"SampleEntry"]!==void 0){var T=new l[c.type+"SampleEntry"];T.data_reference_index=1;var b="";for(var A in l.sampleEntryCodes)for(var I=l.sampleEntryCodes[A],L=0;L<I.length;L++)if(I.indexOf(c.type)>-1){b=A;break}switch(b){case"Visual":if(S.add("vmhd").set("graphicsmode",0).set("opcolor",[0,0,0]),T.set("width",c.width).set("height",c.height).set("horizresolution",72<<16).set("vertresolution",72<<16).set("frame_count",1).set("compressorname",c.type+" Compressor").set("depth",24),c.avcDecoderConfigRecord){var w=new l.avcCBox;w.parse(new t(c.avcDecoderConfigRecord)),T.addBox(w)}else if(c.hevcDecoderConfigRecord){var R=new l.hvcCBox;R.parse(new t(c.hevcDecoderConfigRecord)),T.addBox(R)}break;case"Audio":S.add("smhd").set("balance",c.balance||0),T.set("channel_count",c.channel_count||2).set("samplesize",c.samplesize||16).set("samplerate",c.samplerate||65536);break;case"Hint":S.add("hmhd");break;case"Subtitle":switch(S.add("sthd"),c.type){case"stpp":T.set("namespace",c.namespace||"nonamespace").set("schema_location",c.schema_location||"").set("auxiliary_mime_types",c.auxiliary_mime_types||"");break}break;case"Metadata":S.add("nmhd");break;case"System":S.add("nmhd");break;default:S.add("nmhd");break}c.description&&T.addBox(c.description),c.description_boxes&&c.description_boxes.forEach(function(k){T.addBox(k)}),S.add("dinf").add("dref").addEntry(new l["url Box"]().set("flags",1));var M=S.add("stbl");return M.add("stsd").addEntry(T),M.add("stts").set("sample_counts",[]).set("sample_deltas",[]),M.add("stsc").set("first_chunk",[]).set("samples_per_chunk",[]).set("sample_description_index",[]),M.add("stco").set("chunk_offsets",[]),M.add("stsz").set("sample_sizes",[]),this.moov.mvex.add("trex").set("track_id",c.id).set("default_sample_description_index",c.default_sample_description_index||1).set("default_sample_duration",c.default_sample_duration||0).set("default_sample_size",c.default_sample_size||0).set("default_sample_flags",c.default_sample_flags||0),this.buildTrakSampleLists(f),c.id}},l.Box.prototype.computeSize=function(o){var c=o||new s;c.endianness=s.BIG_ENDIAN,this.write(c)},v.prototype.addSample=function(o,c,f){var m=f||{},S={},T=this.getTrackById(o);if(T!==null){S.number=T.samples.length,S.track_id=T.tkhd.track_id,S.timescale=T.mdia.mdhd.timescale,S.description_index=m.sample_description_index?m.sample_description_index-1:0,S.description=T.mdia.minf.stbl.stsd.entries[S.description_index],S.data=c,S.size=c.byteLength,S.alreadyRead=S.size,S.duration=m.duration||1,S.cts=m.cts||0,S.dts=m.dts||0,S.is_sync=m.is_sync||!1,S.is_leading=m.is_leading||0,S.depends_on=m.depends_on||0,S.is_depended_on=m.is_depended_on||0,S.has_redundancy=m.has_redundancy||0,S.degradation_priority=m.degradation_priority||0,S.offset=0,S.subsamples=m.subsamples,T.samples.push(S),T.samples_size+=S.size,T.samples_duration+=S.duration,T.first_dts===void 0&&(T.first_dts=m.dts),this.processSamples();var b=this.createSingleSampleMoof(S);return this.addBox(b),b.computeSize(),b.trafs[0].truns[0].data_offset=b.size+8,this.add("mdat").data=new Uint8Array(c),S}},v.prototype.createSingleSampleMoof=function(o){var c=0;o.is_sync?c=1<<25:c=65536;var f=new l.moofBox;f.add("mfhd").set("sequence_number",this.nextMoofNumber),this.nextMoofNumber++;var m=f.add("traf"),S=this.getTrackById(o.track_id);return m.add("tfhd").set("track_id",o.track_id).set("flags",l.TFHD_FLAG_DEFAULT_BASE_IS_MOOF),m.add("tfdt").set("baseMediaDecodeTime",o.dts-(S.first_dts||0)),m.add("trun").set("flags",l.TRUN_FLAGS_DATA_OFFSET|l.TRUN_FLAGS_DURATION|l.TRUN_FLAGS_SIZE|l.TRUN_FLAGS_FLAGS|l.TRUN_FLAGS_CTS_OFFSET).set("data_offset",0).set("first_sample_flags",0).set("sample_count",1).set("sample_duration",[o.duration]).set("sample_size",[o.size]).set("sample_flags",[c]).set("sample_composition_time_offset",[o.cts-o.dts]),f},v.prototype.lastMoofIndex=0,v.prototype.samplesDataSize=0,v.prototype.resetTables=function(){var o,c,f,m,S,T,b,A;for(this.initial_duration=this.moov.mvhd.duration,this.moov.mvhd.duration=0,o=0;o<this.moov.traks.length;o++){c=this.moov.traks[o],c.tkhd.duration=0,c.mdia.mdhd.duration=0,f=c.mdia.minf.stbl.stco||c.mdia.minf.stbl.co64,f.chunk_offsets=[],m=c.mdia.minf.stbl.stsc,m.first_chunk=[],m.samples_per_chunk=[],m.sample_description_index=[],S=c.mdia.minf.stbl.stsz||c.mdia.minf.stbl.stz2,S.sample_sizes=[],T=c.mdia.minf.stbl.stts,T.sample_counts=[],T.sample_deltas=[],b=c.mdia.minf.stbl.ctts,b&&(b.sample_counts=[],b.sample_offsets=[]),A=c.mdia.minf.stbl.stss;var I=c.mdia.minf.stbl.boxes.indexOf(A);I!=-1&&(c.mdia.minf.stbl.boxes[I]=null)}},v.initSampleGroups=function(o,c,f,m,S){var T,b,A,I;function L(w,R,M){this.grouping_type=w,this.grouping_type_parameter=R,this.sbgp=M,this.last_sample_in_run=-1,this.entry_index=-1}for(c&&(c.sample_groups_info=[]),o.sample_groups_info||(o.sample_groups_info=[]),b=0;b<f.length;b++){for(I=f[b].grouping_type+"/"+f[b].grouping_type_parameter,A=new L(f[b].grouping_type,f[b].grouping_type_parameter,f[b]),c&&(c.sample_groups_info[I]=A),o.sample_groups_info[I]||(o.sample_groups_info[I]=A),T=0;T<m.length;T++)m[T].grouping_type===f[b].grouping_type&&(A.description=m[T],A.description.used=!0);if(S)for(T=0;T<S.length;T++)S[T].grouping_type===f[b].grouping_type&&(A.fragment_description=S[T],A.fragment_description.used=!0,A.is_fragment=!0)}if(c){if(S)for(b=0;b<S.length;b++)!S[b].used&&S[b].version>=2&&(I=S[b].grouping_type+"/0",A=new L(S[b].grouping_type,0),A.is_fragment=!0,c.sample_groups_info[I]||(c.sample_groups_info[I]=A))}else for(b=0;b<m.length;b++)!m[b].used&&m[b].version>=2&&(I=m[b].grouping_type+"/0",A=new L(m[b].grouping_type,0),o.sample_groups_info[I]||(o.sample_groups_info[I]=A))},v.setSampleGroupProperties=function(o,c,f,m){var S,T;c.sample_groups=[];for(S in m)if(c.sample_groups[S]={},c.sample_groups[S].grouping_type=m[S].grouping_type,c.sample_groups[S].grouping_type_parameter=m[S].grouping_type_parameter,f>=m[S].last_sample_in_run&&(m[S].last_sample_in_run<0&&(m[S].last_sample_in_run=0),m[S].entry_index++,m[S].entry_index<=m[S].sbgp.entries.length-1&&(m[S].last_sample_in_run+=m[S].sbgp.entries[m[S].entry_index].sample_count)),m[S].entry_index<=m[S].sbgp.entries.length-1?c.sample_groups[S].group_description_index=m[S].sbgp.entries[m[S].entry_index].group_description_index:c.sample_groups[S].group_description_index=-1,c.sample_groups[S].group_description_index!==0){var b;m[S].fragment_description?b=m[S].fragment_description:b=m[S].description,c.sample_groups[S].group_description_index>0?(c.sample_groups[S].group_description_index>65535?T=(c.sample_groups[S].group_description_index>>16)-1:T=c.sample_groups[S].group_description_index-1,b&&T>=0&&(c.sample_groups[S].description=b.entries[T])):b&&b.version>=2&&b.default_group_description_index>0&&(c.sample_groups[S].description=b.entries[b.default_group_description_index-1])}},v.process_sdtp=function(o,c,f){c&&(o?(c.is_leading=o.is_leading[f],c.depends_on=o.sample_depends_on[f],c.is_depended_on=o.sample_is_depended_on[f],c.has_redundancy=o.sample_has_redundancy[f]):(c.is_leading=0,c.depends_on=0,c.is_depended_on=0,c.has_redundancy=0))},v.prototype.buildSampleLists=function(){var o,c;for(o=0;o<this.moov.traks.length;o++)c=this.moov.traks[o],this.buildTrakSampleLists(c)},v.prototype.buildTrakSampleLists=function(o){var c,f,m,S,T,b,A,I,L,w,R,M,k,z,O,U,j,H,V,J,$,G,ie,ce;if(o.samples=[],o.samples_duration=0,o.samples_size=0,f=o.mdia.minf.stbl.stco||o.mdia.minf.stbl.co64,m=o.mdia.minf.stbl.stsc,S=o.mdia.minf.stbl.stsz||o.mdia.minf.stbl.stz2,T=o.mdia.minf.stbl.stts,b=o.mdia.minf.stbl.ctts,A=o.mdia.minf.stbl.stss,I=o.mdia.minf.stbl.stsd,L=o.mdia.minf.stbl.subs,M=o.mdia.minf.stbl.stdp,w=o.mdia.minf.stbl.sbgps,R=o.mdia.minf.stbl.sgpds,H=-1,V=-1,J=-1,$=-1,G=0,ie=0,ce=0,v.initSampleGroups(o,null,w,R),!(typeof S>"u")){for(c=0;c<S.sample_sizes.length;c++){var K={};K.number=c,K.track_id=o.tkhd.track_id,K.timescale=o.mdia.mdhd.timescale,K.alreadyRead=0,o.samples[c]=K,K.size=S.sample_sizes[c],o.samples_size+=K.size,c===0?(z=1,k=0,K.chunk_index=z,K.chunk_run_index=k,j=m.samples_per_chunk[k],U=0,k+1<m.first_chunk.length?O=m.first_chunk[k+1]-1:O=1/0):c<j?(K.chunk_index=z,K.chunk_run_index=k):(z++,K.chunk_index=z,U=0,z<=O||(k++,k+1<m.first_chunk.length?O=m.first_chunk[k+1]-1:O=1/0),K.chunk_run_index=k,j+=m.samples_per_chunk[k]),K.description_index=m.sample_description_index[K.chunk_run_index]-1,K.description=I.entries[K.description_index],K.offset=f.chunk_offsets[K.chunk_index-1]+U,U+=K.size,c>H&&(V++,H<0&&(H=0),H+=T.sample_counts[V]),c>0?(o.samples[c-1].duration=T.sample_deltas[V],o.samples_duration+=o.samples[c-1].duration,K.dts=o.samples[c-1].dts+o.samples[c-1].duration):K.dts=0,b?(c>=J&&($++,J<0&&(J=0),J+=b.sample_counts[$]),K.cts=o.samples[c].dts+b.sample_offsets[$]):K.cts=K.dts,A?(c==A.sample_numbers[G]-1?(K.is_sync=!0,G++):(K.is_sync=!1,K.degradation_priority=0),L&&L.entries[ie].sample_delta+ce==c+1&&(K.subsamples=L.entries[ie].subsamples,ce+=L.entries[ie].sample_delta,ie++)):K.is_sync=!0,v.process_sdtp(o.mdia.minf.stbl.sdtp,K,K.number),M?K.degradation_priority=M.priority[c]:K.degradation_priority=0,L&&L.entries[ie].sample_delta+ce==c&&(K.subsamples=L.entries[ie].subsamples,ce+=L.entries[ie].sample_delta),(w.length>0||R.length>0)&&v.setSampleGroupProperties(o,K,c,o.sample_groups_info)}c>0&&(o.samples[c-1].duration=Math.max(o.mdia.mdhd.duration-o.samples[c-1].dts,0),o.samples_duration+=o.samples[c-1].duration)}},v.prototype.updateSampleLists=function(){var o,c,f,m,S,T,b,A,I,L,w,R,M,k,z;if(this.moov!==void 0){for(;this.lastMoofIndex<this.moofs.length;)if(I=this.moofs[this.lastMoofIndex],this.lastMoofIndex++,I.type=="moof")for(L=I,o=0;o<L.trafs.length;o++){for(w=L.trafs[o],R=this.getTrackById(w.tfhd.track_id),M=this.getTrexById(w.tfhd.track_id),w.tfhd.flags&l.TFHD_FLAG_SAMPLE_DESC?m=w.tfhd.default_sample_description_index:m=M?M.default_sample_description_index:1,w.tfhd.flags&l.TFHD_FLAG_SAMPLE_DUR?S=w.tfhd.default_sample_duration:S=M?M.default_sample_duration:0,w.tfhd.flags&l.TFHD_FLAG_SAMPLE_SIZE?T=w.tfhd.default_sample_size:T=M?M.default_sample_size:0,w.tfhd.flags&l.TFHD_FLAG_SAMPLE_FLAGS?b=w.tfhd.default_sample_flags:b=M?M.default_sample_flags:0,w.sample_number=0,w.sbgps.length>0&&v.initSampleGroups(R,w,w.sbgps,R.mdia.minf.stbl.sgpds,w.sgpds),c=0;c<w.truns.length;c++){var O=w.truns[c];for(f=0;f<O.sample_count;f++){k={},k.moof_number=this.lastMoofIndex,k.number_in_traf=w.sample_number,w.sample_number++,k.number=R.samples.length,w.first_sample_index=R.samples.length,R.samples.push(k),k.track_id=R.tkhd.track_id,k.timescale=R.mdia.mdhd.timescale,k.description_index=m-1,k.description=R.mdia.minf.stbl.stsd.entries[k.description_index],k.size=T,O.flags&l.TRUN_FLAGS_SIZE&&(k.size=O.sample_size[f]),R.samples_size+=k.size,k.duration=S,O.flags&l.TRUN_FLAGS_DURATION&&(k.duration=O.sample_duration[f]),R.samples_duration+=k.duration,R.first_traf_merged||f>0?k.dts=R.samples[R.samples.length-2].dts+R.samples[R.samples.length-2].duration:(w.tfdt?k.dts=w.tfdt.baseMediaDecodeTime:k.dts=0,R.first_traf_merged=!0),k.cts=k.dts,O.flags&l.TRUN_FLAGS_CTS_OFFSET&&(k.cts=k.dts+O.sample_composition_time_offset[f]),z=b,O.flags&l.TRUN_FLAGS_FLAGS?z=O.sample_flags[f]:f===0&&O.flags&l.TRUN_FLAGS_FIRST_FLAG&&(z=O.first_sample_flags),k.is_sync=!(z>>16&1),k.is_leading=z>>26&3,k.depends_on=z>>24&3,k.is_depended_on=z>>22&3,k.has_redundancy=z>>20&3,k.degradation_priority=z&65535;var U=!!(w.tfhd.flags&l.TFHD_FLAG_BASE_DATA_OFFSET),j=!!(w.tfhd.flags&l.TFHD_FLAG_DEFAULT_BASE_IS_MOOF),H=!!(O.flags&l.TRUN_FLAGS_DATA_OFFSET),V=0;U?V=w.tfhd.base_data_offset:j||c===0?V=L.start:V=A,c===0&&f===0?H?k.offset=V+O.data_offset:k.offset=V:k.offset=A,A=k.offset+k.size,(w.sbgps.length>0||w.sgpds.length>0||R.mdia.minf.stbl.sbgps.length>0||R.mdia.minf.stbl.sgpds.length>0)&&v.setSampleGroupProperties(R,k,k.number_in_traf,w.sample_groups_info)}}if(w.subs){R.has_fragment_subsamples=!0;var J=w.first_sample_index;for(c=0;c<w.subs.entries.length;c++)J+=w.subs.entries[c].sample_delta,k=R.samples[J-1],k.subsamples=w.subs.entries[c].subsamples}}}},v.prototype.getSample=function(o,c){var f,m=o.samples[c];if(!this.moov)return null;if(!m.data)m.data=new Uint8Array(m.size),m.alreadyRead=0,this.samplesDataSize+=m.size,e.debug("ISOFile","Allocating sample #"+c+" on track #"+o.tkhd.track_id+" of size "+m.size+" (total: "+this.samplesDataSize+")");else if(m.alreadyRead==m.size)return m;for(;;){var S=this.stream.findPosition(!0,m.offset+m.alreadyRead,!1);if(S>-1){f=this.stream.buffers[S];var T=f.byteLength-(m.offset+m.alreadyRead-f.fileStart);if(m.size-m.alreadyRead<=T)return e.debug("ISOFile","Getting sample #"+c+" data (alreadyRead: "+m.alreadyRead+" offset: "+(m.offset+m.alreadyRead-f.fileStart)+" read size: "+(m.size-m.alreadyRead)+" full size: "+m.size+")"),s.memcpy(m.data.buffer,m.alreadyRead,f,m.offset+m.alreadyRead-f.fileStart,m.size-m.alreadyRead),f.usedBytes+=m.size-m.alreadyRead,this.stream.logBufferLevel(),m.alreadyRead=m.size,m;if(T===0)return null;e.debug("ISOFile","Getting sample #"+c+" partial data (alreadyRead: "+m.alreadyRead+" offset: "+(m.offset+m.alreadyRead-f.fileStart)+" read size: "+T+" full size: "+m.size+")"),s.memcpy(m.data.buffer,m.alreadyRead,f,m.offset+m.alreadyRead-f.fileStart,T),m.alreadyRead+=T,f.usedBytes+=T,this.stream.logBufferLevel()}else return null}},v.prototype.releaseSample=function(o,c){var f=o.samples[c];return f.data?(this.samplesDataSize-=f.size,f.data=null,f.alreadyRead=0,f.size):0},v.prototype.getAllocatedSampleDataSize=function(){return this.samplesDataSize},v.prototype.getCodecs=function(){var o,c="";for(o=0;o<this.moov.traks.length;o++){var f=this.moov.traks[o];o>0&&(c+=","),c+=f.mdia.minf.stbl.stsd.entries[0].getCodec()}return c},v.prototype.getTrexById=function(o){var c;if(!this.moov||!this.moov.mvex)return null;for(c=0;c<this.moov.mvex.trexs.length;c++){var f=this.moov.mvex.trexs[c];if(f.track_id==o)return f}return null},v.prototype.getTrackById=function(o){if(this.moov===void 0)return null;for(var c=0;c<this.moov.traks.length;c++){var f=this.moov.traks[c];if(f.tkhd.track_id==o)return f}return null},v.prototype.itemsDataSize=0,v.prototype.flattenItemInfo=function(){var o=this.items,c=this.entity_groups,f,m,S,T=this.meta;if(T!=null&&T.hdlr!==void 0&&T.iinf!==void 0){for(f=0;f<T.iinf.item_infos.length;f++)S={},S.id=T.iinf.item_infos[f].item_ID,o[S.id]=S,S.ref_to=[],S.name=T.iinf.item_infos[f].item_name,T.iinf.item_infos[f].protection_index>0&&(S.protection=T.ipro.protections[T.iinf.item_infos[f].protection_index-1]),T.iinf.item_infos[f].item_type?S.type=T.iinf.item_infos[f].item_type:S.type="mime",S.content_type=T.iinf.item_infos[f].content_type,S.content_encoding=T.iinf.item_infos[f].content_encoding,S.item_uri_type=T.iinf.item_infos[f].item_uri_type;if(T.grpl)for(f=0;f<T.grpl.boxes.length;f++)entity_group={},entity_group.id=T.grpl.boxes[f].group_id,entity_group.entity_ids=T.grpl.boxes[f].entity_ids,entity_group.type=T.grpl.boxes[f].type,c[entity_group.id]=entity_group;if(T.iloc)for(f=0;f<T.iloc.items.length;f++){var b=T.iloc.items[f];switch(S=o[b.item_ID],b.data_reference_index!==0&&(e.warn("Item storage with reference to other files: not supported"),S.source=T.dinf.boxes[b.data_reference_index-1]),b.construction_method){case 0:break;case 1:break;case 2:e.warn("Item storage with construction_method : not supported");break}for(S.extents=[],S.size=0,m=0;m<b.extents.length;m++)S.extents[m]={},S.extents[m].offset=b.extents[m].extent_offset+b.base_offset,b.construction_method==1&&(S.extents[m].offset+=T.idat.start+T.idat.hdr_size),S.extents[m].length=b.extents[m].extent_length,S.extents[m].alreadyRead=0,S.size+=S.extents[m].length}if(T.pitm&&(o[T.pitm.item_id].primary=!0),T.iref)for(f=0;f<T.iref.references.length;f++){var A=T.iref.references[f];for(m=0;m<A.references.length;m++)o[A.from_item_ID].ref_to.push({type:A.type,id:A.references[m]})}if(T.iprp)for(var I=0;I<T.iprp.ipmas.length;I++){var L=T.iprp.ipmas[I];for(f=0;f<L.associations.length;f++){var w=L.associations[f];if(S=o[w.id],S||(S=c[w.id]),S)for(S.properties===void 0&&(S.properties={},S.properties.boxes=[]),m=0;m<w.props.length;m++){var R=w.props[m];if(R.property_index>0&&R.property_index-1<T.iprp.ipco.boxes.length){var M=T.iprp.ipco.boxes[R.property_index-1];S.properties[M.type]=M,S.properties.boxes.push(M)}}}}}},v.prototype.getItem=function(o){var c,f;if(!this.meta)return null;if(f=this.items[o],!f.data&&f.size)f.data=new Uint8Array(f.size),f.alreadyRead=0,this.itemsDataSize+=f.size,e.debug("ISOFile","Allocating item #"+o+" of size "+f.size+" (total: "+this.itemsDataSize+")");else if(f.alreadyRead===f.size)return f;for(var m=0;m<f.extents.length;m++){var S=f.extents[m];if(S.alreadyRead!==S.length){var T=this.stream.findPosition(!0,S.offset+S.alreadyRead,!1);if(T>-1){c=this.stream.buffers[T];var b=c.byteLength-(S.offset+S.alreadyRead-c.fileStart);if(S.length-S.alreadyRead<=b)e.debug("ISOFile","Getting item #"+o+" extent #"+m+" data (alreadyRead: "+S.alreadyRead+" offset: "+(S.offset+S.alreadyRead-c.fileStart)+" read size: "+(S.length-S.alreadyRead)+" full extent size: "+S.length+" full item size: "+f.size+")"),s.memcpy(f.data.buffer,f.alreadyRead,c,S.offset+S.alreadyRead-c.fileStart,S.length-S.alreadyRead),c.usedBytes+=S.length-S.alreadyRead,this.stream.logBufferLevel(),f.alreadyRead+=S.length-S.alreadyRead,S.alreadyRead=S.length;else return e.debug("ISOFile","Getting item #"+o+" extent #"+m+" partial data (alreadyRead: "+S.alreadyRead+" offset: "+(S.offset+S.alreadyRead-c.fileStart)+" read size: "+b+" full extent size: "+S.length+" full item size: "+f.size+")"),s.memcpy(f.data.buffer,f.alreadyRead,c,S.offset+S.alreadyRead-c.fileStart,b),S.alreadyRead+=b,f.alreadyRead+=b,c.usedBytes+=b,this.stream.logBufferLevel(),null}else return null}}return f.alreadyRead===f.size?f:null},v.prototype.releaseItem=function(o){var c=this.items[o];if(c.data){this.itemsDataSize-=c.size,c.data=null,c.alreadyRead=0;for(var f=0;f<c.extents.length;f++){var m=c.extents[f];m.alreadyRead=0}return c.size}else return 0},v.prototype.processItems=function(o){for(var c in this.items){var f=this.items[c];this.getItem(f.id),o&&!f.sent&&(o(f),f.sent=!0,f.data=null)}},v.prototype.hasItem=function(o){for(var c in this.items){var f=this.items[c];if(f.name===o)return f.id}return-1},v.prototype.getMetaHandler=function(){return this.meta?this.meta.hdlr.handler:null},v.prototype.getPrimaryItem=function(){return!this.meta||!this.meta.pitm?null:this.getItem(this.meta.pitm.item_id)},v.prototype.itemToFragmentedTrackFile=function(o){var c=o||{},f=null;if(c.itemId?f=this.getItem(c.itemId):f=this.getPrimaryItem(),f==null)return null;var m=new v;m.discardMdatData=!1;var S={type:f.type,description_boxes:f.properties.boxes};f.properties.ispe&&(S.width=f.properties.ispe.image_width,S.height=f.properties.ispe.image_height);var T=m.addTrack(S);return T?(m.addSample(T,f.data),m):null},v.prototype.write=function(o){for(var c=0;c<this.boxes.length;c++)this.boxes[c].write(o)},v.prototype.createFragment=function(o,c,f){var m=this.getTrackById(o),S=this.getSample(m,c);if(S==null)return this.setNextSeekPositionFromSample(m.samples[c]),null;var T=f||new s;T.endianness=s.BIG_ENDIAN;var b=this.createSingleSampleMoof(S);b.write(T),b.trafs[0].truns[0].data_offset=b.size+8,e.debug("MP4Box","Adjusting data_offset with new value "+b.trafs[0].truns[0].data_offset),T.adjustUint32(b.trafs[0].truns[0].data_offset_position,b.trafs[0].truns[0].data_offset);var A=new l.mdatBox;return A.data=S.data,A.write(T),T},v.writeInitializationSegment=function(o,c,f,m){var S;e.debug("ISOFile","Generating initialization segment");var T=new s;T.endianness=s.BIG_ENDIAN,o.write(T);var b=c.add("mvex");for(f&&b.add("mehd").set("fragment_duration",f),S=0;S<c.traks.length;S++)b.add("trex").set("track_id",c.traks[S].tkhd.track_id).set("default_sample_description_index",1).set("default_sample_duration",m).set("default_sample_size",0).set("default_sample_flags",65536);return c.write(T),T.buffer},v.prototype.save=function(o){var c=new s;c.endianness=s.BIG_ENDIAN,this.write(c),c.save(o)},v.prototype.getBuffer=function(){var o=new s;return o.endianness=s.BIG_ENDIAN,this.write(o),o.buffer},v.prototype.initializeSegmentation=function(){var o,c,f,m;for(this.onSegment===null&&e.warn("MP4Box","No segmentation callback set!"),this.isFragmentationInitialized||(this.isFragmentationInitialized=!0,this.nextMoofNumber=0,this.resetTables()),c=[],o=0;o<this.fragmentedTracks.length;o++){var S=new l.moovBox;S.mvhd=this.moov.mvhd,S.boxes.push(S.mvhd),f=this.getTrackById(this.fragmentedTracks[o].id),S.boxes.push(f),S.traks.push(f),m={},m.id=f.tkhd.track_id,m.user=this.fragmentedTracks[o].user,m.buffer=v.writeInitializationSegment(this.ftyp,S,this.moov.mvex&&this.moov.mvex.mehd?this.moov.mvex.mehd.fragment_duration:void 0,this.moov.traks[o].samples.length>0?this.moov.traks[o].samples[0].duration:0),c.push(m)}return c},l.Box.prototype.printHeader=function(o){this.size+=8,this.size>n&&(this.size+=8),this.type==="uuid"&&(this.size+=16),o.log(o.indent+"size:"+this.size),o.log(o.indent+"type:"+this.type)},l.FullBox.prototype.printHeader=function(o){this.size+=4,l.Box.prototype.printHeader.call(this,o),o.log(o.indent+"version:"+this.version),o.log(o.indent+"flags:"+this.flags)},l.Box.prototype.print=function(o){this.printHeader(o)},l.ContainerBox.prototype.print=function(o){this.printHeader(o);for(var c=0;c<this.boxes.length;c++)if(this.boxes[c]){var f=o.indent;o.indent+=" ",this.boxes[c].print(o),o.indent=f}},v.prototype.print=function(o){o.indent="";for(var c=0;c<this.boxes.length;c++)this.boxes[c]&&this.boxes[c].print(o)},l.mvhdBox.prototype.print=function(o){l.FullBox.prototype.printHeader.call(this,o),o.log(o.indent+"creation_time: "+this.creation_time),o.log(o.indent+"modification_time: "+this.modification_time),o.log(o.indent+"timescale: "+this.timescale),o.log(o.indent+"duration: "+this.duration),o.log(o.indent+"rate: "+this.rate),o.log(o.indent+"volume: "+(this.volume>>8)),o.log(o.indent+"matrix: "+this.matrix.join(", ")),o.log(o.indent+"next_track_id: "+this.next_track_id)},l.tkhdBox.prototype.print=function(o){l.FullBox.prototype.printHeader.call(this,o),o.log(o.indent+"creation_time: "+this.creation_time),o.log(o.indent+"modification_time: "+this.modification_time),o.log(o.indent+"track_id: "+this.track_id),o.log(o.indent+"duration: "+this.duration),o.log(o.indent+"volume: "+(this.volume>>8)),o.log(o.indent+"matrix: "+this.matrix.join(", ")),o.log(o.indent+"layer: "+this.layer),o.log(o.indent+"alternate_group: "+this.alternate_group),o.log(o.indent+"width: "+this.width),o.log(o.indent+"height: "+this.height)};var _={};_.createFile=function(o,c){var f=o!==void 0?o:!0,m=new v(c);return m.discardMdatData=!f,m},r.createFile=_.createFile})(or);class Zh{constructor(e,t,s,n=0){this.segment=e,this.sourceFps=t,this.targetFps=s,this.sum=n,this.framesRequested=0}async getNextFrame(){var t;const e=this.sourceFps/this.targetFps;if(this.sum+=e,this.framesRequested+=1,this.sum<1&&this.lastFrame)return this.lastFrame;for(;this.sum>=2;){const s=await this.segment.getNextFrame();if(!s)return;s.close(),this.sum-=1}if(this.sum>=1||!this.lastFrame){this.sum-=1;const s=await this.segment.getNextFrame();return s?((t=this.lastFrame)==null||t.close(),this.lastFrame=s,s):void 0}throw new Error("Unreachable code")}getLastFrame(){return this.lastFrame}getSum(){return this.sum}getSegment(){return this.segment}getTime(e){return(this.framesRequested-e)/this.targetFps}}class Fu{constructor(e,t,s=0){this.file=e,this.setStatus=t,this.offset=s}write(e){const t=new ArrayBuffer(e.byteLength);new Uint8Array(t).set(e),t.fileStart=this.offset,this.offset+=t.byteLength,this.setStatus("fetch",(this.offset/1024**2).toFixed(1)+" MiB"),this.file.appendBuffer(t)}close(){this.setStatus("fetch","Done"),this.file.flush()}}const wS=30;class Jh{constructor(e,t,s,n,a=0){this.done=!1,this.currentFramePastSegmentEndTime=!1,this.abortController=new AbortController,this.responseFinished=!1,this.framesProcessed=0,this.framesDue=0,this.frameBuffer=[],this.encodedChunkQueue=[],this.readMore=async()=>{},this.uri=e,this.file=t,this.file.onSamples=this.onSamples.bind(this),this.edit=s[n],this.startTime=a;const h=Math.floor(this.startTime*this.edit.fps);this.framesProcessed+=h,this.decoder=new VideoDecoder({output:this.onFrame.bind(this),error(l){console.error(l)}})}async start(e){if(this.edit.mediaTime===-1){this.done=!0,this.responseFinished=!0,this.decoder.close();const d=this.edit.segmentDuration/this.file.getInfo().videoTracks[0].movie_timescale,p=Math.ceil(d*this.edit.fps),g=this.file.getInfo().videoTracks[0].track_height,y=this.file.getInfo().videoTracks[0].track_width,x=g*y*4,v=new ArrayBuffer(x),_=new Uint8Array(v);_.fill(0),this.frameBuffer=Array.from({length:p},()=>new VideoFrame(_,{timestamp:0,duration:1/this.edit.fps,codedHeight:g,codedWidth:y,format:"BGRA"}));return}this.decoder.configure(e);const t=this.file.getInfo().videoTracks[0],s=this.file.getTrackById(t.id),n=this.edit.mediaTime,a=this.startTime*t.timescale,l=(n+a)/t.timescale,u=this.file.seekTrack(l,!0,s);this.readMore=await this.startStreamingAtOffset(this.file,this.uri,u.offset)}async startStreamingAtOffset(e,t,s){return fetch(t,{headers:{Range:`bytes=${s}-`},signal:this.abortController.signal}).then(async n=>{if(!n.body)throw new Error("Response body is null");const a=n.body.getReader(),h=new Fu(e,()=>{},s);return async()=>a.read().then(({done:l,value:u})=>{if(l){this.responseFinished=!0,this.abortController.abort(),h.close();return}h.write(u)})})}onSamples(e,t,s){for(const n of s){const a=new EncodedVideoChunk({type:n.is_sync?"key":"delta",timestamp:1e6*n.cts/n.timescale,duration:1e6*n.duration/n.timescale,data:n.data});this.framesDue++,this.encodedChunkQueue.push(a);const h=this.file.getInfo().videoTracks[0],l=this.file.getTrackById(h.id);this.file.releaseSample(l,n.number)}}async decodeChunks(){for(;this.encodedChunkQueue.length>0&&this.decoder.decodeQueueSize<wS;){const e=this.encodedChunkQueue.shift();e&&this.decoder.decode(e)}if(this.done){this.currentFramePastSegmentEndTime=!0;return}if(this.responseFinished&&this.encodedChunkQueue.length===0){await this.flushDecoderWithRetry(),this.currentFramePastSegmentEndTime=!0;return}}async flushDecoderWithRetry(e=3,t=2e3){for(let s=0;s<e;s++){if(this.decoder.decodeQueueSize===0)return;try{await Promise.race([this.decoder.flush(),new Promise((n,a)=>setTimeout(()=>a(new Error("Flush timeout")),t))])}catch(n){if(s===e)throw n}}}async onFrame(e){this.framesDue--;const t=this.edit.mediaTime/this.file.getInfo().videoTracks[0].timescale,s=this.startTime+t,n=e.timestamp/1e6;if(n<s){e.close();return}const a=this.edit.segmentDuration/this.file.getInfo().videoTracks[0].movie_timescale,h=t+a;if(n>h){e.close(),this.done=!0,await this.decoder.flush();return}this.frameBuffer.push(e)}async populateBuffer(){for(;this.frameBuffer.length===0&&!this.currentFramePastSegmentEndTime;)this.responseFinished||await this.readMore(),await this.decodeChunks(),await new Promise(e=>setTimeout(e,0));if(this.frameBuffer.length===0&&this.framesDue>0){let e=200;for(;this.frameBuffer.length===0;)if(await new Promise(t=>setTimeout(t,10)),e--,this.done||e===0)return}}async getNextFrame(){await this.populateBuffer();const e=this.frameBuffer.shift();return e&&this.framesProcessed++,e}async close(){this.abortController.abort(),this.frameBuffer.forEach(e=>e.close());try{this.decoder.state==="configured"&&(await this.decoder.flush(),this.decoder.close())}catch{}}getFramesProcessed(){return this.framesProcessed}getStartTime(){return this.startTime}}function LS(r,e){const t=r.getTrackById(e.id);for(const s of t.mdia.minf.stbl.stsd.entries){const n=s.avcC||s.hvcC||s.vpcC||s.av1C;if(n){const a=new or.DataStream(void 0,0,or.DataStream.BIG_ENDIAN);return n.write(a),new Uint8Array(a.buffer,8)}}throw new Error("avcC, hvcC, vpcC, or av1C box not found")}function RS(r){return{mediaTime:r.media_time,segmentDuration:r.segment_duration,mediaRateInteger:r.media_rate_integer,mediaRateFraction:r.media_rate_fraction}}async function CS(r){return new Promise((e,t)=>{const s=or.createFile();let n=!1;const a=new AbortController;return s.onReady=h=>{var x;n=!0,a.abort();const l=h.videoTracks[0],u={codec:l.codec.startsWith("vp08")?"vp8":l.codec,codedHeight:l.video.height,codedWidth:l.video.width,description:LS(s,l)},d={mediaTime:0,segmentDuration:l.duration,mediaRateInteger:1,mediaRateFraction:0},p=(x=l.edits)==null?void 0:x.map(v=>RS(v)),y=(p!=null&&p.length?p:[d]).map(v=>{const _=l.duration/l.timescale,o=v.segmentDuration/l.movie_timescale,c=l.nb_samples*(o/_),f=v.mediaRateInteger+v.mediaRateFraction/65535,m=c/o*f;return{...v,fps:m}});s.setExtractionOptions(l.id),s.start(),e({file:s,edits:y,config:u})},fetch(r,{signal:a.signal}).then(async h=>{if(!h.body)throw new Error("Response body is null");const l=h.body.getReader(),u=new Fu(s,()=>{});for(;!n;)await l.read().then(({done:d,value:p})=>{if(d){s.flush(),a.abort(),t("Could not find moov");return}u.write(p)})})})}class PS{constructor(e,t,s){this.edits=[],this.nextSegment=0,this.uri=e,this.targetFps=t,this.startTime=s}async start(){const{file:e,edits:t,config:s}=await CS(this.uri);this.file=e,this.edits=t,this.decoderConfig=s}async getNextFrame(){var t;if(!this.sampler){let s=this.startTime;for(;this.nextSegment<this.edits.length;){const a=this.getSecondDurationOfSegment(this.edits[this.nextSegment]);if(s<a)break;s-=a,this.nextSegment++}if(this.nextSegment>=this.edits.length)throw new Error(`Timestamp ${this.startTime} is outside of the video, max timestamp is ${this.getDuration()}`);const n=new Jh(this.uri,this.file,this.edits,this.nextSegment,s);await n.start(this.decoderConfig),this.sampler=new Zh(n,this.edits[this.nextSegment].fps,this.targetFps,0),this.nextSegment++}let e=await this.sampler.getNextFrame();for(;!e&&this.nextSegment<this.edits.length;){this.sampler.getSegment().close(),(t=this.sampler.getLastFrame())==null||t.close();const s=new Jh(this.uri,this.file,this.edits,this.nextSegment,0);await s.start(this.decoderConfig),this.sampler=new Zh(s,this.edits[this.nextSegment].fps,this.targetFps,this.sampler.getSum()),this.nextSegment++,e=await this.sampler.getNextFrame()}if(!e&&(e=this.sampler.getLastFrame(),await this.sampler.getSegment().close(),!e))throw new Error("There are no frames in the video.");return e}getSecondDurationOfSegment(e){const t=e.mediaRateInteger+e.mediaRateFraction/65535;return e.segmentDuration/this.file.getInfo().videoTracks[0].movie_timescale/t}getDuration(){return this.edits.reduce((e,t)=>e+this.getSecondDurationOfSegment(t),0)}getTimeSubtractingFrames(e){const t=this.edits.slice(0,this.nextSegment-1).reduce((a,h)=>a+this.getSecondDurationOfSegment(h),0);if(!this.sampler)throw new Error("No current segment");const s=this.sampler.getSegment().getStartTime(),n=this.sampler.getTime(e);return t+s+n}getTime(){return this.getTimeSubtractingFrames(0)}getLastTime(){return this.getTimeSubtractingFrames(1)}getLastFrame(){var e;return(e=this.sampler)==null?void 0:e.getLastFrame()}close(){var e,t,s;(e=this.sampler)==null||e.getSegment().close(),(s=(t=this.sampler)==null?void 0:t.getLastFrame())==null||s.close(),this.file.flush()}}const ns=new Map;async function DS(r,e){const t=e+"-"+r,s=ns.get(t);s&&(s.close(),ns.delete(t))}async function kS(r,e,t,s){const n=e+"-"+r;let a=ns.get(n);const h=1/s,l=a==null?void 0:a.getDuration();l&&t>l&&(t=l);const u=a&&Math.abs(t-a.getLastTime())<h/2;if(a&&u){const d=a.getLastFrame();if(!d)throw new Error("No last frame");return d}return a&&t+h<a.getTime()&&(a.close(),ns.delete(n),a=void 0),a&&t>a.getTime()+h*1.5&&(a.close(),ns.delete(n),a=void 0),a||(a=new PS(e,s,t),await a.start(),ns.set(n,a)),a.getNextFrame()}var Yi=function(r,e,t,s){var n=arguments.length,a=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,t):s,h;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(r,e,t,s);else for(var l=r.length-1;l>=0;l--)(h=r[l])&&(a=(n<3?h(a):n>3?h(e,t,a):h(e,t))||a);return n>3&&a&&Object.defineProperty(e,t,a),a},hi;let vt=hi=class extends qe{constructor(e){super(e),this.detectedFileType="unknown",this.fileTypeWasDetected=!1,this.lastFrame=null}desiredSize(){const e=super.desiredSize();if(e.x===null&&e.y===null){const t=this.video();return{x:t.videoWidth,y:t.videoHeight}}return e}mediaElement(){return this.video()}seekedMedia(){return this.seekedVideo()}fastSeekedMedia(){return this.fastSeekedVideo()}video(){const e=this.src(),t=`${this.key}/${e||"pending"}`;let s=hi.pool[t];if(s){if(e&&e!=="undefined"&&s.src!==e){try{if(new URL(e,window.location.origin).pathname.endsWith(".m3u8")){const l=new Qt;l.loadSource(e),l.attachMedia(s)}else s.src=e}catch{s.src=e}delete hi.pool[t];const a=`${this.key}/${e}`;hi.pool[a]=s}}else{if(s=document.createElement("video"),s.crossOrigin="anonymous",e&&e!=="undefined")try{if(new URL(e,window.location.origin).pathname.endsWith(".m3u8")){const h=new Qt;h.loadSource(e),h.attachMedia(s)}else s.src=e}catch{s.src=e}hi.pool[t]=s}return(!e||e==="undefined")&&ye.collectPromise(new Promise(a=>{const h=()=>{const l=this.src();l&&l!=="undefined"?a():setTimeout(h,10)};h()})),this.waitForCanPlayNecessary(s)&&ye.collectPromise(new Promise(a=>{this.waitForCanPlay(s,a)})),s}seekedVideo(){const e=this.video(),t=this.clampTime(this.time());return e.playbackRate=this.playbackRate(),e.paused||e.pause(),this.lastTime===t||this.setCurrentTime(t),e}fastSeekedVideo(){const e=this.video(),t=this.clampTime(this.time());if(e.playbackRate=this.playbackRate(),this.lastTime===t)return e;const s=this.playing()&&t<e.duration&&e.playbackRate>0;return s?e.paused&&ye.collectPromise(e.play()):e.paused||e.pause(),Math.abs(e.currentTime-t)>1?this.setCurrentTime(t):s||(e.currentTime=t),e}async webcodecSeekedVideo(){const e=this.video(),t=this.clampTime(this.time());if(e.playbackRate=this.playbackRate(),this.lastFrame&&this.lastTime===t)return this.lastFrame;const s=this.view().fps()/this.playbackRate();return kS(this.key,e.src,t,s)}async ffmpegSeekedVideo(){const e=this.video(),t=this.clampTime(this.time()),s=this.getDuration();if(e.playbackRate=this.playbackRate(),this.lastFrame&&this.lastTime===t)return this.lastFrame;const n=this.view().fps()/this.playbackRate();if(!hi.imageCommunication)throw new Error("ServerSeekedVideo can only be used with HMR.");const a=await hi.imageCommunication.getFrame(this.key,e.src,t,s,n);return this.lastFrame=a,this.lastTime=t,a}async seekFunction(){const e=this.view().playbackState();return e===tt.Playing||e===tt.Presenting?this.fastSeekedVideo():e===tt.Paused?this.seekedVideo():this.decoder()==="slow"?this.seekedVideo():this.decoder()==="ffmpeg"?this.ffmpegSeekedVideo():this.decoder()==="web"?this.webcodecSeekedVideo():(this.fileTypeWasDetected||this.detectFileType(),this.detectedFileType==="webm"?this.ffmpegSeekedVideo():this.detectedFileType==="hls"?this.seekedVideo():this.webcodecSeekedVideo())}async draw(e){this.autoPlayBasedOnTwick(),this.drawShape(e);const t=this.alpha();if(t>0){const s=await this.seekFunction(),n=pe.fromSizeCentered(this.computedSize());e.save(),e.clip(this.getPath()),t<1&&(e.globalAlpha*=t),e.imageSmoothingEnabled=this.smoothing(),Zc(e,s,n),e.restore()}this.clip()&&e.clip(this.getPath()),await this.drawChildren(e)}applyFlex(){super.applyFlex();try{const e=this.video();e&&e.videoWidth>0&&e.videoHeight>0&&(this.element.style.aspectRatio=(this.ratio()??e.videoWidth/e.videoHeight).toString())}catch{}}remove(){return super.remove(),DS(this.key,this.src()),this}handleUnknownFileType(e){console.warn(`WARNING: Could not detect file type of video (${e}), will default to using mp4 decoder. If your video file is not an mp4 file, this will lead to an error - to fix this, reencode your video as an mp4 file (better performance) or specify a different decoder: https://docs.re.video/common-issues/slow-rendering#use-mp4-decoder`),this.detectedFileType="unknown",this.fileTypeWasDetected=!0}detectFileType(){return ye.collectPromise((async()=>{var a;const e=this.src(),t=(a=e.split("?")[0].split(".").pop())==null?void 0:a.toLowerCase();if(t==="mp4"||t==="webm"||t==="mov"){this.detectedFileType=t,this.fileTypeWasDetected=!0;return}if(t==="m3u8"){this.detectedFileType="hls",this.fileTypeWasDetected=!0;return}if(!e.startsWith("http://")&&!e.startsWith("https://")){this.handleUnknownFileType(e);return}const n=(await fetch(e,{method:"HEAD"})).headers.get("Content-Type");if(!n){this.handleUnknownFileType(e);return}if(n.includes("video/mp4")){this.detectedFileType="mp4",this.fileTypeWasDetected=!0;return}if(n.includes("video/webm")){this.detectedFileType="webm",this.fileTypeWasDetected=!0;return}if(n.includes("video/quicktime")){this.detectedFileType="mov",this.fileTypeWasDetected=!0;return}if(n.includes("application/vnd.apple.mpegurl")||n.includes("application/x-mpegURL")){this.detectedFileType="hls",this.fileTypeWasDetected=!0;return}this.handleUnknownFileType(e)})())}};vt.pool={};vt.imageCommunication=null;Yi([W(1),N()],vt.prototype,"alpha",void 0);Yi([W(!0),N()],vt.prototype,"smoothing",void 0);Yi([W(null),N()],vt.prototype,"decoder",void 0);Yi([te()],vt.prototype,"video",null);Yi([te()],vt.prototype,"seekedVideo",null);Yi([te()],vt.prototype,"fastSeekedVideo",null);vt=hi=Yi([ut("Video")],vt);class MS extends e0{constructor(e){super(e),this.view=null,this.registeredNodes=new Map,this.nodeCounters=new Map,this.assetHash=Date.now().toString(),this.recreateView()}getView(){return this.view}next(){var e;return(e=this.getView())==null||e.playbackState(this.playback.state).globalTime(this.playback.time),super.next()}async draw(e){e.save(),this.renderLifecycle.dispatch([Mt.BeforeRender,e]),e.save(),this.renderLifecycle.dispatch([Mt.BeginRender,e]),this.getView().playbackState(this.playback.state).globalTime(this.playback.time).fps(this.playback.fps),await this.getView().render(e),this.renderLifecycle.dispatch([Mt.FinishRender,e]),e.restore(),this.renderLifecycle.dispatch([Mt.AfterRender,e]),e.restore()}reset(e){for(const t of this.registeredNodes.keys())try{this.registeredNodes.get(t).dispose()}catch(s){this.logger.error(s)}return this.registeredNodes.clear(),this.registeredNodes=new Map,this.nodeCounters.clear(),this.recreateView(),super.reset(e)}inspectPosition(e,t){const s=this.getNodeByPosition(e,t);return s==null?void 0:s.key}getNodeByPosition(e,t){return this.execute(()=>this.getView().hit(new C(e,t))??null)}validateInspection(e){var t;return((t=this.getNode(e))==null?void 0:t.key)??null}inspectAttributes(e){const t=this.getNode(e);if(!t)return null;const s={stack:t.creationStack,key:t.key};for(const{key:n,meta:a,signal:h}of t)a.inspectable&&(s[n]=h());return s}drawOverlay(e,t,s){const n=this.getNode(e);n&&this.execute(()=>{n.drawOverlay(s,t.multiply(n.localToWorld()))})}transformMousePosition(e,t){return Nt(new C(e,t),this.getView().localToParent().inverse())}registerNode(e,t){var h;const s=((h=e.constructor)==null?void 0:h.name)??"unknown",n=(this.nodeCounters.get(s)??0)+1;this.nodeCounters.set(s,n),t&&this.registeredNodes.has(t)&&(Ue().error({message:`Duplicated node key: "${t}".`,inspect:t,stack:new Error().stack}),t=void 0),t??(t=`${this.name}/${s}[${n}]`),this.registeredNodes.set(t,e);const a=this.registeredNodes;return[t,()=>a.delete(t)]}getNode(e){return typeof e!="string"?null:this.registeredNodes.get(e)??null}*getDetachedNodes(){for(const e of this.registeredNodes.values())!e.parent()&&e!==this.view&&(yield e)}getMediaAssets(){const e=Array.from(this.registeredNodes.values()).filter(n=>n instanceof vt).filter(n=>n.isPlaying()),t=Array.from(this.registeredNodes.values()).filter(n=>n instanceof ti).filter(n=>n.isPlaying()),s=[];return s.push(...e.map(n=>({key:n.key,type:"video",src:n.src(),decoder:n.decoder(),playbackRate:typeof n.playbackRate=="function"?n.playbackRate():n.playbackRate,volume:n.getVolume(),currentTime:n.getCurrentTime(),duration:n.getDuration()}))),s.push(...t.map(n=>({key:n.key,type:"audio",src:n.src(),playbackRate:typeof n.playbackRate=="function"?n.playbackRate():n.playbackRate,volume:n.getVolume(),currentTime:n.getCurrentTime(),duration:n.getDuration()}))),s}stopAllMedia(){const e=Array.from(this.registeredNodes.values()).filter(t=>t instanceof qe).filter(t=>t.isPlaying());for(const t of e)t.dispose()}adjustVolume(e){const t=Array.from(this.registeredNodes.values()).filter(s=>s instanceof qe);for(const s of t)s.setVolume(s.getVolume()*e)}recreateView(){this.execute(()=>{const e=this.getSize();this.view=new ii({position:e.scale(this.resolutionScale/2),scale:this.resolutionScale,assetHash:this.assetHash,size:e})})}}function FS(r,e){return{klass:MS,name:r,config:e,stack:new Error().stack,plugins:["@twick/2d/editor"]}}const Uu="#000000",Ou={x:0,y:0},mi="easeInOut",Ls={VIDEO:"video",AUDIO:"audio",CAPTION:"caption",SCENE:"scene",ELEMENT:"element"},ec={highlight_bg:{rect:{alignItems:"center",gap:2},word:{lineWidth:.35,stroke:"#000000",fontWeight:700,shadowOffset:[-3,3],shadowColor:"#000000",fill:"#ffffff",fontFamily:"Bangers",bgColor:"#444444",bgOffsetWidth:30,bgOffsetHeight:8,fontSize:50}},word_by_word:{rect:{alignItems:"center",justifyContent:"center",gap:8},word:{lineWidth:.35,stroke:"#000000",fontWeight:700,strokeFirst:!0,shadowOffset:[-2,2],shadowColor:"#000000",shadowBlur:5,fontFamily:"Bangers",fill:"#FFFFFF",bgOffsetWidth:20,bgOffsetHeight:10,fontSize:50}},word_by_word_with_bg:{rect:{alignItems:"center",gap:8,padding:[10,20],radius:10},word:{lineWidth:.35,stroke:"#000000",fontWeight:700,strokeFirst:!0,shadowOffset:[-2,2],shadowColor:"#000000",shadowBlur:5,fontFamily:"Bangers",fill:"#FFFFFF",bgOffsetWidth:20,bgOffsetHeight:10,fontSize:50}}},US={text:"#000000",bgColor:"#444444"},OS={family:"Poppins",size:48,weight:400},BS="#FFFFFF00",tc={VIDEO:"video",IMAGE:"image"},Ia={CONTAIN:"contain",COVER:"cover",FILL:"fill"},Xe={SATURATED:"saturated",BRIGHT:"bright",VIBRANT:"vibrant",RETRO:"retro",BLACK_WHITE:"blackWhite",COOL:"cool",WARM:"warm",CINEMATIC:"cinematic",SOFT_GLOW:"softGlow",MOODY:"moody",DREAMY:"dreamy",INVERTED:"inverted",VINTAGE:"vintage",DRAMATIC:"dramatic",FADED:"faded"},ic={PLAYER_UPDATE:"twick:playerUpdate"};function nn(r,e){console.log(`[Visualizer] ${r}`,e||"")}const NS={name:"audio",*create({containerRef:r,element:e,view:t}){const s=Oe();yield*oe(e==null?void 0:e.s),yield r().add(ke(ti,{ref:s,play:!0,...e.props},e.id)),yield*oe(Math.max(0,e.e-e.s)),yield s().play(!1),yield s().remove()}};function $S({t:r,s:e,e:t}){const s=r.split(" "),n=t-e,a=s.join("").length;let h=e;return s.map(l=>{const u=l.length/a*n,d=h,p=d+u;return h=p,{t:l,s:parseFloat(d.toFixed(2)),e:parseFloat(p.toFixed(2))}})}const Bu=r=>{let e=r.replace(/^#/,"");if(e.length===3&&(e=e.split("").map(h=>h+h).join("")),e.length!==6)throw new Error("Invalid hex color");const t=parseInt(e,16),s=t>>16&255,n=t>>8&255,a=t&255;return{r:s,g:n,b:a}},GS={name:"caption",*create({containerRef:r,caption:e}){var a,h,l,u,d,p;const t=$S(e);let s=0;t!=null&&t.length&&(s=t[0].s);let n={refs:[],props:[],idx:0,prevTime:s};for(const g of t){n.props.push(e.props);const y=Oe(),x=e.props;if(r().add(ke($t,{ref:y,...x,text:g.t,opacity:0})),e.capStyle=="highlight_bg"){const v=Oe(),_=Oe(),o=new we({...Bu(x.colors.bgColor),a:(x==null?void 0:x.bgOpacity)??1});r().add(ke(je,{ref:v,fill:o,width:y().width()+(x.bgOffsetWidth??30),height:y().height()+(x.bgOffsetHeight??10),margin:x.bgMargin??[0,-5],radius:x.bgRadius??10,padding:x.bgPadding??[0,15],opacity:0,alignItems:"center",justifyContent:"center",layout:!0,children:ke($t,{ref:_,...x,text:g.t})})),y().remove(),n.refs.push({bgRef:v,textRef:_})}else n.refs.push({textRef:y});n.prevTime=g.e,n.idx=n.idx+1}n.prevTime=s,n.idx=0;for(const g of t)e.capStyle=="highlight_bg"?(yield*(h=(a=n.refs[n.idx])==null?void 0:a.bgRef)==null?void 0:h.call(a).opacity(1,0),yield*oe(Math.max(0,g.e-g.s)),yield*(u=(l=n.refs[n.idx])==null?void 0:l.bgRef)==null?void 0:u.call(l).fill(BS,0)):(yield*(p=(d=n.refs[n.idx])==null?void 0:d.textRef)==null?void 0:p.call(d).opacity(1,0),yield*oe(Math.max(0,g.e-g.s))),n.prevTime=g.e,n.idx=n.idx+1}},zS={name:"elastic",*run({elementRef:r,duration:e,delay:t}){t&&(yield*oe(t)),r().scale(0),yield*r().scale(1,e,dc)}},HS={name:"erase",*run({elementRef:r,duration:e,delay:t,bufferTime:s=.1}){const n=r().text(),a=r().size();r().setText(""),r().size(a),r().textAlign("left"),t&&(yield*oe(t));let h=(e-s)/n.length;yield*oe(h);for(let l=n.length;l>=0;l--)yield*oe(h),r().setText(n.substring(0,l))}},VS={name:"stream-word",*run({elementRef:r,duration:e,delay:t,bufferTime:s=.1}){const n=r().text(),a=r().size(),h=n.split(" ");r().setText(""),r().size(a),t&&(yield*oe(t)),r().textAlign("left");let l=(e-s)/h.length;for(let u=0;u<h.length;u++)yield*oe(l),r().setText(h.slice(0,u+1).join(" "))}},KS={name:"typewriter",*run({elementRef:r,duration:e,delay:t,bufferTime:s=.1}){const n=r().text(),a=r().size();r().setText(""),r().size(a),r().textAlign("left"),t&&(yield*oe(t));let h=(e-s)/n.length;yield*oe(h);for(let l=0;l<n.length;l++)yield*oe(h),r().setText(n.substring(0,l+1))}};class YS{constructor(){this.effects=new Map}register(e){this.effects.set(e.name,e)}get(e){return this.effects.get(e)}list(){return Array.from(this.effects.keys())}}const WS=()=>{Cs.register(KS),Cs.register(VS),Cs.register(HS),Cs.register(zS)},Cs=new YS;WS();const jS={name:"blur",*run({elementRef:r,containerRef:e,interval:t,duration:s,intensity:n=25,animate:a}){const h=e??r;let l=Math.min(t,s);a==="enter"?(h().filters.blur(n),yield*h().filters.blur(0,l)):a==="exit"?(yield*oe(s-l),yield*h().filters.blur(n,l)):a==="both"&&(l=Math.min(t,s/2),h().filters.blur(n),yield*h().filters.blur(0,l),yield*oe(s-l),yield*h().filters.blur(n,l))}};function Ot(r){switch(r){case"easeInSine":return af;case"easeOutSine":return of;case"easeInOutSine":return lf;case"easeInQuad":return hf;case"easeOutQuad":return cf;case"easeInOutQuad":return df;case"easeInCubic":return uf;case"easeOutCubic":return ff;case"easeInOutCubic":return Bs;case"easeInQuart":return pf;case"easeOutQuart":return gf;case"easeInOutQuart":return mf;case"easeInQuint":return yf;case"easeOutQuint":return vf;case"easeInOutQuint":return xf;case"easeInExpo":return Sf;case"easeOutExpo":return hc;case"easeInOutExpo":return _f;case"easeInCirc":return Ef;case"easeOutCirc":return Tf;case"easeInOutCirc":return bf;case"easeInBack":return kf;case"easeOutBack":return Mf;case"easeInOutBack":return Ff;case"easeInElastic":return Nf;case"easeOutElastic":return dc;case"easeInOutElastic":return $f;case"easeInBounce":return Uf;case"easeOutBounce":return Of;case"easeInOutBounce":return Bf;default:return cc}}const qS={name:"breathe",*run({elementRef:r,containerRef:e,mode:t,duration:s,intensity:n=.5}){const a=e??r,h=a().scale();t==="in"&&(yield*a().scale(new C(h.x*n,h.y*n),s,Ot("easeInSine"))),t==="out"&&(a().scale(new C(h.x*n,h.y*n)),yield*a().scale(new C(h.x,h.y),s,Ot("easeOutSine")))}},XS={name:"fade",*run({elementRef:r,containerRef:e,interval:t,duration:s,animate:n}){const a=e??r;let h=Math.min(t,s);n==="enter"?(a().opacity(0),yield*a().opacity(1,h)):n==="exit"?(yield*oe(s-h),yield*a().opacity(0,h)):n==="both"&&(h=Math.min(t,s/2),a().opacity(0),yield*a().opacity(1,h),yield*oe(s-h),yield*a().opacity(0,h))}},QS={name:"photo-rise",*run({elementRef:r,containerRef:e,direction:t,duration:s,intensity:n=200}){if(e){const a=r().position();t==="up"?(r().y(a.y+n),yield*r().y(a.y,s)):t==="down"?(r().y(a.y-n),yield*r().y(a.y,s)):t==="left"?(r().x(a.x+n),yield*r().x(a.x,s)):t==="right"&&(r().x(a.x-n),yield*r().x(a.x,s))}}},ZS={name:"photo-zoom",*run({elementRef:r,containerRef:e,mode:t,duration:s,intensity:n=1.5}){if(e){const a=r().scale();t==="in"&&(yield r().scale(new C(a.x*n,a.y*n)),yield*r().scale(new C(a.x,a.y),s)),t==="out"&&(r().scale(new C(a.x,a.y)),yield*r().scale(new C(a.x*n,a.y*n),s))}}},JS={name:"rise",*run({elementRef:r,containerRef:e,interval:t=.25,duration:s,animate:n,direction:a,intensity:h=200}){const l=e??r,u=l().position();let d=Math.min(t,s);n==="enter"?(l().opacity(0),a==="up"?(l().y(u.y+h),yield*Se(l().opacity(1,d/4),l().y(u.y,d))):a==="down"&&(l().y(u.y-h),yield*Se(l().opacity(1,d/4),l().y(u.y,d)))):n==="exit"?(yield*oe(s-d),a==="up"?yield*Se(Fi(3*d/4,l().opacity(0,d/4)),l().y(u.y-h,d)):a==="down"&&(yield*Se(Fi(3*d/4,l().opacity(0,d/4)),l().y(u.y+h,d)))):n==="both"&&(d=Math.min(t,s/2),l().opacity(0),a==="up"?(l().y(u.y+h),yield*Se(l().opacity(1,d/4),l().y(u.y,d)),yield*oe(s-d),yield*Se(Fi(3*d/4,l().opacity(0,d/4)),l().y(u.y-h,d))):a==="down"&&(l().y(u.y-h),yield*Se(l().opacity(1,d/4),l().y(u.y,d)),yield*oe(s-d),yield*Se(Fi(3*d/4,l().opacity(0,d/4)),l().y(u.y+h,d))))}},e_={name:"succession",*run({elementRef:r,containerRef:e,interval:t,duration:s,animate:n}){const a=e??r,h=a().scale();let l=Math.min(t,s);n==="enter"?(a().opacity(0),a().scale(new C(h.x/2,h.y/2)),yield*Se(a().scale(h,l),a().opacity(1,l/2))):n==="exit"?(yield*oe(s-l),yield*Se(a().scale(new C(h.x/2,h.y/2),l),Fi(l/2,a().opacity(0,l/2)))):n==="both"&&(l=Math.min(t,s/2),a().opacity(0),a().scale(new C(h.x/2,h.y/2)),yield*Se(a().scale(h,l),a().opacity(1,l/2)),yield*oe(s-l),yield*Se(a().scale(new C(h.x/2,h.y/2),l),Fi(l/2,a().opacity(0,l/2))))}};class t_{constructor(){this.animations=new Map}register(e){this.animations.set(e.name,e)}get(e){return this.animations.get(e)}list(){return Array.from(this.animations.keys())}}const i_=()=>{ci.register(XS),ci.register(JS),ci.register(qS),ci.register(e_),ci.register(jS),ci.register(ZS),ci.register(QS)},ci=new t_;i_();const s_={name:"circle",*run({containerRef:r,elementRef:e,initFrameState:t,frameEffect:s}){yield*oe(s.s);const n=s.props,a=[];a.push(r().size({x:n.frameSize[0],y:n.frameSize[1]},n.transitionDuration,Ot(n.transitionEasing??mi))),a.push(r().position(n.framePosition??{x:0,y:0},n.transitionDuration,Ot(n.transitionEasing??mi))),a.push(e().position(n.elementPosition??Ou,n.transitionDuration,Ot(n.transitionEasing??mi))),a.push(r().radius(n.frameSize[0]/2,n.transitionDuration,Ot(n.transitionEasing??mi))),n.objectFit&&a.push(rn({elementRef:e,containerSize:{x:n.frameSize[0],y:n.frameSize[1]},elementSize:t.element.size,objectFit:n.objectFit})),yield*Se(...a)}},n_={name:"rect",*run({containerRef:r,elementRef:e,initFrameState:t,frameEffect:s}){yield*oe(s.s);const n=s.props,a=[];a.push(r().size(n.frameSize,n.transitionDuration,Ot(n.transitionEasing??mi))),a.push(r().position(n.framePosition??{x:0,y:0},n.transitionDuration,Ot(n.transitionEasing??mi))),a.push(e().position(n.elementPosition??Ou,n.transitionDuration,Ot(n.transitionEasing??mi))),a.push(r().radius(n.radius??0,n.transitionDuration,Ot(n.transitionEasing??mi))),n.objectFit&&a.push(rn({elementRef:e,containerSize:{x:n.frameSize[0],y:n.frameSize[1]},elementSize:t.element.size,objectFit:n.objectFit})),yield*Se(...a)}};class r_{constructor(){this.frameEffects=new Map}register(e){this.frameEffects.set(e.name,e)}get(e){return this.frameEffects.get(e)}list(){return Array.from(this.frameEffects.keys())}}const a_=()=>{ao.register(s_),ao.register(n_)},ao=new r_;a_();function*rn({containerSize:r,elementSize:e,elementRef:t,objectFit:s}){const n=r.x/r.y,a=e.x/e.y;switch(s){case Ia.CONTAIN:a>n?(yield t().size({x:r.x,y:r.x/a}),yield t().scale(r.x/e.x,r.x*a/e.y)):(yield t().size({x:r.y*a,y:r.y}),yield t().scale(r.y*a/e.x,r.y/e.y));break;case Ia.COVER:a>n?(yield t().size({x:r.y*a,y:r.y}),yield t().scale(r.y*a/e.x,r.y/e.y)):(yield t().size({x:r.x,y:r.x/a}),yield t().scale(r.x/e.x,r.x*a/e.y));break;case Ia.FILL:yield t().size(r),yield t().scale(r.x/e.x,r.x/e.y);break}}function*o_({elementRef:r,element:e}){if(yield r(),e.textEffect){const t=Cs.get(e.textEffect.name);t&&(yield*t.run({elementRef:r,duration:e.e-e.s,...e.textEffect}))}}function*Ts({elementRef:r,containerRef:e,element:t,view:s}){if(yield r(),t.animation){const n=ci.get(t.animation.name);n&&(yield*n.run({elementRef:r,containerRef:e,view:s,duration:t.e-t.s,...t.animation}))}}function*Nu({containerRef:r,elementRef:e,element:t}){var n;const s=l_({containerRef:r,elementRef:e});for(let a=0;a<((n=t==null?void 0:t.frameEffects)==null?void 0:n.length);a++){const h=t.frameEffects[a],l=a===t.frameEffects.length-1||t.frameEffects[a+1].s!==h.e,u=ao.get(h.name);u&&(yield*u.run({containerRef:r,elementRef:e,initFrameState:s,frameEffect:h}),l&&(yield*h_({containerRef:r,elementRef:e,duration:h.e-h.s,element:t,initProps:s})))}}function l_({containerRef:r,elementRef:e}){return{frame:{size:r().size(),pos:r().position(),radius:r().radius(),scale:r().scale(),rotation:r().rotation()},element:{size:r().size(),pos:e().position(),scale:e().scale()}}}function*h_({containerRef:r,elementRef:e,duration:t,element:s,initProps:n}){yield*oe(t),nn(`restoreFrameState: ${JSON.stringify(n)}`);let a=[];a.push(r().size(n.frame.size)),a.push(r().position(n.frame.pos)),a.push(r().scale(n.frame.scale)),a.push(r().rotation(n.frame.rotation)),a.push(r().radius(n.frame.radius)),a.push(e().size(n.element.size)),a.push(e().position(n.element.pos)),a.push(e().scale(n.element.scale)),a.push(rn({elementRef:e,containerSize:n.frame.size,elementSize:n.element.size,objectFit:s.objectFit??"none"})),yield*Se(...a)}const c_={name:"circle",*create({containerRef:r,element:e,view:t}){const s=Oe();yield*oe(e==null?void 0:e.s),yield r().add(ke(Gi,{ref:s,...e.props},e.id)),yield*Se(Ts({elementRef:s,element:e,view:t}),oe(Math.max(0,e.e-e.s))),yield s().remove()}},d_={name:"icon",*create({containerRef:r,element:e,view:t}){const s=Oe();yield*oe(e==null?void 0:e.s),yield r().add(ke(Ir,{ref:s,...e.props},e.id)),yield*Se(Ts({elementRef:s,element:e,view:t}),oe(Math.max(0,e.e-e.s))),yield s().remove()}},$u=(r,e)=>{switch(e){case Xe.SATURATED:r().filters.saturate(1.4),r().filters.contrast(1.1);break;case Xe.BRIGHT:r().filters.brightness(1.3),r().filters.contrast(1.05);break;case Xe.VIBRANT:r().filters.saturate(1.6),r().filters.brightness(1.15),r().filters.contrast(1.1);break;case Xe.RETRO:r().filters.sepia(.8),r().filters.contrast(1.3),r().filters.brightness(.85),r().filters.saturate(.8);break;case Xe.BLACK_WHITE:r().filters.grayscale(1),r().filters.contrast(1.25),r().filters.brightness(1.05);break;case Xe.COOL:r().filters.hue(15),r().filters.brightness(1.1),r().filters.saturate(1.3),r().filters.contrast(1.05);break;case Xe.WARM:r().filters.hue(-15),r().filters.brightness(1.15),r().filters.saturate(1.3),r().filters.contrast(1.05);break;case Xe.CINEMATIC:r().filters.contrast(1.4),r().filters.brightness(.95),r().filters.saturate(.85),r().filters.sepia(.2);break;case Xe.SOFT_GLOW:r().filters.brightness(1.2),r().filters.contrast(.95),r().filters.blur(1.2),r().filters.saturate(1.1);break;case Xe.MOODY:r().filters.brightness(1.05),r().filters.contrast(1.4),r().filters.saturate(.65),r().filters.sepia(.2);break;case Xe.DREAMY:r().filters.brightness(1.3),r().filters.blur(2),r().filters.saturate(1.4),r().filters.contrast(.95);break;case Xe.INVERTED:r().filters.invert(1),r().filters.hue(180);break;case Xe.VINTAGE:r().filters.sepia(.4),r().filters.saturate(1.4),r().filters.contrast(1.2),r().filters.brightness(1.1);break;case Xe.DRAMATIC:r().filters.contrast(1.5),r().filters.brightness(.9),r().filters.saturate(1.2);break;case Xe.FADED:r().filters.opacity(.9),r().filters.brightness(1.2),r().filters.saturate(.8),r().filters.contrast(.9);break}},Gu={name:"image",*create({containerRef:r,element:e,view:t}){var a;yield*oe(e==null?void 0:e.s);const s=Oe(),n=Oe();yield r().add(ke(je,{ref:s,...e.frame,children:ke(mt,{ref:n,...e.props},`child-${e.id}`)},e.id)),s()&&(yield rn({elementRef:n,containerSize:s().size(),elementSize:n().size(),objectFit:e.objectFit}),(a=e==null?void 0:e.props)!=null&&a.mediaFilter&&$u(n,e.props.mediaFilter),yield*Se(Ts({elementRef:n,containerRef:s,element:e,view:t}),Nu({containerRef:s,elementRef:n,element:e}),oe(Math.max(0,e.e-e.s))),yield n().remove(),yield s().remove())}},u_={name:"rect",*create({containerRef:r,element:e,view:t}){const s=Oe();yield*oe(e==null?void 0:e.s),nn(`RectElement: ${JSON.stringify(e)}`),yield r().add(ke(je,{ref:s,...e.props},e.id)),yield*Se(Ts({elementRef:s,element:e,view:t}),oe(Math.max(0,e.e-e.s))),yield s().remove()}},zu={name:"video",*create({containerRef:r,element:e,view:t}){var a;yield*oe(e==null?void 0:e.s);const s=Oe(),n=Oe();yield r().add(ke(je,{ref:s,...e.frame,children:ke(vt,{ref:n,play:!0,...e.props},`child-${e.id}`)},e.id)),s()&&(yield rn({elementRef:n,containerSize:s().size(),elementSize:n().size(),objectFit:e.objectFit}),(a=e==null?void 0:e.props)!=null&&a.mediaFilter&&$u(n,e.props.mediaFilter),yield*Se(Ts({elementRef:n,containerRef:s,element:e,view:t}),Nu({containerRef:s,elementRef:n,element:e}),oe(Math.max(0,e.e-e.s))),yield n().play(!1),yield n().remove(),yield s().remove())}},f_={name:"scene",*create({containerRef:r,element:e,view:t}){yield*oe(e==null?void 0:e.s);const s=Oe();nn(`SceneElement: ${JSON.stringify(e)}`),yield r().add(ke(je,{ref:s,fill:e.backgroundColor??Uu,size:"100%"})),e.type===tc.IMAGE?yield*Gu.create({containerRef:r,element:e,view:t}):e.type===tc.VIDEO&&(yield*zu.create({containerRef:r,element:e,view:t})),yield s().remove()}},p_={name:"text",*create({containerRef:r,element:e,view:t}){var n,a;const s=Oe();yield*oe(e==null?void 0:e.s),yield r().add(ke($t,{ref:s,text:e.t,textWrap:((n=e.props)==null?void 0:n.textWrap)??!0,textAlign:((a=e.props)==null?void 0:a.textAlign)??"center",...e.props},e.id)),yield*Se(Ts({elementRef:s,element:e,view:t}),o_({elementRef:s,element:e}),oe(Math.max(0,e.e-e.s))),yield s().remove()}};class g_{constructor(){this.elements=new Map}register(e){this.elements.set(e.name,e)}get(e){return this.elements.get(e)}list(){return Array.from(this.elements.keys())}}const m_=()=>{ht.register(zu),ht.register(GS),ht.register(f_),ht.register(Gu),ht.register(p_),ht.register(NS),ht.register(c_),ht.register(d_),ht.register(u_)},ht=new g_;m_();function*y_({view:r,track:e}){var n;const t=Oe();let s=0;r.add(ke(Q,{size:"100%",ref:t,layout:!0}));for(const a of e.elements||[])yield*oe((a==null?void 0:a.s)-s),yield*(n=ht.get("video"))==null?void 0:n.create({containerRef:t,element:a,view:r}),s=a.e;yield t().remove()}function*v_({view:r,track:e}){let t=0;for(const s of e.elements){const n=Oe();yield*oe((s==null?void 0:s.s)-t),t=s==null?void 0:s.e,nn(`Adding audio element ${s.id}`),r.add(ke(ti,{ref:n,...s.props},s.id)),yield*oe(Math.max(0,s.e-s.s)),yield n().playing(!1),yield n().remove()}}function*x_({view:r,track:e}){var l;let t=0;const s=Oe();r.add(ke(Q,{size:"100%",ref:s}));const n=e==null?void 0:e.props,a=(n==null?void 0:n.applyToAll)??!1,h=(ec[(n==null?void 0:n.capStyle)??""]||{}).word||{};for(const u of e.elements){const d=u.props,p=(ec[(d==null?void 0:d.capStyle)??(n==null?void 0:n.capStyle)??""]||{}).rect||{},g={...p,justifyContent:p.justifyContent,alignItems:p.alignItems},y=a?n==null?void 0:n.colors:(d==null?void 0:d.colors)??(n==null?void 0:n.colors)??US,x={...h,...(n==null?void 0:n.captionProps)||{},colors:y,font:a?n==null?void 0:n.font:(d==null?void 0:d.font)??(n==null?void 0:n.font)??OS,fill:y.text,bgColor:y.bgColor,bgOpacity:(n==null?void 0:n.bgOpacity)??1};yield*oe((u==null?void 0:u.s)-t);const v=Oe();if(s().add(ke(je,{ref:v,...g,x:a?n==null?void 0:n.x:(d==null?void 0:d.x)??(n==null?void 0:n.x),y:a?n==null?void 0:n.y:(d==null?void 0:d.y)??(n==null?void 0:n.y),layout:!0},u.id)),(n==null?void 0:n.capStyle)==="word_by_word_with_bg"){const _=new we({...Bu(x.bgColor),a:(x==null?void 0:x.bgOpacity)??1});v().fill(_)}yield*(l=ht.get("caption"))==null?void 0:l.create({containerRef:v,caption:{...u,t:u.t??"",capStyle:(d==null?void 0:d.capStyle)??(n==null?void 0:n.capStyle),props:x},view:r}),t=u.e,yield v().remove()}}function*S_({view:r,track:e}){var s;const t=Oe();r.add(ke(Q,{size:"100%",ref:t,layout:!0}));for(const n of e.elements||[])yield*(s=ht.get("scene"))==null?void 0:s.create({containerRef:t,element:n,view:r});yield t().remove()}function*__({view:r,track:e}){var n;const t=Oe();r.add(ke(Q,{size:"100%",ref:t}));const s=[];try{for(const a of e.elements)s.push((n=ht.get(a.type))==null?void 0:n.create({containerRef:t,element:a,view:r}))}catch(a){nn("Error creating element track",a)}yield*Se(...s),yield t().remove()}const sc=(r,e)=>{if(typeof window<"u"){const t=new CustomEvent(r,e);return window.dispatchEvent(t)}},E_=FS("scene",function*(r){const e=zn().variables.get("input",null)(),t=zn().variables.get("playerId",null)();if(e)if(console.log("Scene updated",{playerId:t,input:e}),yield r.add(ke(je,{fill:e.backgroundColor??Uu,size:"100%"})),e.tracks){const s=[];for(const n of e.tracks)switch(n.type){case Ls.VIDEO:s.push(y_({view:r,track:n}));break;case Ls.AUDIO:s.push(v_({view:r,track:n}));break;case Ls.CAPTION:s.push(x_({view:r,track:n}));break;case Ls.SCENE:s.push(S_({view:r,track:n}));break;case Ls.ELEMENT:s.push(__({view:r,track:n}));break}yield*Se(...s),sc(ic.PLAYER_UPDATE,{detail:{status:"ready",playerId:t,message:"All elements created"}})}else sc(ic.PLAYER_UPDATE,{detail:{status:"ready",playerId:t,message:"No elements to create"}})}),G_=Bg({scenes:[E_]});export{G_ as default};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@twick/visualizer",
3
- "version": "0.14.17",
3
+ "version": "0.14.20",
4
4
  "license": "SEE LICENSE IN LICENSE.md",
5
5
  "scripts": {
6
6
  "start": "twick editor --projectFile ./src/live.tsx",
@@ -19,18 +19,18 @@
19
19
  },
20
20
  "dependencies": {
21
21
  "@preact/signals": "^1.2.1",
22
- "@twick/2d": "0.14.17",
23
- "@twick/core": "0.14.17",
24
- "@twick/renderer": "0.14.17",
25
- "@twick/vite-plugin": "0.14.17",
22
+ "@twick/2d": "^0.14.20",
23
+ "@twick/core": "^0.14.20",
24
+ "@twick/renderer": "^0.14.20",
25
+ "@twick/vite-plugin": "^0.14.20",
26
26
  "date-fns": "^4.1.0",
27
27
  "preact": "^10.19.2",
28
28
  "crelt": "^1.0.6",
29
- "@twick/media-utils": "0.14.17"
29
+ "@twick/media-utils": "0.14.20"
30
30
  },
31
31
  "devDependencies": {
32
- "@twick/cli": "0.14.11",
33
- "@twick/ui": "0.14.11",
32
+ "@twick/cli": "^0.14.20",
33
+ "@twick/ui": "^0.14.20",
34
34
  "typescript": "5.4.2",
35
35
  "typedoc": "^0.25.8",
36
36
  "typedoc-plugin-markdown": "^3.17.1",
@@ -88,6 +88,8 @@ export const TextElement = {
88
88
  ref={elementRef}
89
89
  key={element.id}
90
90
  text={element.t}
91
+ textWrap={element.props?.textWrap ?? true}
92
+ textAlign={element.props?.textAlign ?? "center"}
91
93
  {...element.props}
92
94
  />
93
95
  );