@htmlbricks/hb-player-live 0.66.6 → 0.66.7

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/main.iife.js CHANGED
@@ -1,73 +1,65 @@
1
- (function(ea){"use strict";typeof window<"u"&&((window.__svelte??={}).v??=new Set).add("5");const _u=1,Iu=2,ta="[",sa="[!",ia="[?",ra="]",Es={},Pe=Symbol(),Lu="http://www.w3.org/1999/xhtml",Ru=!1;var bu=Array.isArray,Du=Array.prototype.indexOf,Ts=Array.prototype.includes,Cu=Array.from,yi=Object.keys,vi=Object.defineProperty,Ss=Object.getOwnPropertyDescriptor,Pu=Object.prototype,wu=Array.prototype,ku=Object.getPrototypeOf,na=Object.isExtensible;const Ou=()=>{};function Mu(r){for(var e=0;e<r.length;e++)r[e]()}function aa(){var r,e,t=new Promise((s,i)=>{r=s,e=i});return{promise:t,resolve:r,reject:e}}const be=2,xs=4,Ei=8,oa=1<<24,Kt=16,mt=32,Vt=64,yr=128,et=512,Ie=1024,Fe=2048,pt=4096,yt=8192,lt=16384,Ht=32768,la=1<<25,As=65536,ca=1<<17,Fu=1<<18,ns=1<<19,Nu=1<<20,as=65536,vr=1<<21,Er=1<<22,Wt=1<<23,Tr=Symbol("$state"),$u=Symbol("legacy props"),Ct=new class extends Error{name="StaleReactionError";message="The reaction that called `getAbortSignal()` was re-run or destroyed"},Ti=3,Si=8;function Bu(r){throw new Error("https://svelte.dev/e/lifecycle_outside_component")}function Uu(){throw new Error("https://svelte.dev/e/async_derived_orphan")}function Gu(r){throw new Error("https://svelte.dev/e/effect_in_teardown")}function Ku(){throw new Error("https://svelte.dev/e/effect_in_unowned_derived")}function Vu(r){throw new Error("https://svelte.dev/e/effect_orphan")}function Hu(){throw new Error("https://svelte.dev/e/effect_update_depth_exceeded")}function Wu(){throw new Error("https://svelte.dev/e/hydration_failed")}function Yu(){throw new Error("https://svelte.dev/e/state_descriptors_fixed")}function qu(){throw new Error("https://svelte.dev/e/state_prototype_fixed")}function ju(){throw new Error("https://svelte.dev/e/state_unsafe_mutation")}function Xu(){throw new Error("https://svelte.dev/e/svelte_boundary_reset_onerror")}function xi(r){console.warn("https://svelte.dev/e/hydration_mismatch")}function zu(){console.warn("https://svelte.dev/e/svelte_boundary_reset_noop")}let Ee=!1;function _s(r){Ee=r}let ne;function ct(r){if(r===null)throw xi(),Es;return ne=r}function Ai(){return ct(kt(ne))}function fe(r){if(Ee){if(kt(ne)!==null)throw xi(),Es;ne=r}}function Qu(r=1){if(Ee){for(var e=r,t=ne;e--;)t=kt(t);ne=t}}function ua(r=!0){for(var e=0,t=ne;;){if(t.nodeType===Si){var s=t.data;if(s===ra){if(e===0)return t;e-=1}else(s===ta||s===sa||s[0]==="["&&!isNaN(Number(s.slice(1))))&&(e+=1)}var i=kt(t);r&&t.remove(),t=i}}function Ju(r){if(!r||r.nodeType!==Si)throw xi(),Es;return r.data}function ha(r){return r===this.v}function Zu(r,e){return r!=r?e==e:r!==e||r!==null&&typeof r=="object"||typeof r=="function"}function eh(r){return!Zu(r,this.v)}let th=!1,Ye=null;function Is(r){Ye=r}function da(r,e=!1,t){Ye={p:Ye,i:!1,c:null,e:null,s:r,x:null,r:se,l:null}}function fa(r){var e=Ye,t=e.e;if(t!==null){e.e=null;for(var s of t)Na(s)}return r!==void 0&&(e.x=r),e.i=!0,Ye=e.p,r??{}}function ga(){return!0}let os=[];function ma(){var r=os;os=[],Mu(r)}function Ls(r){if(os.length===0&&!qs){var e=os;queueMicrotask(()=>{e===os&&ma()})}os.push(r)}function sh(){for(;os.length>0;)ma()}function pa(r){var e=se;if(e===null)return te.f|=Wt,r;if((e.f&Ht)===0&&(e.f&xs)===0)throw r;Yt(r,e)}function Yt(r,e){for(;e!==null;){if((e.f&yr)!==0){if((e.f&Ht)===0)throw r;try{e.b.error(r);return}catch(t){r=t}}e=e.parent}throw r}const ih=-7169;function Ae(r,e){r.f=r.f&ih|e}function Sr(r){(r.f&et)!==0||r.deps===null?Ae(r,Ie):Ae(r,pt)}function ya(r){if(r!==null)for(const e of r)(e.f&be)===0||(e.f&as)===0||(e.f^=as,ya(e.deps))}function va(r,e,t){(r.f&Fe)!==0?e.add(r):(r.f&pt)!==0&&t.add(r),ya(r.deps),Ae(r,Ie)}const qt=new Set;let he=null,ut=null,xr=null,qs=!1,Ar=!1,Rs=null,_i=null;var Ea=0;let rh=1;class Pt{id=rh++;current=new Map;previous=new Map;#e=new Set;#s=new Set;#t=new Map;#r=new Map;#n=null;#i=[];#a=new Set;#o=new Set;#l=new Map;is_fork=!1;#h=!1;#c=new Set;#d(){return this.is_fork||this.#r.size>0}#g(){for(const s of this.#c)for(const i of s.#r.keys()){for(var e=!1,t=i;t.parent!==null;){if(this.#l.has(t)){e=!0;break}t=t.parent}if(!e)return!0}return!1}skip_effect(e){this.#l.has(e)||this.#l.set(e,{d:[],m:[]})}unskip_effect(e){var t=this.#l.get(e);if(t){this.#l.delete(e);for(var s of t.d)Ae(s,Fe),this.schedule(s);for(s of t.m)Ae(s,pt),this.schedule(s)}}#f(){if(Ea++>1e3&&(qt.delete(this),nh()),!this.#d()){for(const o of this.#a)this.#o.delete(o),Ae(o,Fe),this.schedule(o);for(const o of this.#o)Ae(o,pt),this.schedule(o)}const e=this.#i;this.#i=[],this.apply();var t=Rs=[],s=[],i=_i=[];for(const o of e)try{this.#u(o,t,s)}catch(c){throw _a(o),c}if(he=null,i.length>0){var n=Pt.ensure();for(const o of i)n.schedule(o)}if(Rs=null,_i=null,this.#d()||this.#g()){this.#m(s),this.#m(t);for(const[o,c]of this.#l)Aa(o,c)}else{this.#t.size===0&&qt.delete(this),this.#a.clear(),this.#o.clear();for(const o of this.#e)o(this);this.#e.clear(),Ta(s),Ta(t),this.#n?.resolve()}var a=he;if(this.#i.length>0){const o=a??=this;o.#i.push(...this.#i.filter(c=>!o.#i.includes(c)))}a!==null&&(qt.add(a),a.#f()),qt.has(this)||this.#p()}#u(e,t,s){e.f^=Ie;for(var i=e.first;i!==null;){var n=i.f,a=(n&(mt|Vt))!==0,o=a&&(n&Ie)!==0,c=o||(n&yt)!==0||this.#l.has(i);if(!c&&i.fn!==null){a?i.f^=Ie:(n&xs)!==0?t.push(i):Zs(i)&&((n&Kt)!==0&&this.#o.add(i),Ds(i));var l=i.first;if(l!==null){i=l;continue}}for(;i!==null;){var u=i.next;if(u!==null){i=u;break}i=i.parent}}}#m(e){for(var t=0;t<e.length;t+=1)va(e[t],this.#a,this.#o)}capture(e,t,s=!1){t!==Pe&&!this.previous.has(e)&&this.previous.set(e,t),(e.f&Wt)===0&&(this.current.set(e,[e.v,s]),ut?.set(e,e.v))}activate(){he=this}deactivate(){he=null,ut=null}flush(){try{Ar=!0,he=this,this.#f()}finally{Ea=0,xr=null,Rs=null,_i=null,Ar=!1,he=null,ut=null,jt.clear()}}discard(){for(const e of this.#s)e(this);this.#s.clear(),qt.delete(this)}#p(){for(const l of qt){var e=l.id<this.id,t=[];for(const[u,[h,d]]of this.current){if(l.current.has(u)){var s=l.current.get(u)[0];if(e&&h!==s)l.current.set(u,[h,d]);else continue}t.push(u)}var i=[...l.current.keys()].filter(u=>!this.current.has(u));if(i.length===0)e&&l.discard();else if(t.length>0){l.activate();var n=new Set,a=new Map;for(var o of t)Sa(o,i,n,a);if(l.#i.length>0){l.apply();for(var c of l.#i)l.#u(c,[],[]);l.#i=[]}l.deactivate()}}for(const l of qt)l.#c.has(this)&&(l.#c.delete(this),l.#c.size===0&&!l.#d()&&(l.activate(),l.#f()))}increment(e,t){let s=this.#t.get(t)??0;if(this.#t.set(t,s+1),e){let i=this.#r.get(t)??0;this.#r.set(t,i+1)}}decrement(e,t,s){let i=this.#t.get(t)??0;if(i===1?this.#t.delete(t):this.#t.set(t,i-1),e){let n=this.#r.get(t)??0;n===1?this.#r.delete(t):this.#r.set(t,n-1)}this.#h||s||(this.#h=!0,Ls(()=>{this.#h=!1,this.flush()}))}transfer_effects(e,t){for(const s of e)this.#a.add(s);for(const s of t)this.#o.add(s);e.clear(),t.clear()}oncommit(e){this.#e.add(e)}ondiscard(e){this.#s.add(e)}settled(){return(this.#n??=aa()).promise}static ensure(){if(he===null){const e=he=new Pt;Ar||(qt.add(he),qs||Ls(()=>{he===e&&e.flush()}))}return he}apply(){{ut=null;return}}schedule(e){if(xr=e,e.b?.is_pending&&(e.f&(xs|Ei|oa))!==0&&(e.f&Ht)===0){e.b.defer_effect(e);return}for(var t=e;t.parent!==null;){t=t.parent;var s=t.f;if(Rs!==null&&t===se&&(te===null||(te.f&be)===0))return;if((s&(Vt|mt))!==0){if((s&Ie)===0)return;t.f^=Ie}}this.#i.push(t)}}function ls(r){var e=qs;qs=!0;try{for(var t;;){if(sh(),he===null)return t;he.flush()}}finally{qs=e}}function nh(){try{Hu()}catch(r){Yt(r,xr)}}let wt=null;function Ta(r){var e=r.length;if(e!==0){for(var t=0;t<e;){var s=r[t++];if((s.f&(lt|yt))===0&&Zs(s)&&(wt=new Set,Ds(s),s.deps===null&&s.first===null&&s.nodes===null&&s.teardown===null&&s.ac===null&&Ka(s),wt?.size>0)){jt.clear();for(const i of wt){if((i.f&(lt|yt))!==0)continue;const n=[i];let a=i.parent;for(;a!==null;)wt.has(a)&&(wt.delete(a),n.push(a)),a=a.parent;for(let o=n.length-1;o>=0;o--){const c=n[o];(c.f&(lt|yt))===0&&Ds(c)}}wt.clear()}}wt=null}}function Sa(r,e,t,s){if(!t.has(r)&&(t.add(r),r.reactions!==null))for(const i of r.reactions){const n=i.f;(n&be)!==0?Sa(i,e,t,s):(n&(Er|Kt))!==0&&(n&Fe)===0&&xa(i,e,s)&&(Ae(i,Fe),_r(i))}}function xa(r,e,t){const s=t.get(r);if(s!==void 0)return s;if(r.deps!==null)for(const i of r.deps){if(Ts.call(e,i))return!0;if((i.f&be)!==0&&xa(i,e,t))return t.set(i,!0),!0}return t.set(r,!1),!1}function _r(r){he.schedule(r)}function Aa(r,e){if(!((r.f&mt)!==0&&(r.f&Ie)!==0)){(r.f&Fe)!==0?e.d.push(r):(r.f&pt)!==0&&e.m.push(r),Ae(r,Ie);for(var t=r.first;t!==null;)Aa(t,e),t=t.next}}function _a(r){Ae(r,Ie);for(var e=r.first;e!==null;)_a(e),e=e.next}function ah(r){let e=0,t=js(0),s;return()=>{Cr()&&(re(t),Ba(()=>(e===0&&(s=wr(()=>r(()=>Xs(t)))),e+=1,()=>{Ls(()=>{e-=1,e===0&&(s?.(),s=void 0,Xs(t))})})))}}var oh=As|ns;function lh(r,e,t,s){new ch(r,e,t,s)}class ch{parent;is_pending=!1;transform_error;#e;#s=Ee?ne:null;#t;#r;#n;#i=null;#a=null;#o=null;#l=null;#h=0;#c=0;#d=!1;#g=new Set;#f=new Set;#u=null;#m=ah(()=>(this.#u=js(this.#h),()=>{this.#u=null}));constructor(e,t,s,i){this.#e=e,this.#t=t,this.#r=n=>{var a=se;a.b=this,a.f|=yr,s(n)},this.parent=se.b,this.transform_error=i??this.parent?.transform_error??(n=>n),this.#n=Ua(()=>{if(Ee){const n=this.#s;Ai();const a=n.data===sa;if(n.data.startsWith(ia)){const c=JSON.parse(n.data.slice(ia.length));this.#S(c)}else a?this.#x():this.#p()}else this.#E()},oh),Ee&&(this.#e=ne)}#p(){try{this.#i=Ot(()=>this.#r(this.#e))}catch(e){this.error(e)}}#S(e){const t=this.#t.failed;t&&(this.#o=Ot(()=>{t(this.#e,()=>e,()=>()=>{})}))}#x(){const e=this.#t.pending;e&&(this.is_pending=!0,this.#a=Ot(()=>e(this.#e)),Ls(()=>{var t=this.#l=document.createDocumentFragment(),s=vt();t.append(s),this.#i=this.#v(()=>Ot(()=>this.#r(s))),this.#c===0&&(this.#e.before(t),this.#l=null,Js(this.#a,()=>{this.#a=null}),this.#y(he))}))}#E(){try{if(this.is_pending=this.has_pending_snippet(),this.#c=0,this.#h=0,this.#i=Ot(()=>{this.#r(this.#e)}),this.#c>0){var e=this.#l=document.createDocumentFragment();Wa(this.#i,e);const t=this.#t.pending;this.#a=Ot(()=>t(this.#e))}else this.#y(he)}catch(t){this.error(t)}}#y(e){this.is_pending=!1,e.transfer_effects(this.#g,this.#f)}defer_effect(e){va(e,this.#g,this.#f)}is_rendered(){return!this.is_pending&&(!this.parent||this.parent.is_rendered())}has_pending_snippet(){return!!this.#t.pending}#v(e){var t=se,s=te,i=Ye;Tt(this.#n),tt(this.#n),Is(this.#n.ctx);try{return Pt.ensure(),e()}catch(n){return pa(n),null}finally{Tt(t),tt(s),Is(i)}}#T(e,t){if(!this.has_pending_snippet()){this.parent&&this.parent.#T(e,t);return}this.#c+=e,this.#c===0&&(this.#y(t),this.#a&&Js(this.#a,()=>{this.#a=null}),this.#l&&(this.#e.before(this.#l),this.#l=null))}update_pending_count(e,t){this.#T(e,t),this.#h+=e,!(!this.#u||this.#d)&&(this.#d=!0,Ls(()=>{this.#d=!1,this.#u&&Li(this.#u,this.#h)}))}get_effect_pending(){return this.#m(),re(this.#u)}error(e){var t=this.#t.onerror;let s=this.#t.failed;if(!t&&!s)throw e;this.#i&&(Ke(this.#i),this.#i=null),this.#a&&(Ke(this.#a),this.#a=null),this.#o&&(Ke(this.#o),this.#o=null),Ee&&(ct(this.#s),Qu(),ct(ua()));var i=!1,n=!1;const a=()=>{if(i){zu();return}i=!0,n&&Xu(),this.#o!==null&&Js(this.#o,()=>{this.#o=null}),this.#v(()=>{this.#E()})},o=c=>{try{n=!0,t?.(c,a),n=!1}catch(l){Yt(l,this.#n&&this.#n.parent)}s&&(this.#o=this.#v(()=>{try{return Ot(()=>{var l=se;l.b=this,l.f|=yr,s(this.#e,()=>c,()=>a)})}catch(l){return Yt(l,this.#n.parent),null}}))};Ls(()=>{var c;try{c=this.transform_error(e)}catch(l){Yt(l,this.#n&&this.#n.parent);return}c!==null&&typeof c=="object"&&typeof c.then=="function"?c.then(o,l=>Yt(l,this.#n&&this.#n.parent)):o(c)})}}function uh(r,e,t,s){const i=La;var n=r.filter(d=>!d.settled);if(t.length===0&&n.length===0){s(e.map(i));return}var a=se,o=hh(),c=n.length===1?n[0].promise:n.length>1?Promise.all(n.map(d=>d.promise)):null;function l(d){o();try{s(d)}catch(g){(a.f&lt)===0&&Yt(g,a)}Ii()}if(t.length===0){c.then(()=>l(e.map(i)));return}var u=Ia();function h(){Promise.all(t.map(d=>dh(d))).then(d=>l([...e.map(i),...d])).catch(d=>Yt(d,a)).finally(()=>u())}c?c.then(()=>{o(),h(),Ii()}):h()}function hh(){var r=se,e=te,t=Ye,s=he;return function(n=!0){Tt(r),tt(e),Is(t),n&&(r.f&lt)===0&&(s?.activate(),s?.apply())}}function Ii(r=!0){Tt(null),tt(null),Is(null),r&&he?.deactivate()}function Ia(){var r=se,e=r.b,t=he,s=e.is_rendered();return e.update_pending_count(1,t),t.increment(s,r),(i=!1)=>{e.update_pending_count(-1,t),t.decrement(s,r,i)}}function La(r){var e=be|Fe,t=te!==null&&(te.f&be)!==0?te:null;return se!==null&&(se.f|=ns),{ctx:Ye,deps:null,effects:null,equals:ha,f:e,fn:r,reactions:null,rv:0,v:Pe,wv:0,parent:t??se,ac:null}}function dh(r,e,t){let s=se;s===null&&Uu();var i=void 0,n=js(Pe),a=!te,o=new Map;return Ih(()=>{var c=se,l=aa();i=l.promise;try{Promise.resolve(r()).then(l.resolve,l.reject).finally(Ii)}catch(g){l.reject(g),Ii()}var u=he;if(a){if((c.f&Ht)!==0)var h=Ia();if(s.b.is_rendered())o.get(u)?.reject(Ct),o.delete(u);else{for(const g of o.values())g.reject(Ct);o.clear()}o.set(u,l)}const d=(g,f=void 0)=>{if(h){var p=f===Ct;h(p)}if(!(f===Ct||(c.f&lt)!==0)){if(u.activate(),f)n.f|=Wt,Li(n,f);else{(n.f&Wt)!==0&&(n.f^=Wt),Li(n,g);for(const[y,v]of o){if(o.delete(y),y===u)break;v.reject(Ct)}}u.deactivate()}};l.promise.then(d,g=>d(null,g||"unknown"))}),xh(()=>{for(const c of o.values())c.reject(Ct)}),new Promise(c=>{function l(u){function h(){u===i?c(n):l(i)}u.then(h,h)}l(i)})}function fh(r){var e=r.effects;if(e!==null){r.effects=null;for(var t=0;t<e.length;t+=1)Ke(e[t])}}function gh(r){for(var e=r.parent;e!==null;){if((e.f&be)===0)return(e.f&lt)===0?e:null;e=e.parent}return null}function Ir(r){var e,t=se;Tt(gh(r));try{r.f&=~as,fh(r),e=Qa(r)}finally{Tt(t)}return e}function Ra(r){var e=r.v,t=Ir(r);if(!r.equals(t)&&(r.wv=Xa(),(!he?.is_fork||r.deps===null)&&(r.v=t,he?.capture(r,e,!0),r.deps===null))){Ae(r,Ie);return}Xt||(ut!==null?(Cr()||he?.is_fork)&&ut.set(r,t):Sr(r))}function mh(r){if(r.effects!==null)for(const e of r.effects)(e.teardown||e.ac)&&(e.teardown?.(),e.ac?.abort(Ct),e.teardown=Ou,e.ac=null,ei(e,0),Pr(e))}function ba(r){if(r.effects!==null)for(const e of r.effects)e.teardown&&Ds(e)}let Lr=new Set;const jt=new Map;let Da=!1;function js(r,e){var t={f:0,v:r,reactions:null,equals:ha,rv:0,wv:0};return t}function Ge(r,e){const t=js(r);return Dh(t),t}function ph(r,e=!1,t=!0){const s=js(r);return e||(s.equals=eh),s}function de(r,e,t=!1){te!==null&&(!ht||(te.f&ca)!==0)&&ga()&&(te.f&(be|Kt|Er|ca))!==0&&(st===null||!Ts.call(st,r))&&ju();let s=t?zs(e):e;return Li(r,s,_i)}function Li(r,e,t=null){if(!r.equals(e)){var s=r.v;Xt?jt.set(r,e):jt.set(r,s),r.v=e;var i=Pt.ensure();if(i.capture(r,s),(r.f&be)!==0){const n=r;(r.f&Fe)!==0&&Ir(n),ut===null&&Sr(n)}r.wv=Xa(),Ca(r,Fe,t),se!==null&&(se.f&Ie)!==0&&(se.f&(mt|Vt))===0&&(it===null?Ch([r]):it.push(r)),!i.is_fork&&Lr.size>0&&!Da&&yh()}return e}function yh(){Da=!1;for(const r of Lr)(r.f&Ie)!==0&&Ae(r,pt),Zs(r)&&Ds(r);Lr.clear()}function Xs(r){de(r,r.v+1)}function Ca(r,e,t){var s=r.reactions;if(s!==null)for(var i=s.length,n=0;n<i;n++){var a=s[n],o=a.f,c=(o&Fe)===0;if(c&&Ae(a,e),(o&be)!==0){var l=a;ut?.delete(l),(o&as)===0&&(o&et&&(a.f|=as),Ca(l,pt,t))}else if(c){var u=a;(o&Kt)!==0&&wt!==null&&wt.add(u),t!==null?t.push(u):_r(u)}}}function zs(r){if(typeof r!="object"||r===null||Tr in r)return r;const e=ku(r);if(e!==Pu&&e!==wu)return r;var t=new Map,s=bu(r),i=Ge(0),n=hs,a=o=>{if(hs===n)return o();var c=te,l=hs;tt(null),ja(n);var u=o();return tt(c),ja(l),u};return s&&t.set("length",Ge(r.length)),new Proxy(r,{defineProperty(o,c,l){(!("value"in l)||l.configurable===!1||l.enumerable===!1||l.writable===!1)&&Yu();var u=t.get(c);return u===void 0?a(()=>{var h=Ge(l.value);return t.set(c,h),h}):de(u,l.value,!0),!0},deleteProperty(o,c){var l=t.get(c);if(l===void 0){if(c in o){const u=a(()=>Ge(Pe));t.set(c,u),Xs(i)}}else de(l,Pe),Xs(i);return!0},get(o,c,l){if(c===Tr)return r;var u=t.get(c),h=c in o;if(u===void 0&&(!h||Ss(o,c)?.writable)&&(u=a(()=>{var g=zs(h?o[c]:Pe),f=Ge(g);return f}),t.set(c,u)),u!==void 0){var d=re(u);return d===Pe?void 0:d}return Reflect.get(o,c,l)},getOwnPropertyDescriptor(o,c){var l=Reflect.getOwnPropertyDescriptor(o,c);if(l&&"value"in l){var u=t.get(c);u&&(l.value=re(u))}else if(l===void 0){var h=t.get(c),d=h?.v;if(h!==void 0&&d!==Pe)return{enumerable:!0,configurable:!0,value:d,writable:!0}}return l},has(o,c){if(c===Tr)return!0;var l=t.get(c),u=l!==void 0&&l.v!==Pe||Reflect.has(o,c);if(l!==void 0||se!==null&&(!u||Ss(o,c)?.writable)){l===void 0&&(l=a(()=>{var d=u?zs(o[c]):Pe,g=Ge(d);return g}),t.set(c,l));var h=re(l);if(h===Pe)return!1}return u},set(o,c,l,u){var h=t.get(c),d=c in o;if(s&&c==="length")for(var g=l;g<h.v;g+=1){var f=t.get(g+"");f!==void 0?de(f,Pe):g in o&&(f=a(()=>Ge(Pe)),t.set(g+"",f))}if(h===void 0)(!d||Ss(o,c)?.writable)&&(h=a(()=>Ge(void 0)),de(h,zs(l)),t.set(c,h));else{d=h.v!==Pe;var p=a(()=>zs(l));de(h,p)}var y=Reflect.getOwnPropertyDescriptor(o,c);if(y?.set&&y.set.call(u,l),!d){if(s&&typeof c=="string"){var v=t.get("length"),E=Number(c);Number.isInteger(E)&&E>=v.v&&de(v,E+1)}Xs(i)}return!0},ownKeys(o){re(i);var c=Reflect.ownKeys(o).filter(h=>{var d=t.get(h);return d===void 0||d.v!==Pe});for(var[l,u]of t)u.v!==Pe&&!(l in o)&&c.push(l);return c},setPrototypeOf(){qu()}})}var Pa,wa,ka,Oa;function Rr(){if(Pa===void 0){Pa=window,wa=/Firefox/.test(navigator.userAgent);var r=Element.prototype,e=Node.prototype,t=Text.prototype;ka=Ss(e,"firstChild").get,Oa=Ss(e,"nextSibling").get,na(r)&&(r.__click=void 0,r.__className=void 0,r.__attributes=null,r.__style=void 0,r.__e=void 0),na(t)&&(t.__t=void 0)}}function vt(r=""){return document.createTextNode(r)}function bs(r){return ka.call(r)}function kt(r){return Oa.call(r)}function ge(r,e){if(!Ee)return bs(r);var t=bs(ne);return t===null&&(t=ne.appendChild(vt())),ct(t),t}function Qs(r,e=!1){if(!Ee){var t=bs(r);return t instanceof Comment&&t.data===""?kt(t):t}if(e){if(ne?.nodeType!==Ti){var s=vt();return ne?.before(s),ct(s),s}Dr(ne)}return ne}function Ri(r,e=1,t=!1){let s=Ee?ne:r;for(var i;e--;)i=s,s=kt(s);if(!Ee)return s;if(t){if(s?.nodeType!==Ti){var n=vt();return s===null?i?.after(n):s.before(n),ct(n),n}Dr(s)}return ct(s),s}function vh(r){r.textContent=""}function Eh(){return!1}function br(r,e,t){return document.createElementNS(Lu,r,void 0)}function Dr(r){if(r.nodeValue.length<65536)return;let e=r.nextSibling;for(;e!==null&&e.nodeType===Ti;)e.remove(),r.nodeValue+=e.nodeValue,e=r.nextSibling}function Ma(r){var e=te,t=se;tt(null),Tt(null);try{return r()}finally{tt(e),Tt(t)}}function Th(r){se===null&&(te===null&&Vu(),Ku()),Xt&&Gu()}function Sh(r,e){var t=e.last;t===null?e.last=e.first=r:(t.next=r,r.prev=t,e.last=r)}function Et(r,e){var t=se;t!==null&&(t.f&yt)!==0&&(r|=yt);var s={ctx:Ye,deps:null,nodes:null,f:r|Fe|et,first:null,fn:e,last:null,next:null,parent:t,b:t&&t.b,prev:null,teardown:null,wv:0,ac:null},i=s;if((r&xs)!==0)Rs!==null?Rs.push(s):Pt.ensure().schedule(s);else if(e!==null){try{Ds(s)}catch(a){throw Ke(s),a}i.deps===null&&i.teardown===null&&i.nodes===null&&i.first===i.last&&(i.f&ns)===0&&(i=i.first,(r&Kt)!==0&&(r&As)!==0&&i!==null&&(i.f|=As))}if(i!==null&&(i.parent=t,t!==null&&Sh(i,t),te!==null&&(te.f&be)!==0&&(r&Vt)===0)){var n=te;(n.effects??=[]).push(i)}return s}function Cr(){return te!==null&&!ht}function xh(r){const e=Et(Ei,null);return Ae(e,Ie),e.teardown=r,e}function Fa(r){Th();var e=se.f,t=!te&&(e&mt)!==0&&(e&Ht)===0;if(t){var s=Ye;(s.e??=[]).push(r)}else return Na(r)}function Na(r){return Et(xs|Nu,r)}function Ah(r){Pt.ensure();const e=Et(Vt|ns,r);return()=>{Ke(e)}}function _h(r){Pt.ensure();const e=Et(Vt|ns,r);return(t={})=>new Promise(s=>{t.outro?Js(e,()=>{Ke(e),s(void 0)}):(Ke(e),s(void 0))})}function $a(r){return Et(xs,r)}function Ih(r){return Et(Er|ns,r)}function Ba(r,e=0){return Et(Ei|e,r)}function cs(r,e=[],t=[],s=[]){uh(s,e,t,i=>{Et(Ei,()=>r(...i.map(re)))})}function Ua(r,e=0){var t=Et(Kt|e,r);return t}function Ot(r){return Et(mt|ns,r)}function Ga(r){var e=r.teardown;if(e!==null){const t=Xt,s=te;Ya(!0),tt(null);try{e.call(null)}finally{Ya(t),tt(s)}}}function Pr(r,e=!1){var t=r.first;for(r.first=r.last=null;t!==null;){const i=t.ac;i!==null&&Ma(()=>{i.abort(Ct)});var s=t.next;(t.f&Vt)!==0?t.parent=null:Ke(t,e),t=s}}function Lh(r){for(var e=r.first;e!==null;){var t=e.next;(e.f&mt)===0&&Ke(e),e=t}}function Ke(r,e=!0){var t=!1;(e||(r.f&Fu)!==0)&&r.nodes!==null&&r.nodes.end!==null&&(Rh(r.nodes.start,r.nodes.end),t=!0),Ae(r,la),Pr(r,e&&!t),ei(r,0);var s=r.nodes&&r.nodes.t;if(s!==null)for(const n of s)n.stop();Ga(r),r.f^=la,r.f|=lt;var i=r.parent;i!==null&&i.first!==null&&Ka(r),r.next=r.prev=r.teardown=r.ctx=r.deps=r.fn=r.nodes=r.ac=r.b=null}function Rh(r,e){for(;r!==null;){var t=r===e?null:kt(r);r.remove(),r=t}}function Ka(r){var e=r.parent,t=r.prev,s=r.next;t!==null&&(t.next=s),s!==null&&(s.prev=t),e!==null&&(e.first===r&&(e.first=s),e.last===r&&(e.last=t))}function Js(r,e,t=!0){var s=[];Va(r,s,!0);var i=()=>{t&&Ke(r),e&&e()},n=s.length;if(n>0){var a=()=>--n||i();for(var o of s)o.out(a)}else i()}function Va(r,e,t){if((r.f&yt)===0){r.f^=yt;var s=r.nodes&&r.nodes.t;if(s!==null)for(const o of s)(o.is_global||t)&&e.push(o);for(var i=r.first;i!==null;){var n=i.next,a=(i.f&As)!==0||(i.f&mt)!==0&&(r.f&Kt)!==0;Va(i,e,a?t:!1),i=n}}}function bh(r){Ha(r,!0)}function Ha(r,e){if((r.f&yt)!==0){r.f^=yt,(r.f&Ie)===0&&(Ae(r,Fe),Pt.ensure().schedule(r));for(var t=r.first;t!==null;){var s=t.next,i=(t.f&As)!==0||(t.f&mt)!==0;Ha(t,i?e:!1),t=s}var n=r.nodes&&r.nodes.t;if(n!==null)for(const a of n)(a.is_global||e)&&a.in()}}function Wa(r,e){if(r.nodes)for(var t=r.nodes.start,s=r.nodes.end;t!==null;){var i=t===s?null:kt(t);e.append(t),t=i}}let bi=!1,Xt=!1;function Ya(r){Xt=r}let te=null,ht=!1;function tt(r){te=r}let se=null;function Tt(r){se=r}let st=null;function Dh(r){te!==null&&(st===null?st=[r]:st.push(r))}let Ve=null,qe=0,it=null;function Ch(r){it=r}let qa=1,us=0,hs=us;function ja(r){hs=r}function Xa(){return++qa}function Zs(r){var e=r.f;if((e&Fe)!==0)return!0;if(e&be&&(r.f&=~as),(e&pt)!==0){for(var t=r.deps,s=t.length,i=0;i<s;i++){var n=t[i];if(Zs(n)&&Ra(n),n.wv>r.wv)return!0}(e&et)!==0&&ut===null&&Ae(r,Ie)}return!1}function za(r,e,t=!0){var s=r.reactions;if(s!==null&&!(st!==null&&Ts.call(st,r)))for(var i=0;i<s.length;i++){var n=s[i];(n.f&be)!==0?za(n,e,!1):e===n&&(t?Ae(n,Fe):(n.f&Ie)!==0&&Ae(n,pt),_r(n))}}function Qa(r){var e=Ve,t=qe,s=it,i=te,n=st,a=Ye,o=ht,c=hs,l=r.f;Ve=null,qe=0,it=null,te=(l&(mt|Vt))===0?r:null,st=null,Is(r.ctx),ht=!1,hs=++us,r.ac!==null&&(Ma(()=>{r.ac.abort(Ct)}),r.ac=null);try{r.f|=vr;var u=r.fn,h=u();r.f|=Ht;var d=r.deps,g=he?.is_fork;if(Ve!==null){var f;if(g||ei(r,qe),d!==null&&qe>0)for(d.length=qe+Ve.length,f=0;f<Ve.length;f++)d[qe+f]=Ve[f];else r.deps=d=Ve;if(Cr()&&(r.f&et)!==0)for(f=qe;f<d.length;f++)(d[f].reactions??=[]).push(r)}else!g&&d!==null&&qe<d.length&&(ei(r,qe),d.length=qe);if(ga()&&it!==null&&!ht&&d!==null&&(r.f&(be|pt|Fe))===0)for(f=0;f<it.length;f++)za(it[f],r);if(i!==null&&i!==r){if(us++,i.deps!==null)for(let p=0;p<t;p+=1)i.deps[p].rv=us;if(e!==null)for(const p of e)p.rv=us;it!==null&&(s===null?s=it:s.push(...it))}return(r.f&Wt)!==0&&(r.f^=Wt),h}catch(p){return pa(p)}finally{r.f^=vr,Ve=e,qe=t,it=s,te=i,st=n,Is(a),ht=o,hs=c}}function Ph(r,e){let t=e.reactions;if(t!==null){var s=Du.call(t,r);if(s!==-1){var i=t.length-1;i===0?t=e.reactions=null:(t[s]=t[i],t.pop())}}if(t===null&&(e.f&be)!==0&&(Ve===null||!Ts.call(Ve,e))){var n=e;(n.f&et)!==0&&(n.f^=et,n.f&=~as),Sr(n),mh(n),ei(n,0)}}function ei(r,e){var t=r.deps;if(t!==null)for(var s=e;s<t.length;s++)Ph(r,t[s])}function Ds(r){var e=r.f;if((e&lt)===0){Ae(r,Ie);var t=se,s=bi;se=r,bi=!0;try{(e&(Kt|oa))!==0?Lh(r):Pr(r),Ga(r);var i=Qa(r);r.teardown=typeof i=="function"?i:null,r.wv=qa;var n;Ru&&th&&(r.f&Fe)!==0&&r.deps}finally{bi=s,se=t}}}function re(r){var e=r.f,t=(e&be)!==0;if(te!==null&&!ht){var s=se!==null&&(se.f&lt)!==0;if(!s&&(st===null||!Ts.call(st,r))){var i=te.deps;if((te.f&vr)!==0)r.rv<us&&(r.rv=us,Ve===null&&i!==null&&i[qe]===r?qe++:Ve===null?Ve=[r]:Ve.push(r));else{(te.deps??=[]).push(r);var n=r.reactions;n===null?r.reactions=[te]:Ts.call(n,te)||n.push(te)}}}if(Xt&&jt.has(r))return jt.get(r);if(t){var a=r;if(Xt){var o=a.v;return((a.f&Ie)===0&&a.reactions!==null||Za(a))&&(o=Ir(a)),jt.set(a,o),o}var c=(a.f&et)===0&&!ht&&te!==null&&(bi||(te.f&et)!==0),l=(a.f&Ht)===0;Zs(a)&&(c&&(a.f|=et),Ra(a)),c&&!l&&(ba(a),Ja(a))}if(ut?.has(r))return ut.get(r);if((r.f&Wt)!==0)throw r.v;return r.v}function Ja(r){if(r.f|=et,r.deps!==null)for(const e of r.deps)(e.reactions??=[]).push(r),(e.f&be)!==0&&(e.f&et)===0&&(ba(e),Ja(e))}function Za(r){if(r.v===Pe)return!0;if(r.deps===null)return!1;for(const e of r.deps)if(jt.has(e)||(e.f&be)!==0&&Za(e))return!0;return!1}function wr(r){var e=ht;try{return ht=!0,r()}finally{ht=e}}const Di=Symbol("events"),wh=new Set,eo=new Set;let to=null;function so(r){var e=this,t=e.ownerDocument,s=r.type,i=r.composedPath?.()||[],n=i[0]||r.target;to=r;var a=0,o=to===r&&r[Di];if(o){var c=i.indexOf(o);if(c!==-1&&(e===document||e===window)){r[Di]=e;return}var l=i.indexOf(e);if(l===-1)return;c<=l&&(a=c)}if(n=i[a]||r.target,n!==e){vi(r,"currentTarget",{configurable:!0,get(){return n||t}});var u=te,h=se;tt(null),Tt(null);try{for(var d,g=[];n!==null;){var f=n.assignedSlot||n.parentNode||n.host||null;try{var p=n[Di]?.[s];p!=null&&(!n.disabled||r.target===n)&&p.call(n,r)}catch(y){d?g.push(y):d=y}if(r.cancelBubble||f===e||f===null)break;n=f}if(d){for(let y of g)queueMicrotask(()=>{throw y});throw d}}finally{r[Di]=e,delete r.currentTarget,tt(u),Tt(h)}}}const kh=globalThis?.window?.trustedTypes&&globalThis.window.trustedTypes.createPolicy("svelte-trusted-html",{createHTML:r=>r});function Oh(r){return kh?.createHTML(r)??r}function Mh(r){var e=br("template");return e.innerHTML=Oh(r.replaceAll("<!>","<!---->")),e.content}function zt(r,e){var t=se;t.nodes===null&&(t.nodes={start:r,end:e,a:null,t:null})}function Qt(r,e){var t=(e&_u)!==0,s=(e&Iu)!==0,i,n=!r.startsWith("<!>");return()=>{if(Ee)return zt(ne,null),ne;i===void 0&&(i=Mh(n?r:"<!>"+r),t||(i=bs(i)));var a=s||wa?document.importNode(i,!0):i.cloneNode(!0);if(t){var o=bs(a),c=a.lastChild;zt(o,c)}else zt(a,a);return a}}function Cs(r=""){if(!Ee){var e=vt(r+"");return zt(e,e),e}var t=ne;return t.nodeType!==Ti?(t.before(t=vt()),ct(t)):Dr(t),zt(t,t),t}function kr(){if(Ee)return zt(ne,null),ne;var r=document.createDocumentFragment(),e=document.createComment(""),t=vt();return r.append(e,t),zt(e,t),r}function De(r,e){if(Ee){var t=se;((t.f&Ht)===0||t.nodes.end===null)&&(t.nodes.end=ne),Ai();return}r!==null&&r.before(e)}const Fh=["touchstart","touchmove"];function Nh(r){return Fh.includes(r)}function Ps(r,e){var t=e==null?"":typeof e=="object"?`${e}`:e;t!==(r.__t??=r.nodeValue)&&(r.__t=t,r.nodeValue=`${t}`)}function io(r,e){return ro(r,e)}function $h(r,e){Rr(),e.intro=e.intro??!1;const t=e.target,s=Ee,i=ne;try{for(var n=bs(t);n&&(n.nodeType!==Si||n.data!==ta);)n=kt(n);if(!n)throw Es;_s(!0),ct(n);const a=ro(r,{...e,anchor:n});return _s(!1),a}catch(a){if(a instanceof Error&&a.message.split(`
2
- `).some(o=>o.startsWith("https://svelte.dev/e/")))throw a;return a!==Es&&console.warn("Failed to hydrate: ",a),e.recover===!1&&Wu(),Rr(),vh(t),_s(!1),io(r,e)}finally{_s(s),ct(i)}}const Ci=new Map;function ro(r,{target:e,anchor:t,props:s={},events:i,context:n,intro:a=!0,transformError:o}){Rr();var c=void 0,l=_h(()=>{var u=t??e.appendChild(vt());lh(u,{pending:()=>{}},g=>{da({});var f=Ye;if(n&&(f.c=n),i&&(s.$$events=i),Ee&&zt(g,null),c=r(g,s)||{},Ee&&(se.nodes.end=ne,ne===null||ne.nodeType!==Si||ne.data!==ra))throw xi(),Es;fa()},o);var h=new Set,d=g=>{for(var f=0;f<g.length;f++){var p=g[f];if(!h.has(p)){h.add(p);var y=Nh(p);for(const T of[e,document]){var v=Ci.get(T);v===void 0&&(v=new Map,Ci.set(T,v));var E=v.get(p);E===void 0?(T.addEventListener(p,so,{passive:y}),v.set(p,1)):v.set(p,E+1)}}}};return d(Cu(wh)),eo.add(d),()=>{for(var g of h)for(const y of[e,document]){var f=Ci.get(y),p=f.get(g);--p==0?(y.removeEventListener(g,so),f.delete(g),f.size===0&&Ci.delete(y)):f.set(g,p)}eo.delete(d),u!==t&&u.parentNode?.removeChild(u)}});return Or.set(c,l),c}let Or=new WeakMap;function Bh(r,e){const t=Or.get(r);return t?(Or.delete(r),t(e)):Promise.resolve()}class Uh{anchor;#e=new Map;#s=new Map;#t=new Map;#r=new Set;#n=!0;constructor(e,t=!0){this.anchor=e,this.#n=t}#i=e=>{if(this.#e.has(e)){var t=this.#e.get(e),s=this.#s.get(t);if(s)bh(s),this.#r.delete(t);else{var i=this.#t.get(t);i&&(this.#s.set(t,i.effect),this.#t.delete(t),i.fragment.lastChild.remove(),this.anchor.before(i.fragment),s=i.effect)}for(const[n,a]of this.#e){if(this.#e.delete(n),n===e)break;const o=this.#t.get(a);o&&(Ke(o.effect),this.#t.delete(a))}for(const[n,a]of this.#s){if(n===t||this.#r.has(n))continue;const o=()=>{if(Array.from(this.#e.values()).includes(n)){var l=document.createDocumentFragment();Wa(a,l),l.append(vt()),this.#t.set(n,{effect:a,fragment:l})}else Ke(a);this.#r.delete(n),this.#s.delete(n)};this.#n||!s?(this.#r.add(n),Js(a,o,!1)):o()}}};#a=e=>{this.#e.delete(e);const t=Array.from(this.#e.values());for(const[s,i]of this.#t)t.includes(s)||(Ke(i.effect),this.#t.delete(s))};ensure(e,t){var s=he,i=Eh();if(t&&!this.#s.has(e)&&!this.#t.has(e))if(i){var n=document.createDocumentFragment(),a=vt();n.append(a),this.#t.set(e,{effect:Ot(()=>t(a)),fragment:n})}else this.#s.set(e,Ot(()=>t(this.anchor)));if(this.#e.set(s,e),i){for(const[o,c]of this.#s)o===e?s.unskip_effect(c):s.skip_effect(c);for(const[o,c]of this.#t)o===e?s.unskip_effect(c.effect):s.skip_effect(c.effect);s.oncommit(this.#i),s.ondiscard(this.#a)}else Ee&&(this.anchor=ne),this.#i(s)}}function Gh(r){Ye===null&&Bu(),Fa(()=>{const e=wr(r);if(typeof e=="function")return e})}function Mr(r,e,t=!1){var s;Ee&&(s=ne,Ai());var i=new Uh(r),n=t?As:0;function a(o,c){if(Ee){var l=Ju(s);if(o!==parseInt(l.substring(1))){var u=ua();ct(u),i.anchor=u,_s(!1),i.ensure(o,c),_s(!0);return}}i.ensure(o,c)}Ua(()=>{var o=!1;e((c,l=0)=>{o=!0,a(l,c)}),o||a(-1,null)},n)}function Mt(r,e,t,s,i){Ee&&Ai();var n=e.$$slots?.[t],a=!1;n===!0&&(n=e[t==="default"?"children":t],a=!0),n===void 0?i!==null&&i(r):n(r,a?()=>s:s)}function Kh(r,e){$a(()=>{var t=r.getRootNode(),s=t.host?t:t.head??t.ownerDocument.head;if(!s.querySelector("#"+e.hash)){const i=br("style");i.id=e.hash,i.textContent=e.code,s.appendChild(i)}})}function Vh(r,e,t){$a(()=>{var s=wr(()=>e(r,t?.())||{});if(s?.destroy)return()=>s.destroy()})}function ws(r,e,t,s){var i=s,n=!0,a=()=>(n&&(n=!1,i=s),i),o;o=r[e],o===void 0&&s!==void 0&&(o=a());var c;c=()=>{var d=r[e];return d===void 0?a():(n=!0,d)};var l=!1,u=La(()=>(l=!1,c())),h=se;return(function(d,g){if(arguments.length>0){const f=g?re(u):d;return de(u,f),l=!0,i!==void 0&&(i=f),d}return Xt&&l||(h.f&lt)!==0?u.v:re(u)})}function Hh(r){return new Wh(r)}class Wh{#e;#s;constructor(e){var t=new Map,s=(n,a)=>{var o=ph(a,!1,!1);return t.set(n,o),o};const i=new Proxy({...e.props||{},$$events:{}},{get(n,a){return re(t.get(a)??s(a,Reflect.get(n,a)))},has(n,a){return a===$u?!0:(re(t.get(a)??s(a,Reflect.get(n,a))),Reflect.has(n,a))},set(n,a,o){return de(t.get(a)??s(a,o),o),Reflect.set(n,a,o)}});this.#s=(e.hydrate?$h:io)(e.component,{target:e.target,anchor:e.anchor,props:i,context:e.context,intro:e.intro??!1,recover:e.recover,transformError:e.transformError}),(!e?.props?.$$host||e.sync===!1)&&ls(),this.#e=i.$$events;for(const n of Object.keys(this.#s))n==="$set"||n==="$destroy"||n==="$on"||vi(this,n,{get(){return this.#s[n]},set(a){this.#s[n]=a},enumerable:!0});this.#s.$set=n=>{Object.assign(i,n)},this.#s.$destroy=()=>{Bh(this.#s)}}$set(e){this.#s.$set(e)}$on(e,t){this.#e[e]=this.#e[e]||[];const s=(...i)=>t.call(this,...i);return this.#e[e].push(s),()=>{this.#e[e]=this.#e[e].filter(i=>i!==s)}}$destroy(){this.#s.$destroy()}}let no;typeof HTMLElement=="function"&&(no=class extends HTMLElement{$$ctor;$$s;$$c;$$cn=!1;$$d={};$$r=!1;$$p_d={};$$l={};$$l_u=new Map;$$me;$$shadowRoot=null;constructor(r,e,t){super(),this.$$ctor=r,this.$$s=e,t&&(this.$$shadowRoot=this.attachShadow(t))}addEventListener(r,e,t){if(this.$$l[r]=this.$$l[r]||[],this.$$l[r].push(e),this.$$c){const s=this.$$c.$on(r,e);this.$$l_u.set(e,s)}super.addEventListener(r,e,t)}removeEventListener(r,e,t){if(super.removeEventListener(r,e,t),this.$$c){const s=this.$$l_u.get(e);s&&(s(),this.$$l_u.delete(e))}}async connectedCallback(){if(this.$$cn=!0,!this.$$c){let r=function(s){return i=>{const n=br("slot");s!=="default"&&(n.name=s),De(i,n)}};if(await Promise.resolve(),!this.$$cn||this.$$c)return;const e={},t=Yh(this);for(const s of this.$$s)s in t&&(s==="default"&&!this.$$d.children?(this.$$d.children=r(s),e.default=!0):e[s]=r(s));for(const s of this.attributes){const i=this.$$g_p(s.name);i in this.$$d||(this.$$d[i]=Pi(i,s.value,this.$$p_d,"toProp"))}for(const s in this.$$p_d)!(s in this.$$d)&&this[s]!==void 0&&(this.$$d[s]=this[s],delete this[s]);this.$$c=Hh({component:this.$$ctor,target:this.$$shadowRoot||this,props:{...this.$$d,$$slots:e,$$host:this}}),this.$$me=Ah(()=>{Ba(()=>{this.$$r=!0;for(const s of yi(this.$$c)){if(!this.$$p_d[s]?.reflect)continue;this.$$d[s]=this.$$c[s];const i=Pi(s,this.$$d[s],this.$$p_d,"toAttribute");i==null?this.removeAttribute(this.$$p_d[s].attribute||s):this.setAttribute(this.$$p_d[s].attribute||s,i)}this.$$r=!1})});for(const s in this.$$l)for(const i of this.$$l[s]){const n=this.$$c.$on(s,i);this.$$l_u.set(i,n)}this.$$l={}}}attributeChangedCallback(r,e,t){this.$$r||(r=this.$$g_p(r),this.$$d[r]=Pi(r,t,this.$$p_d,"toProp"),this.$$c?.$set({[r]:this.$$d[r]}))}disconnectedCallback(){this.$$cn=!1,Promise.resolve().then(()=>{!this.$$cn&&this.$$c&&(this.$$c.$destroy(),this.$$me(),this.$$c=void 0)})}$$g_p(r){return yi(this.$$p_d).find(e=>this.$$p_d[e].attribute===r||!this.$$p_d[e].attribute&&e.toLowerCase()===r)||r}});function Pi(r,e,t,s){const i=t[r]?.type;if(e=i==="Boolean"&&typeof e!="boolean"?e!=null:e,!s||!t[r])return e;if(s==="toAttribute")switch(i){case"Object":case"Array":return e==null?null:JSON.stringify(e);case"Boolean":return e?"":null;case"Number":return e??null;default:return e}else switch(i){case"Object":case"Array":return e&&JSON.parse(e);case"Boolean":return e;case"Number":return e!=null?+e:e;default:return e}}function Yh(r){const e={};return r.childNodes.forEach(t=>{e[t.slot||"default"]=!0}),e}function qh(r,e,t,s,i,n){let a=class extends no{constructor(){super(r,t,i),this.$$p_d=e}static get observedAttributes(){return yi(e).map(o=>(e[o].attribute||o).toLowerCase())}};return yi(e).forEach(o=>{vi(a.prototype,o,{get(){return this.$$c&&o in this.$$c?this.$$c[o]:this.$$d[o]},set(c){c=Pi(o,c,e),this.$$d[o]=c;var l=this.$$c;if(l){var u=Ss(l,o)?.get;u?l[o]=c:l.$set({[o]:c})}}})}),s.forEach(o=>{vi(a.prototype,o,{get(){return this.$$c?.[o]}})}),r.element=a,a}const $=Number.isFinite||function(r){return typeof r=="number"&&isFinite(r)},jh=Number.isSafeInteger||function(r){return typeof r=="number"&&Math.abs(r)<=Xh},Xh=Number.MAX_SAFE_INTEGER||9007199254740991;let H=(function(r){return r.NETWORK_ERROR="networkError",r.MEDIA_ERROR="mediaError",r.KEY_SYSTEM_ERROR="keySystemError",r.MUX_ERROR="muxError",r.OTHER_ERROR="otherError",r})({}),R=(function(r){return r.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",r.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",r.KEY_SYSTEM_NO_SESSION="keySystemNoSession",r.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",r.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",r.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",r.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",r.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",r.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",r.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",r.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",r.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",r.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",r.MANIFEST_LOAD_ERROR="manifestLoadError",r.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",r.MANIFEST_PARSING_ERROR="manifestParsingError",r.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",r.LEVEL_EMPTY_ERROR="levelEmptyError",r.LEVEL_LOAD_ERROR="levelLoadError",r.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",r.LEVEL_PARSING_ERROR="levelParsingError",r.LEVEL_SWITCH_ERROR="levelSwitchError",r.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",r.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",r.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",r.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",r.FRAG_LOAD_ERROR="fragLoadError",r.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",r.FRAG_DECRYPT_ERROR="fragDecryptError",r.FRAG_PARSING_ERROR="fragParsingError",r.FRAG_GAP="fragGap",r.REMUX_ALLOC_ERROR="remuxAllocError",r.KEY_LOAD_ERROR="keyLoadError",r.KEY_LOAD_TIMEOUT="keyLoadTimeOut",r.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",r.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",r.BUFFER_APPEND_ERROR="bufferAppendError",r.BUFFER_APPENDING_ERROR="bufferAppendingError",r.BUFFER_STALLED_ERROR="bufferStalledError",r.BUFFER_FULL_ERROR="bufferFullError",r.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",r.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",r.ASSET_LIST_LOAD_ERROR="assetListLoadError",r.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",r.ASSET_LIST_PARSING_ERROR="assetListParsingError",r.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",r.INTERNAL_EXCEPTION="internalException",r.INTERNAL_ABORTED="aborted",r.ATTACH_MEDIA_ERROR="attachMediaError",r.UNKNOWN="unknown",r})({}),m=(function(r){return r.MEDIA_ATTACHING="hlsMediaAttaching",r.MEDIA_ATTACHED="hlsMediaAttached",r.MEDIA_DETACHING="hlsMediaDetaching",r.MEDIA_DETACHED="hlsMediaDetached",r.MEDIA_ENDED="hlsMediaEnded",r.STALL_RESOLVED="hlsStallResolved",r.BUFFER_RESET="hlsBufferReset",r.BUFFER_CODECS="hlsBufferCodecs",r.BUFFER_CREATED="hlsBufferCreated",r.BUFFER_APPENDING="hlsBufferAppending",r.BUFFER_APPENDED="hlsBufferAppended",r.BUFFER_EOS="hlsBufferEos",r.BUFFERED_TO_END="hlsBufferedToEnd",r.BUFFER_FLUSHING="hlsBufferFlushing",r.BUFFER_FLUSHED="hlsBufferFlushed",r.MANIFEST_LOADING="hlsManifestLoading",r.MANIFEST_LOADED="hlsManifestLoaded",r.MANIFEST_PARSED="hlsManifestParsed",r.LEVEL_SWITCHING="hlsLevelSwitching",r.LEVEL_SWITCHED="hlsLevelSwitched",r.LEVEL_LOADING="hlsLevelLoading",r.LEVEL_LOADED="hlsLevelLoaded",r.LEVEL_UPDATED="hlsLevelUpdated",r.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",r.LEVELS_UPDATED="hlsLevelsUpdated",r.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",r.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",r.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",r.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",r.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",r.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",r.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",r.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",r.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",r.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",r.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",r.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",r.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",r.CUES_PARSED="hlsCuesParsed",r.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",r.INIT_PTS_FOUND="hlsInitPtsFound",r.FRAG_LOADING="hlsFragLoading",r.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",r.FRAG_LOADED="hlsFragLoaded",r.FRAG_DECRYPTED="hlsFragDecrypted",r.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",r.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",r.FRAG_PARSING_METADATA="hlsFragParsingMetadata",r.FRAG_PARSED="hlsFragParsed",r.FRAG_BUFFERED="hlsFragBuffered",r.FRAG_CHANGED="hlsFragChanged",r.FPS_DROP="hlsFpsDrop",r.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",r.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",r.ERROR="hlsError",r.DESTROYING="hlsDestroying",r.KEY_LOADING="hlsKeyLoading",r.KEY_LOADED="hlsKeyLoaded",r.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",r.BACK_BUFFER_REACHED="hlsBackBufferReached",r.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",r.ASSET_LIST_LOADING="hlsAssetListLoading",r.ASSET_LIST_LOADED="hlsAssetListLoaded",r.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",r.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",r.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",r.INTERSTITIAL_STARTED="hlsInterstitialStarted",r.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",r.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",r.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",r.INTERSTITIAL_ENDED="hlsInterstitialEnded",r.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",r.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",r.EVENT_CUE_ENTER="hlsEventCueEnter",r})({});var ee={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},G={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class ks{constructor(e,t=0,s=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=s}sample(e,t){const s=Math.pow(this.alpha_,e);this.estimate_=t*(1-s)+s*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class zh{constructor(e,t,s,i=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=s,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new ks(e),this.fast_=new ks(t),this.defaultTTFB_=i,this.ttfb_=new ks(e)}update(e,t){const{slow_:s,fast_:i,ttfb_:n}=this;s.halfLife!==e&&(this.slow_=new ks(e,s.getEstimate(),s.getTotalWeight())),i.halfLife!==t&&(this.fast_=new ks(t,i.getEstimate(),i.getTotalWeight())),n.halfLife!==e&&(this.ttfb_=new ks(e,n.getEstimate(),n.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);const s=8*t,i=e/1e3,n=s/i;this.fast_.sample(i,n),this.slow_.sample(i,n)}sampleTTFB(e){const t=e/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(s,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}function Qh(r,e,t){return(e=Zh(e))in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}function le(){return le=Object.assign?Object.assign.bind():function(r){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var s in t)({}).hasOwnProperty.call(t,s)&&(r[s]=t[s])}return r},le.apply(null,arguments)}function ao(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(r);e&&(s=s.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,s)}return t}function ae(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?ao(Object(t),!0).forEach(function(s){Qh(r,s,t[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):ao(Object(t)).forEach(function(s){Object.defineProperty(r,s,Object.getOwnPropertyDescriptor(t,s))})}return r}function Jh(r,e){if(typeof r!="object"||!r)return r;var t=r[Symbol.toPrimitive];if(t!==void 0){var s=t.call(r,e);if(typeof s!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(r)}function Zh(r){var e=Jh(r,"string");return typeof e=="symbol"?e:e+""}class rt{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const s=`[${e}]:`;this.trace=Jt,this.debug=t.debug.bind(null,s),this.log=t.log.bind(null,s),this.warn=t.warn.bind(null,s),this.info=t.info.bind(null,s),this.error=t.error.bind(null,s)}}const Jt=function(){},ed={trace:Jt,debug:Jt,log:Jt,warn:Jt,info:Jt,error:Jt};function Fr(){return le({},ed)}function td(r,e){const t=self.console[r];return t?t.bind(self.console,`${e?"["+e+"] ":""}[${r}] >`):Jt}function oo(r,e,t){return e[r]?e[r].bind(e):td(r,t)}const Nr=Fr();function sd(r,e,t){const s=Fr();if(typeof console=="object"&&r===!0||typeof r=="object"){const i=["debug","log","info","warn","error"];i.forEach(n=>{s[n]=oo(n,r,t)});try{s.log(`Debug logs enabled for "${e}" in hls.js version 1.6.15`)}catch{return Fr()}i.forEach(n=>{Nr[n]=oo(n,r)})}else le(Nr,s);return s}const oe=Nr;function Zt(r=!0){return typeof self>"u"?void 0:(r||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function id(r){return typeof self<"u"&&r===self.ManagedMediaSource}function lo(r,e){const t=Object.keys(r),s=Object.keys(e),i=t.length,n=s.length;return!i||!n||i===n&&!t.some(a=>s.indexOf(a)===-1)}function je(r,e=!1){if(typeof TextDecoder<"u"){const l=new TextDecoder("utf-8").decode(r);if(e){const u=l.indexOf("\0");return u!==-1?l.substring(0,u):l}return l.replace(/\0/g,"")}const t=r.length;let s,i,n,a="",o=0;for(;o<t;){if(s=r[o++],s===0&&e)return a;if(s===0||s===3)continue;switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(s);break;case 12:case 13:i=r[o++],a+=String.fromCharCode((s&31)<<6|i&63);break;case 14:i=r[o++],n=r[o++],a+=String.fromCharCode((s&15)<<12|(i&63)<<6|(n&63)<<0);break}}return a}function we(r){let e="";for(let t=0;t<r.length;t++){let s=r[t].toString(16);s.length<2&&(s="0"+s),e+=s}return e}function co(r){return Uint8Array.from(r.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function rd(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var $r={exports:{}},uo;function nd(){return uo||(uo=1,(function(r,e){(function(t){var s=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,n=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(c,l,u){if(u=u||{},c=c.trim(),l=l.trim(),!l){if(!u.alwaysNormalize)return c;var h=o.parseURL(c);if(!h)throw new Error("Error trying to parse base URL.");return h.path=o.normalizePath(h.path),o.buildURLFromParts(h)}var d=o.parseURL(l);if(!d)throw new Error("Error trying to parse relative URL.");if(d.scheme)return u.alwaysNormalize?(d.path=o.normalizePath(d.path),o.buildURLFromParts(d)):l;var g=o.parseURL(c);if(!g)throw new Error("Error trying to parse base URL.");if(!g.netLoc&&g.path&&g.path[0]!=="/"){var f=i.exec(g.path);g.netLoc=f[1],g.path=f[2]}g.netLoc&&!g.path&&(g.path="/");var p={scheme:g.scheme,netLoc:d.netLoc,path:null,params:d.params,query:d.query,fragment:d.fragment};if(!d.netLoc&&(p.netLoc=g.netLoc,d.path[0]!=="/"))if(!d.path)p.path=g.path,d.params||(p.params=g.params,d.query||(p.query=g.query));else{var y=g.path,v=y.substring(0,y.lastIndexOf("/")+1)+d.path;p.path=o.normalizePath(v)}return p.path===null&&(p.path=u.alwaysNormalize?o.normalizePath(d.path):d.path),o.buildURLFromParts(p)},parseURL:function(c){var l=s.exec(c);return l?{scheme:l[1]||"",netLoc:l[2]||"",path:l[3]||"",params:l[4]||"",query:l[5]||"",fragment:l[6]||""}:null},normalizePath:function(c){for(c=c.split("").reverse().join("").replace(n,"");c.length!==(c=c.replace(a,"")).length;);return c.split("").reverse().join("")},buildURLFromParts:function(c){return c.scheme+c.netLoc+c.path+c.params+c.query+c.fragment}};r.exports=o})()})($r)),$r.exports}var Br=nd();class Ur{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}var ce={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class ho{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof e=="string"&&(e={url:e}),this.base=e,od(this,"stats")}setByteRange(e,t){const s=e.split("@",2);let i;s.length===1?i=t?.byteRangeEndOffset||0:i=parseInt(s[1]),this._byteRange=[i,parseInt(s[0])+i]}get baseurl(){return this.base.url}get byteRange(){return this._byteRange===null?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return this._streams===null&&(this._streams={[ce.AUDIO]:null,[ce.VIDEO]:null,[ce.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){return this._stats===null&&(this._stats=new Ur),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=Br.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[ce.AUDIO]=null,e[ce.VIDEO]=null,e[ce.AUDIOVIDEO]=null}}function xe(r){return r.sn!=="initSegment"}class Gr extends ho{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){const e=this.stats.total;if(e)return e}if(this.byteRange.length){const e=this.byteRange[0],t=this.byteRange[1];if($(e)&&$(t))return t-e}return null}get bitrate(){return this.byteLength?this.byteLength*8/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;const{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(!((e=this._decryptdata)!=null&&e.keyId)){const s=Object.keys(t);if(s.length===1){const i=this._decryptdata=t[s[0]]||null;i&&(this._decryptdata=i.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;const e=$(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){var t;const s=Object.keys(this.levelkeys),i=s.length;if(i>1||i===1&&(t=this.levelkeys[s[0]])!=null&&t.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!$(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return xe(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){const t=this.levelkeys;if(t){var s;const i=t[e];i&&!((s=this._decryptdata)!=null&&s.keyId)&&(this._decryptdata=i.getDecryptData(this.sn,t))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,s,i,n,a=!1){const{elementaryStreams:o}=this,c=o[e];if(!c){o[e]={startPTS:t,endPTS:s,startDTS:i,endDTS:n,partial:a};return}c.startPTS=Math.min(c.startPTS,t),c.endPTS=Math.max(c.endPTS,s),c.startDTS=Math.min(c.startDTS,i),c.endDTS=Math.max(c.endDTS,n)}}class ad extends ho{constructor(e,t,s,i,n){super(s),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=i;const a=e.enumeratedString("BYTERANGE");a&&this.setByteRange(a,n),n&&(this.fragOffset=n.fragOffset+n.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}function fo(r,e){const t=Object.getPrototypeOf(r);if(t){const s=Object.getOwnPropertyDescriptor(t,e);return s||fo(t,e)}}function od(r,e){const t=fo(r,e);t&&(t.enumerable=!0,Object.defineProperty(r,e,t))}const go=Math.pow(2,32)-1,ld=[].push,mo={video:1,audio:2,id3:3,text:4};function Le(r){return String.fromCharCode.apply(null,r)}function po(r,e){const t=r[e]<<8|r[e+1];return t<0?65536+t:t}function Y(r,e){const t=vo(r,e);return t<0?4294967296+t:t}function yo(r,e){let t=Y(r,e);return t*=Math.pow(2,32),t+=Y(r,e+4),t}function vo(r,e){return r[e]<<24|r[e+1]<<16|r[e+2]<<8|r[e+3]}function cd(r){const e=r.byteLength;for(let t=0;t<e;){const s=Y(r,t);if(s>8&&r[t+4]===109&&r[t+5]===111&&r[t+6]===111&&r[t+7]===102)return!0;t=s>1?t+s:e}return!1}function J(r,e){const t=[];if(!e.length)return t;const s=r.byteLength;for(let i=0;i<s;){const n=Y(r,i),a=Le(r.subarray(i+4,i+8)),o=n>1?i+n:s;if(a===e[0])if(e.length===1)t.push(r.subarray(i+8,o));else{const c=J(r.subarray(i+8,o),e.slice(1));c.length&&ld.apply(t,c)}i=o}return t}function ud(r){const e=[],t=r[0];let s=8;const i=Y(r,s);s+=4;let n=0,a=0;t===0?(n=Y(r,s),a=Y(r,s+4),s+=8):(n=yo(r,s),a=yo(r,s+8),s+=16),s+=2;let o=r.length+a;const c=po(r,s);s+=2;for(let l=0;l<c;l++){let u=s;const h=Y(r,u);u+=4;const d=h&2147483647;if((h&2147483648)>>>31===1)return oe.warn("SIDX has hierarchical references (not supported)"),null;const f=Y(r,u);u+=4,e.push({referenceSize:d,subsegmentDuration:f,info:{duration:f/i,start:o,end:o+d-1}}),o+=d,u+=4,s=u}return{earliestPresentationTime:n,timescale:i,version:t,referencesCount:c,references:e}}function Eo(r){const e=[],t=J(r,["moov","trak"]);for(let i=0;i<t.length;i++){const n=t[i],a=J(n,["tkhd"])[0];if(a){let o=a[0];const c=Y(a,o===0?12:20),l=J(n,["mdia","mdhd"])[0];if(l){o=l[0];const u=Y(l,o===0?12:20),h=J(n,["mdia","hdlr"])[0];if(h){const d=Le(h.subarray(8,12)),g={soun:ce.AUDIO,vide:ce.VIDEO}[d],f=J(n,["mdia","minf","stbl","stsd"])[0],p=hd(f);g?(e[c]={timescale:u,type:g,stsd:p},e[g]=ae({timescale:u,id:c},p)):e[c]={timescale:u,type:d,stsd:p}}}}}return J(r,["moov","mvex","trex"]).forEach(i=>{const n=Y(i,4),a=e[n];a&&(a.default={duration:Y(i,12),flags:Y(i,20)})}),e}function hd(r){const e=r.subarray(8),t=e.subarray(86),s=Le(e.subarray(4,8));let i=s,n;const a=s==="enca"||s==="encv";if(a){const l=J(e,[s])[0].subarray(s==="enca"?28:78);J(l,["sinf"]).forEach(h=>{const d=J(h,["schm"])[0];if(d){const g=Le(d.subarray(4,8));if(g==="cbcs"||g==="cenc"){const f=J(h,["frma"])[0];f&&(i=Le(f))}}})}const o=i;switch(i){case"avc1":case"avc2":case"avc3":case"avc4":{const c=J(t,["avcC"])[0];c&&c.length>3&&(i+="."+ki(c[1])+ki(c[2])+ki(c[3]),n=wi(o==="avc1"?"dva1":"dvav",t));break}case"mp4a":{const c=J(e,[s])[0],l=J(c.subarray(28),["esds"])[0];if(l&&l.length>7){let u=4;if(l[u++]!==3)break;u=Kr(l,u),u+=2;const h=l[u++];if(h&128&&(u+=2),h&64&&(u+=l[u++]),l[u++]!==4)break;u=Kr(l,u);const d=l[u++];if(d===64)i+="."+ki(d);else break;if(u+=12,l[u++]!==5)break;u=Kr(l,u);const g=l[u++];let f=(g&248)>>3;f===31&&(f+=1+((g&7)<<3)+((l[u]&224)>>5)),i+="."+f}break}case"hvc1":case"hev1":{const c=J(t,["hvcC"])[0];if(c&&c.length>12){const l=c[1],u=["","A","B","C"][l>>6],h=l&31,d=Y(c,2),g=(l&32)>>5?"H":"L",f=c[12],p=c.subarray(6,12);i+="."+u+h,i+="."+dd(d).toString(16).toUpperCase(),i+="."+g+f;let y="";for(let v=p.length;v--;){const E=p[v];(E||y)&&(y="."+E.toString(16).toUpperCase()+y)}i+=y}n=wi(o=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{i=wi(i,t)||i;break}case"vp09":{const c=J(t,["vpcC"])[0];if(c&&c.length>6){const l=c[4],u=c[5],h=c[6]>>4&15;i+="."+St(l)+"."+St(u)+"."+St(h)}break}case"av01":{const c=J(t,["av1C"])[0];if(c&&c.length>2){const l=c[1]>>>5,u=c[1]&31,h=c[2]>>>7?"H":"M",d=(c[2]&64)>>6,g=(c[2]&32)>>5,f=l===2&&d?g?12:10:d?10:8,p=(c[2]&16)>>4,y=(c[2]&8)>>3,v=(c[2]&4)>>2,E=c[2]&3;i+="."+l+"."+St(u)+h+"."+St(f)+"."+p+"."+y+v+E+"."+St(1)+"."+St(1)+"."+St(1)+"."+0,n=wi("dav1",t)}break}}return{codec:i,encrypted:a,supplemental:n}}function wi(r,e){const t=J(e,["dvvC"]),s=t.length?t[0]:J(e,["dvcC"])[0];if(s){const i=s[2]>>1&127,n=s[2]<<5&32|s[3]>>3&31;return r+"."+St(i)+"."+St(n)}}function dd(r){let e=0;for(let t=0;t<32;t++)e|=(r>>t&1)<<31-t;return e>>>0}function Kr(r,e){const t=e+5;for(;r[e++]&128&&e<t;);return e}function ki(r){return("0"+r.toString(16).toUpperCase()).slice(-2)}function St(r){return(r<10?"0":"")+r}function fd(r,e){if(!r||!e)return;const t=e.keyId;t&&e.isCommonEncryption&&To(r,(s,i)=>{const n=s.subarray(8,24);n.some(a=>a!==0)||(oe.log(`[eme] Patching keyId in 'enc${i?"a":"v"}>sinf>>tenc' box: ${we(n)} -> ${we(t)}`),s.set(t,8))})}function gd(r){const e=[];return To(r,t=>e.push(t.subarray(8,24))),e}function To(r,e){J(r,["moov","trak"]).forEach(s=>{const i=J(s,["mdia","minf","stbl","stsd"])[0];if(!i)return;const n=i.subarray(8);let a=J(n,["enca"]);const o=a.length>0;o||(a=J(n,["encv"])),a.forEach(c=>{const l=o?c.subarray(28):c.subarray(78);J(l,["sinf"]).forEach(h=>{const d=So(h);d&&e(d,o)})})})}function So(r){const e=J(r,["schm"])[0];if(e){const t=Le(e.subarray(4,8));if(t==="cbcs"||t==="cenc"){const s=J(r,["schi","tenc"])[0];if(s)return s}}}function md(r,e,t){const s={},i=J(r,["moof","traf"]);for(let n=0;n<i.length;n++){const a=i[n],o=J(a,["tfhd"])[0],c=Y(o,4),l=e[c];if(!l)continue;s[c]||(s[c]={start:NaN,duration:0,sampleCount:0,timescale:l.timescale,type:l.type});const u=s[c],h=J(a,["tfdt"])[0];if(h){const T=h[0];let S=Y(h,4);T===1&&(S===go?t.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(S*=go+1,S+=Y(h,8))),$(S)&&(!$(u.start)||S<u.start)&&(u.start=S)}const d=l.default,g=Y(o,0)|d?.flags;let f=d?.duration||0;g&8&&(g&2?f=Y(o,12):f=Y(o,8));const p=J(a,["trun"]);let y=u.start||0,v=0,E=f;for(let T=0;T<p.length;T++){const S=p[T],_=Y(S,4),D=u.sampleCount;u.sampleCount+=_;const I=S[3]&1,b=S[3]&4,A=S[2]&1,x=S[2]&2,C=S[2]&4,M=S[2]&8;let K=8,V=_;for(I&&(K+=4),b&&_&&(!(S[K+1]&1)&&u.keyFrameIndex===void 0&&(u.keyFrameIndex=D),K+=4,A?(E=Y(S,K),K+=4):E=f,x&&(K+=4),M&&(K+=4),y+=E,v+=E,V--);V--;)A?(E=Y(S,K),K+=4):E=f,x&&(K+=4),C&&(S[K+1]&1||u.keyFrameIndex===void 0&&(u.keyFrameIndex=u.sampleCount-(V+1),u.keyFrameStart=y),K+=4),M&&(K+=4),y+=E,v+=E;!v&&f&&(v+=f*_)}u.duration+=v}if(!Object.keys(s).some(n=>s[n].duration)){let n=1/0,a=0;const o=J(r,["sidx"]);for(let c=0;c<o.length;c++){const l=ud(o[c]);if(l!=null&&l.references){n=Math.min(n,l.earliestPresentationTime/l.timescale);const u=l.references.reduce((h,d)=>h+d.info.duration||0,0);a=Math.max(a,u+l.earliestPresentationTime/l.timescale)}}a&&$(a)&&Object.keys(s).forEach(c=>{s[c].duration||(s[c].duration=a*s[c].timescale-s[c].start)})}return s}function pd(r){const e={valid:null,remainder:null},t=J(r,["moof"]);if(t.length<2)return e.remainder=r,e;const s=t[t.length-1];return e.valid=r.slice(0,s.byteOffset-8),e.remainder=r.slice(s.byteOffset-8),e}function nt(r,e){const t=new Uint8Array(r.length+e.length);return t.set(r),t.set(e,r.length),t}function xo(r,e){const t=[],s=e.samples,i=e.timescale,n=e.id;let a=!1;return J(s,["moof"]).map(c=>{const l=c.byteOffset-8;J(c,["traf"]).map(h=>{const d=J(h,["tfdt"]).map(g=>{const f=g[0];let p=Y(g,4);return f===1&&(p*=Math.pow(2,32),p+=Y(g,8)),p/i})[0];return d!==void 0&&(r=d),J(h,["tfhd"]).map(g=>{const f=Y(g,4),p=Y(g,0)&16777215,y=(p&1)!==0,v=(p&2)!==0,E=(p&8)!==0;let T=0;const S=(p&16)!==0;let _=0;const D=(p&32)!==0;let I=8;f===n&&(y&&(I+=8),v&&(I+=4),E&&(T=Y(g,I),I+=4),S&&(_=Y(g,I),I+=4),D&&(I+=4),e.type==="video"&&(a=Oi(e.codec)),J(h,["trun"]).map(b=>{const A=b[0],x=Y(b,0)&16777215,C=(x&1)!==0;let M=0;const K=(x&4)!==0,V=(x&256)!==0;let N=0;const w=(x&512)!==0;let U=0;const F=(x&1024)!==0,B=(x&2048)!==0;let W=0;const k=Y(b,4);let O=8;C&&(M=Y(b,O),O+=4),K&&(O+=4);let q=M+l;for(let Z=0;Z<k;Z++){if(V?(N=Y(b,O),O+=4):N=T,w?(U=Y(b,O),O+=4):U=_,F&&(O+=4),B&&(A===0?W=Y(b,O):W=vo(b,O),O+=4),e.type===ce.VIDEO){let X=0;for(;X<U;){const z=Y(s,q);if(q+=4,yd(a,s[q])){const Se=s.subarray(q,q+z);Vr(Se,a?2:1,r+W/i,t)}q+=z,X+=z+4}}r+=N/i}}))})})}),t}function Oi(r){if(!r)return!1;const e=r.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function yd(r,e){if(r){const t=e>>1&63;return t===39||t===40}else return(e&31)===6}function Vr(r,e,t,s){const i=Ao(r);let n=0;n+=e;let a=0,o=0,c=0;for(;n<i.length;){a=0;do{if(n>=i.length)break;c=i[n++],a+=c}while(c===255);o=0;do{if(n>=i.length)break;c=i[n++],o+=c}while(c===255);const l=i.length-n;let u=n;if(o<l)n+=o;else if(o>l){oe.error(`Malformed SEI payload. ${o} is too small, only ${l} bytes left to parse.`);break}if(a===4){if(i[u++]===181){const d=po(i,u);if(u+=2,d===49){const g=Y(i,u);if(u+=4,g===1195456820){const f=i[u++];if(f===3){const p=i[u++],y=31&p,v=64&p,E=v?2+y*3:0,T=new Uint8Array(E);if(v){T[0]=p;for(let S=1;S<E;S++)T[S]=i[u++]}s.push({type:f,payloadType:a,pts:t,bytes:T})}}}}}else if(a===5&&o>16){const h=[];for(let f=0;f<16;f++){const p=i[u++].toString(16);h.push(p.length==1?"0"+p:p),(f===3||f===5||f===7||f===9)&&h.push("-")}const d=o-16,g=new Uint8Array(d);for(let f=0;f<d;f++)g[f]=i[u++];s.push({payloadType:a,pts:t,uuid:h.join(""),userData:je(g),userDataBytes:g})}}}function Ao(r){const e=r.byteLength,t=[];let s=1;for(;s<e-2;)r[s]===0&&r[s+1]===0&&r[s+2]===3?(t.push(s+2),s+=2):s++;if(t.length===0)return r;const i=e-t.length,n=new Uint8Array(i);let a=0;for(s=0;s<i;a++,s++)a===t[0]&&(a++,t.shift()),n[s]=r[a];return n}function vd(r){const e=r[0];let t="",s="",i=0,n=0,a=0,o=0,c=0,l=0;if(e===0){for(;Le(r.subarray(l,l+1))!=="\0";)t+=Le(r.subarray(l,l+1)),l+=1;for(t+=Le(r.subarray(l,l+1)),l+=1;Le(r.subarray(l,l+1))!=="\0";)s+=Le(r.subarray(l,l+1)),l+=1;s+=Le(r.subarray(l,l+1)),l+=1,i=Y(r,12),n=Y(r,16),o=Y(r,20),c=Y(r,24),l=28}else if(e===1){l+=4,i=Y(r,l),l+=4;const h=Y(r,l);l+=4;const d=Y(r,l);for(l+=4,a=2**32*h+d,jh(a)||(a=Number.MAX_SAFE_INTEGER,oe.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=Y(r,l),l+=4,c=Y(r,l),l+=4;Le(r.subarray(l,l+1))!=="\0";)t+=Le(r.subarray(l,l+1)),l+=1;for(t+=Le(r.subarray(l,l+1)),l+=1;Le(r.subarray(l,l+1))!=="\0";)s+=Le(r.subarray(l,l+1)),l+=1;s+=Le(r.subarray(l,l+1)),l+=1}const u=r.subarray(l,r.byteLength);return{schemeIdUri:t,value:s,timeScale:i,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:c,payload:u}}function Ed(r,...e){const t=e.length;let s=8,i=t;for(;i--;)s+=e[i].byteLength;const n=new Uint8Array(s);for(n[0]=s>>24&255,n[1]=s>>16&255,n[2]=s>>8&255,n[3]=s&255,n.set(r,4),i=0,s=8;i<t;i++)n.set(e[i],s),s+=e[i].byteLength;return n}function Td(r,e,t){if(r.byteLength!==16)throw new RangeError("Invalid system id");let s,i;s=0,i=new Uint8Array;let n;s>0?(n=new Uint8Array(4),e.length>0&&new DataView(n.buffer).setUint32(0,e.length,!1)):n=new Uint8Array;const a=new Uint8Array(4);return t.byteLength>0&&new DataView(a.buffer).setUint32(0,t.byteLength,!1),Ed([112,115,115,104],new Uint8Array([s,0,0,0]),r,n,i,a,t)}function Sd(r){const e=[];if(r instanceof ArrayBuffer){const t=r.byteLength;let s=0;for(;s+32<t;){const i=new DataView(r,s),n=xd(i);e.push(n),s+=n.size}}return e}function xd(r){const e=r.getUint32(0),t=r.byteOffset,s=r.byteLength;if(s<e)return{offset:t,size:s};if(r.getUint32(4)!==1886614376)return{offset:t,size:e};const n=r.getUint32(8)>>>24;if(n!==0&&n!==1)return{offset:t,size:e};const a=r.buffer,o=we(new Uint8Array(a,t+12,16));let c=null,l=null,u=0;if(n===0)u=28;else{const d=r.getUint32(28);if(!d||s<32+d*16)return{offset:t,size:e};c=[];for(let g=0;g<d;g++)c.push(new Uint8Array(a,t+32+g*16,16));u=32+d*16}if(!u)return{offset:t,size:e};const h=r.getUint32(u);return e-32<h?{offset:t,size:e}:(l=new Uint8Array(a,t+u+4,h),{version:n,systemId:o,kids:c,data:l,offset:t,size:e})}const _o=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),Os={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function Hr(r,e){const t=Os[e];return!!t&&!!t[r.slice(0,4)]}function ti(r,e,t=!0){return!r.split(",").some(s=>!Wr(s,e,t))}function Wr(r,e,t=!0){var s;const i=Zt(t);return(s=i?.isTypeSupported(si(r,e)))!=null?s:!1}function si(r,e){return`${e}/mp4;codecs=${r}`}function Io(r){if(r){const e=r.substring(0,4);return Os.video[e]}return 2}function Mi(r){const e=_o();return r.split(",").reduce((t,s)=>{const n=e&&Oi(s)?9:Os.video[s];return n?(n*2+t)/(t?3:2):(Os.audio[s]+t)/(t?2:1)},0)}const Yr={};function Ad(r,e=!0){if(Yr[r])return Yr[r];const t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[r];for(let i=0;i<t.length;i++){var s;if(Wr(t[i],"audio",e))return Yr[r]=t[i],t[i];if(t[i]==="mp3"&&(s=Zt(e))!=null&&s.isTypeSupported("audio/mpeg"))return""}return r}const _d=/flac|opus|mp4a\.40\.34/i;function Fi(r,e=!0){return r.replace(_d,t=>Ad(t.toLowerCase(),e))}function Id(r,e){const t=[];if(r){const s=r.split(",");for(let i=0;i<s.length;i++)Hr(s[i],"video")||t.push(s[i])}return e&&t.push(e),t.join(",")}function Ni(r,e){if(r&&(r.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(r)!==-1)&&(Lo(r,"audio")||Lo(r,"video")))return r;if(e){const t=e.split(",");if(t.length>1){if(r){for(let s=t.length;s--;)if(t[s].substring(0,4)===r.substring(0,4))return t[s]}return t[0]}}return e||r}function Lo(r,e){return Hr(r,e)&&Wr(r,e)}function Ld(r){const e=r.split(",");for(let t=0;t<e.length;t++){const s=e[t].split(".");s.length>2&&s[0]==="avc1"&&(e[t]=`avc1.${parseInt(s[1]).toString(16)}${("000"+parseInt(s[2]).toString(16)).slice(-4)}`)}return e.join(",")}function Rd(r){if(r.startsWith("av01.")){const e=r.split("."),t=["0","111","01","01","01","0"];for(let s=e.length;s>4&&s<10;s++)e[s]=t[s-4];return e.join(".")}return r}function Ro(r){const e=Zt(r)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function qr(r){return r.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const bd={supported:!0,powerEfficient:!0,smooth:!0},Dd={supported:!1,smooth:!1,powerEfficient:!1},bo={supported:!0,configurations:[],decodingInfoResults:[bd]};function Do(r,e){return{supported:!1,configurations:e,decodingInfoResults:[Dd],error:r}}function Cd(r,e,t,s,i,n){const a=r.videoCodec,o=r.audioCodec?r.audioGroups:null,c=n?.audioCodec,l=n?.channels,u=l?parseInt(l):c?1/0:2;let h=null;if(o!=null&&o.length)try{o.length===1&&o[0]?h=e.groups[o[0]].channels:h=o.reduce((d,g)=>{if(g){const f=e.groups[g];if(!f)throw new Error(`Audio track group ${g} not found`);Object.keys(f.channels).forEach(p=>{d[p]=(d[p]||0)+f.channels[p]})}return d},{2:0})}catch{return!0}return a!==void 0&&(a.split(",").some(d=>Oi(d))||r.width>1920&&r.height>1088||r.height>1920&&r.width>1088||r.frameRate>Math.max(s,30)||r.videoRange!=="SDR"&&r.videoRange!==t||r.bitrate>Math.max(i,8e6))||!!h&&$(u)&&Object.keys(h).some(d=>parseInt(d)>u)}function Co(r,e,t,s={}){const i=r.videoCodec;if(!i&&!r.audioCodec||!t)return Promise.resolve(bo);const n=[],a=Pd(r),o=a.length,c=wd(r,e,o>0),l=c.length;for(let u=o||1*l||1;u--;){const h={type:"media-source"};if(o&&(h.video=a[u%o]),l){h.audio=c[u%l];const d=h.audio.bitrate;h.video&&d&&(h.video.bitrate-=d)}n.push(h)}if(i){const u=navigator.userAgent;if(i.split(",").some(h=>Oi(h))&&_o())return Promise.resolve(Do(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${u})`),n))}return Promise.all(n.map(u=>{const h=Od(u);return s[h]||(s[h]=t.decodingInfo(u))})).then(u=>({supported:!u.some(h=>!h.supported),configurations:n,decodingInfoResults:u})).catch(u=>({supported:!1,configurations:n,decodingInfoResults:[],error:u}))}function Pd(r){var e;const t=(e=r.videoCodec)==null?void 0:e.split(","),s=Po(r),i=r.width||640,n=r.height||480,a=r.frameRate||30,o=r.videoRange.toLowerCase();return t?t.map(c=>{const l={contentType:si(Rd(c),"video"),width:i,height:n,bitrate:s,framerate:a};return o!=="sdr"&&(l.transferFunction=o),l}):[]}function wd(r,e,t){var s;const i=(s=r.audioCodec)==null?void 0:s.split(","),n=Po(r);return i&&r.audioGroups?r.audioGroups.reduce((a,o)=>{var c;const l=o?(c=e.groups[o])==null?void 0:c.tracks:null;return l?l.reduce((u,h)=>{if(h.groupId===o){const d=parseFloat(h.channels||"");i.forEach(g=>{const f={contentType:si(g,"audio"),bitrate:t?kd(g,n):n};d&&(f.channels=""+d),u.push(f)})}return u},a):a},[]):[]}function kd(r,e){if(e<=1)return 1;let t=128e3;return r==="ec-3"?t=768e3:r==="ac-3"&&(t=64e4),Math.min(e/2,t)}function Po(r){return Math.ceil(Math.max(r.bitrate*.9,r.averageBitrate)/1e3)*1e3||1}function Od(r){let e="";const{audio:t,video:s}=r;if(s){const i=qr(s.contentType);e+=`${i}_r${s.height}x${s.width}f${Math.ceil(s.framerate)}${s.transferFunction||"sd"}_${Math.ceil(s.bitrate/1e5)}`}if(t){const i=qr(t.contentType);e+=`${s?"_":""}${i}_c${t.channels}`}return e}const jr=["NONE","TYPE-0","TYPE-1",null];function Md(r){return jr.indexOf(r)>-1}const $i=["SDR","PQ","HLG"];function Fd(r){return!!r&&$i.indexOf(r)>-1}var Bi={No:"",Yes:"YES",v2:"v2"};function wo(r){const{canSkipUntil:e,canSkipDateRanges:t,age:s}=r,i=s<e/2;return e&&i?t?Bi.v2:Bi.Yes:Bi.No}class ko{constructor(e,t,s){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=s}addDirectives(e){const t=new self.URL(e);return this.msn!==void 0&&t.searchParams.set("_HLS_msn",this.msn.toString()),this.part!==void 0&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}class ii{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter(s=>!!s).map(s=>s.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const s=(t=e.supplemental)==null?void 0:t.videoCodec;s&&s!==e.videoCodec&&(this.codecSet+=`,${s.substring(0,4)}`)}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return Oo(this._audioGroups,e)}hasSubtitleGroup(e){return Oo(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let s=this._audioGroups;s||(s=this._audioGroups=[]),s.indexOf(t)===-1&&s.push(t)}else if(e==="text"){let s=this._subtitleGroups;s||(s=this._subtitleGroups=[]),s.indexOf(t)===-1&&s.push(t)}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return(e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return(e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}}function Oo(r,e){return!e||!r?!1:r.indexOf(e)!==-1}function Nd(){if(typeof matchMedia=="function"){const r=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(r.media!==e.media)return r.matches===!0}return!1}function $d(r,e){let t=!1,s=[];if(r&&(t=r!=="SDR",s=[r]),e){s=e.allowedVideoRanges||$i.slice(0);const i=s.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:i&&Nd(),t||(s=["SDR"])}return{preferHDR:t,allowedVideoRanges:s}}const Bd=r=>{const e=new WeakSet;return(t,s)=>{if(r&&(s=r(t,s)),typeof s=="object"&&s!==null){if(e.has(s))return;e.add(s)}return s}},ue=(r,e)=>JSON.stringify(r,Bd(e));function Ud(r,e,t,s,i){const n=Object.keys(r),a=s?.channels,o=s?.audioCodec,c=i?.videoCodec,l=a&&parseInt(a)===2;let u=!1,h=!1,d=1/0,g=1/0,f=1/0,p=1/0,y=0,v=[];const{preferHDR:E,allowedVideoRanges:T}=$d(e,i);for(let b=n.length;b--;){const A=r[n[b]];u||(u=A.channels[2]>0),d=Math.min(d,A.minHeight),g=Math.min(g,A.minFramerate),f=Math.min(f,A.minBitrate),T.filter(C=>A.videoRanges[C]>0).length>0&&(h=!0)}d=$(d)?d:0,g=$(g)?g:0;const S=Math.max(1080,d),_=Math.max(30,g);f=$(f)?f:t,t=Math.max(f,t),h||(e=void 0);const D=n.length>1;return{codecSet:n.reduce((b,A)=>{const x=r[A];if(A===b)return b;if(v=h?T.filter(C=>x.videoRanges[C]>0):[],D){if(x.minBitrate>t)return xt(A,`min bitrate of ${x.minBitrate} > current estimate of ${t}`),b;if(!x.hasDefaultAudio)return xt(A,"no renditions with default or auto-select sound found"),b;if(o&&A.indexOf(o.substring(0,4))%5!==0)return xt(A,`audio codec preference "${o}" not found`),b;if(a&&!l){if(!x.channels[a])return xt(A,`no renditions with ${a} channel sound found (channels options: ${Object.keys(x.channels)})`),b}else if((!o||l)&&u&&x.channels[2]===0)return xt(A,"no renditions with stereo sound found"),b;if(x.minHeight>S)return xt(A,`min resolution of ${x.minHeight} > maximum of ${S}`),b;if(x.minFramerate>_)return xt(A,`min framerate of ${x.minFramerate} > maximum of ${_}`),b;if(!v.some(C=>x.videoRanges[C]>0))return xt(A,`no variants with VIDEO-RANGE of ${ue(v)} found`),b;if(c&&A.indexOf(c.substring(0,4))%5!==0)return xt(A,`video codec preference "${c}" not found`),b;if(x.maxScore<y)return xt(A,`max score of ${x.maxScore} < selected max of ${y}`),b}return b&&(Mi(A)>=Mi(b)||x.fragmentError>r[b].fragmentError)?b:(p=x.minIndex,y=x.maxScore,A)},void 0),videoRanges:v,preferHDR:E,minFramerate:g,minBitrate:f,minIndex:p}}function xt(r,e){oe.log(`[abr] start candidates with "${r}" ignored because ${e}`)}function Mo(r){return r.reduce((e,t)=>{let s=e.groups[t.groupId];s||(s=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(t);const i=t.channels||"2";return s.channels[i]=(s.channels[i]||0)+1,s.hasDefault=s.hasDefault||t.default,s.hasAutoSelect=s.hasAutoSelect||t.autoselect,s.hasDefault&&(e.hasDefaultAudio=!0),s.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function Gd(r,e,t,s){return r.slice(t,s+1).reduce((i,n,a)=>{if(!n.codecSet)return i;const o=n.audioGroups;let c=i[n.codecSet];c||(i[n.codecSet]=c={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:a,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),c.minBitrate=Math.min(c.minBitrate,n.bitrate);const l=Math.min(n.height,n.width);return c.minHeight=Math.min(c.minHeight,l),c.minFramerate=Math.min(c.minFramerate,n.frameRate),c.minIndex=Math.min(c.minIndex,a),c.maxScore=Math.max(c.maxScore,n.score),c.fragmentError+=n.fragmentError,c.videoRanges[n.videoRange]=(c.videoRanges[n.videoRange]||0)+1,o&&o.forEach(u=>{if(!u)return;const h=e.groups[u];h&&(c.hasDefaultAudio=c.hasDefaultAudio||e.hasDefaultAudio?h.hasDefault:h.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(h.channels).forEach(d=>{c.channels[d]=(c.channels[d]||0)+h.channels[d]}))}),i},{})}function Fo(r){if(!r)return r;const{lang:e,assocLang:t,characteristics:s,channels:i,audioCodec:n}=r;return{lang:e,assocLang:t,characteristics:s,channels:i,audioCodec:n}}function At(r,e,t){if("attrs"in r){const s=e.indexOf(r);if(s!==-1)return s}for(let s=0;s<e.length;s++){const i=e[s];if(ds(r,i,t))return s}return-1}function ds(r,e,t){const{groupId:s,name:i,lang:n,assocLang:a,default:o}=r,c=r.forced;return(s===void 0||e.groupId===s)&&(i===void 0||e.name===i)&&(n===void 0||Kd(n,e.lang))&&(n===void 0||e.assocLang===a)&&(o===void 0||e.default===o)&&(c===void 0||e.forced===c)&&(!("characteristics"in r)||Vd(r.characteristics||"",e.characteristics))&&(t===void 0||t(r,e))}function Kd(r,e="--"){return r.length===e.length?r===e:r.startsWith(e)||e.startsWith(r)}function Vd(r,e=""){const t=r.split(","),s=e.split(",");return t.length===s.length&&!t.some(i=>s.indexOf(i)===-1)}function fs(r,e){const{audioCodec:t,channels:s}=r;return(t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(s===void 0||s===(e.channels||"2"))}function Hd(r,e,t,s,i){const n=e[s],o=e.reduce((d,g,f)=>{const p=g.uri;return(d[p]||(d[p]=[])).push(f),d},{})[n.uri];o.length>1&&(s=Math.max.apply(Math,o));const c=n.videoRange,l=n.frameRate,u=n.codecSet.substring(0,4),h=No(e,s,d=>{if(d.videoRange!==c||d.frameRate!==l||d.codecSet.substring(0,4)!==u)return!1;const g=d.audioGroups,f=t.filter(p=>!g||g.indexOf(p.groupId)!==-1);return At(r,f,i)>-1});return h>-1?h:No(e,s,d=>{const g=d.audioGroups,f=t.filter(p=>!g||g.indexOf(p.groupId)!==-1);return At(r,f,i)>-1})}function No(r,e,t){for(let s=e;s>-1;s--)if(t(r[s]))return s;for(let s=e+1;s<r.length;s++)if(t(r[s]))return s;return-1}function Ui(r,e){var t;return!!r&&r!==((t=e.loadLevelObj)==null?void 0:t.uri)}class Wd extends rt{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var s;const{fragCurrent:i,partCurrent:n,hls:a}=this,{autoLevelEnabled:o,media:c}=a;if(!i||!c)return;const l=performance.now(),u=n?n.stats:i.stats,h=n?n.duration:i.duration,d=l-u.loading.start,g=a.minAutoLevel,f=i.level,p=this._nextAutoLevel;if(u.aborted||u.loaded&&u.loaded===u.total||f<=g){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;const y=p>-1&&p!==f,v=!!t||y;if(!v&&(c.paused||!c.playbackRate||!c.readyState))return;const E=a.mainForwardBufferInfo;if(!v&&E===null)return;const T=this.bwEstimator.getEstimateTTFB(),S=Math.abs(c.playbackRate);if(d<=Math.max(T,1e3*(h/(S*2))))return;const _=E?E.len/S:0,D=u.loading.first?u.loading.first-u.loading.start:-1,I=u.loaded&&D>-1,b=this.getBwEstimate(),A=a.levels,x=A[f],C=Math.max(u.loaded,Math.round(h*(i.bitrate||x.averageBitrate)/8));let M=I?d-D:d;M<1&&I&&(M=Math.min(d,u.loaded*8/b));const K=I?u.loaded*1e3/M:0,V=T/1e3,N=K?(C-u.loaded)/K:C*8/b+V;if(N<=_)return;const w=K?K*8:b,U=((s=t?.details||this.hls.latestLevelDetails)==null?void 0:s.live)===!0,F=this.hls.config.abrBandWidthUpFactor;let B=Number.POSITIVE_INFINITY,W;for(W=f-1;W>g;W--){const Z=A[W].maxBitrate,X=!A[W].details||U;if(B=this.getTimeToLoadFrag(V,w,h*Z,X),B<Math.min(_,h+V))break}if(B>=N||B>h*10)return;I?this.bwEstimator.sample(d-Math.min(T,D),u.loaded):this.bwEstimator.sampleTTFB(d);const k=A[W].maxBitrate;this.getBwEstimate()*F>k&&this.resetEstimator(k);const O=this.findBestLevel(k,g,W,0,_,1,1);O>-1&&(W=O),this.warn(`Fragment ${i.sn}${n?" part "+n.index:""} of level ${f} is loading too slowly;
3
- Fragment duration: ${i.duration.toFixed(3)}
4
- Time to underbuffer: ${_.toFixed(3)} s
5
- Estimated load time for current fragment: ${N.toFixed(3)} s
6
- Estimated load time for down switch fragment: ${B.toFixed(3)} s
7
- TTFB estimate: ${D|0} ms
8
- Current BW estimate: ${$(b)?b|0:"Unknown"} bps
1
+ (function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`}),typeof window<`u`&&((window.__svelte??={}).v??=new Set).add(`5`);var t={},n=Symbol(),r=Array.isArray,i=Array.prototype.indexOf,a=Array.prototype.includes,o=Array.from,s=Object.keys,c=Object.defineProperty,l=Object.getOwnPropertyDescriptor,u=Object.getOwnPropertyDescriptors,d=Object.prototype,f=Array.prototype,p=Object.getPrototypeOf,m=Object.isExtensible,h=()=>{};function g(e){for(var t=0;t<e.length;t++)e[t]()}function _(){var e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}var v=1024,y=2048,b=4096,x=8192,S=16384,C=32768,w=1<<25,T=65536,E=1<<19,ee=1<<20,D=65536,te=1<<21,ne=1<<22,O=1<<23,k=Symbol(`$state`),re=Symbol(`legacy props`),ie=new class extends Error{name=`StaleReactionError`;message="The reaction that called `getAbortSignal()` was re-run or destroyed"};globalThis.document?.contentType;function ae(e){throw Error(`https://svelte.dev/e/lifecycle_outside_component`)}function oe(){throw Error(`https://svelte.dev/e/async_derived_orphan`)}function se(e){throw Error(`https://svelte.dev/e/effect_in_teardown`)}function ce(){throw Error(`https://svelte.dev/e/effect_in_unowned_derived`)}function le(e){throw Error(`https://svelte.dev/e/effect_orphan`)}function ue(){throw Error(`https://svelte.dev/e/effect_update_depth_exceeded`)}function de(){throw Error(`https://svelte.dev/e/hydration_failed`)}function fe(e){throw Error(`https://svelte.dev/e/props_invalid_value`)}function pe(){throw Error(`https://svelte.dev/e/state_descriptors_fixed`)}function me(){throw Error(`https://svelte.dev/e/state_prototype_fixed`)}function he(){throw Error(`https://svelte.dev/e/state_unsafe_mutation`)}function ge(){throw Error(`https://svelte.dev/e/svelte_boundary_reset_onerror`)}function _e(e){console.warn(`https://svelte.dev/e/hydration_mismatch`)}function ve(){console.warn(`https://svelte.dev/e/svelte_boundary_reset_noop`)}var ye=!1;function be(e){ye=e}var A;function xe(e){if(e===null)throw _e(),t;return A=e}function Se(){return xe(Zt(A))}function Ce(e){if(ye){if(Zt(A)!==null)throw _e(),t;A=e}}function we(e=1){if(ye){for(var t=e,n=A;t--;)n=Zt(n);A=n}}function Te(e=!0){for(var t=0,n=A;;){if(n.nodeType===8){var r=n.data;if(r===`]`){if(t===0)return n;--t}else (r===`[`||r===`[!`||r[0]===`[`&&!isNaN(Number(r.slice(1))))&&(t+=1)}var i=Zt(n);e&&n.remove(),n=i}}function Ee(e){if(!e||e.nodeType!==8)throw _e(),t;return e.data}function De(e){return e===this.v}function Oe(e,t){return e==e?e!==t||typeof e==`object`&&!!e||typeof e==`function`:t==t}function ke(e){return!Oe(e,this.v)}var Ae=!1,je=!1,Me=null;function Ne(e){Me=e}function Pe(e,t=!1,n){Me={p:Me,i:!1,c:null,e:null,s:e,x:null,r:F,l:je&&!t?{s:null,u:null,$:[]}:null}}function Fe(e){var t=Me,n=t.e;if(n!==null){t.e=null;for(var r of n)fn(r)}return e!==void 0&&(t.x=e),t.i=!0,Me=t.p,e??{}}function Ie(){return!je||Me!==null&&Me.l===null}var Le=[];function Re(){var e=Le;Le=[],g(e)}function ze(e){if(Le.length===0&&!et){var t=Le;queueMicrotask(()=>{t===Le&&Re()})}Le.push(e)}function Be(){for(;Le.length>0;)Re()}function Ve(e){var t=F;if(t===null)return P.f|=O,e;if(!(t.f&32768)&&!(t.f&4))throw e;He(e,t)}function He(e,t){for(;t!==null;){if(t.f&128){if(!(t.f&32768))throw e;try{t.b.error(e);return}catch(t){e=t}}t=t.parent}throw e}var Ue=~(y|b|v);function We(e,t){e.f=e.f&Ue|t}function Ge(e){e.f&512||e.deps===null?We(e,v):We(e,b)}function Ke(e){if(e!==null)for(let t of e)!(t.f&2)||!(t.f&65536)||(t.f^=D,Ke(t.deps))}function qe(e,t,n){e.f&2048?t.add(e):e.f&4096&&n.add(e),Ke(e.deps),We(e,v)}var Je=!1,Ye=!1;function Xe(e){var t=Ye;try{return Ye=!1,[e(),Ye]}finally{Ye=t}}var Ze=new Set,j=null,Qe=null,$e=null,et=!1,tt=!1,nt=null,rt=null,it=0,at=1,ot=class e{id=at++;current=new Map;previous=new Map;#e=new Set;#t=new Set;#n=new Map;#r=new Map;#i=null;#a=[];#o=new Set;#s=new Set;#c=new Map;is_fork=!1;#l=!1;#u=new Set;#d(){return this.is_fork||this.#r.size>0}#f(){for(let n of this.#u)for(let r of n.#r.keys()){for(var e=!1,t=r;t.parent!==null;){if(this.#c.has(t)){e=!0;break}t=t.parent}if(!e)return!0}return!1}skip_effect(e){this.#c.has(e)||this.#c.set(e,{d:[],m:[]})}unskip_effect(e){var t=this.#c.get(e);if(t){this.#c.delete(e);for(var n of t.d)We(n,y),this.schedule(n);for(n of t.m)We(n,b),this.schedule(n)}}#p(){if(it++>1e3&&(Ze.delete(this),ct()),!this.#d()){for(let e of this.#o)this.#s.delete(e),We(e,y),this.schedule(e);for(let e of this.#s)We(e,b),this.schedule(e)}let t=this.#a;this.#a=[],this.apply();var n=nt=[],r=[],i=rt=[];for(let e of t)try{this.#m(e,n,r)}catch(t){throw ht(e),t}if(j=null,i.length>0){var a=e.ensure();for(let e of i)a.schedule(e)}if(nt=null,rt=null,this.#d()||this.#f()){this.#h(r),this.#h(n);for(let[e,t]of this.#c)mt(e,t)}else{this.#n.size===0&&Ze.delete(this),this.#o.clear(),this.#s.clear();for(let e of this.#e)e(this);this.#e.clear(),ut(r),ut(n),this.#i?.resolve()}var o=j;if(this.#a.length>0){let e=o??=this;e.#a.push(...this.#a.filter(t=>!e.#a.includes(t)))}o!==null&&(Ze.add(o),o.#p()),Ze.has(this)||this.#g()}#m(e,t,n){e.f^=v;for(var r=e.first;r!==null;){var i=r.f,a=(i&96)!=0;if(!(a&&i&1024||i&8192||this.#c.has(r))&&r.fn!==null){a?r.f^=v:i&4?t.push(r):Ae&&i&16777224?n.push(r):Xn(r)&&(i&16&&this.#s.add(r),tr(r));var o=r.first;if(o!==null){r=o;continue}}for(;r!==null;){var s=r.next;if(s!==null){r=s;break}r=r.parent}}}#h(e){for(var t=0;t<e.length;t+=1)qe(e[t],this.#o,this.#s)}capture(e,t,r=!1){t!==n&&!this.previous.has(e)&&this.previous.set(e,t),e.f&8388608||(this.current.set(e,[e.v,r]),Qe?.set(e,e.v))}activate(){j=this}deactivate(){j=null,Qe=null}flush(){try{tt=!0,j=this,this.#p()}finally{it=0,$e=null,nt=null,rt=null,tt=!1,j=null,Qe=null,Pt.clear()}}discard(){for(let e of this.#t)e(this);this.#t.clear(),Ze.delete(this)}#g(){for(let c of Ze){var e=c.id<this.id,t=[];for(let[r,[i,a]]of this.current){if(c.current.has(r)){var n=c.current.get(r)[0];if(e&&i!==n)c.current.set(r,[i,a]);else continue}t.push(r)}var r=[...c.current.keys()].filter(e=>!this.current.has(e));if(r.length===0)e&&c.discard();else if(t.length>0){c.activate();var i=new Set,a=new Map;for(var o of t)dt(o,r,i,a);if(c.#a.length>0){c.apply();for(var s of c.#a)c.#m(s,[],[]);c.#a=[]}c.deactivate()}}for(let e of Ze)e.#u.has(this)&&(e.#u.delete(this),e.#u.size===0&&!e.#d()&&(e.activate(),e.#p()))}increment(e,t){let n=this.#n.get(t)??0;if(this.#n.set(t,n+1),e){let e=this.#r.get(t)??0;this.#r.set(t,e+1)}}decrement(e,t,n){let r=this.#n.get(t)??0;if(r===1?this.#n.delete(t):this.#n.set(t,r-1),e){let e=this.#r.get(t)??0;e===1?this.#r.delete(t):this.#r.set(t,e-1)}this.#l||n||(this.#l=!0,ze(()=>{this.#l=!1,this.flush()}))}transfer_effects(e,t){for(let t of e)this.#o.add(t);for(let e of t)this.#s.add(e);e.clear(),t.clear()}oncommit(e){this.#e.add(e)}ondiscard(e){this.#t.add(e)}settled(){return(this.#i??=_()).promise}static ensure(){if(j===null){let t=j=new e;tt||(Ze.add(j),et||ze(()=>{j===t&&t.flush()}))}return j}apply(){if(!Ae||!this.is_fork&&Ze.size===1){Qe=null;return}Qe=new Map;for(let[e,[t]]of this.current)Qe.set(e,t);for(let n of Ze)if(!(n===this||n.is_fork)){var e=!1,t=!1;if(n.id<this.id)for(let[r,[,i]]of n.current)i||(e||=this.current.has(r),t||=!this.current.has(r));if(e&&t)this.#u.add(n);else for(let[e,t]of n.previous)Qe.has(e)||Qe.set(e,t)}}schedule(e){if($e=e,e.b?.is_pending&&e.f&16777228&&!(e.f&32768)){e.b.defer_effect(e);return}for(var t=e;t.parent!==null;){t=t.parent;var n=t.f;if(nt!==null&&t===F&&(Ae||(P===null||!(P.f&2))&&!Je))return;if(n&96){if(!(n&1024))return;t.f^=v}}this.#a.push(t)}};function st(e){var t=et;et=!0;try{var n;for(e&&(j!==null&&!j.is_fork&&j.flush(),n=e());;){if(Be(),j===null)return n;j.flush()}}finally{et=t}}function ct(){try{ue()}catch(e){He(e,$e)}}var lt=null;function ut(e){var t=e.length;if(t!==0){for(var n=0;n<t;){var r=e[n++];if(!(r.f&24576)&&Xn(r)&&(lt=new Set,tr(r),r.deps===null&&r.first===null&&r.nodes===null&&r.teardown===null&&r.ac===null&&En(r),lt?.size>0)){Pt.clear();for(let e of lt){if(e.f&24576)continue;let t=[e],n=e.parent;for(;n!==null;)lt.has(n)&&(lt.delete(n),t.push(n)),n=n.parent;for(let e=t.length-1;e>=0;e--){let n=t[e];n.f&24576||tr(n)}}lt.clear()}}lt=null}}function dt(e,t,n,r){if(!n.has(e)&&(n.add(e),e.reactions!==null))for(let i of e.reactions){let e=i.f;e&2?dt(i,t,n,r):e&4194320&&!(e&2048)&&ft(i,t,r)&&(We(i,y),pt(i))}}function ft(e,t,n){let r=n.get(e);if(r!==void 0)return r;if(e.deps!==null)for(let r of e.deps){if(a.call(t,r))return!0;if(r.f&2&&ft(r,t,n))return n.set(r,!0),!0}return n.set(e,!1),!1}function pt(e){j.schedule(e)}function mt(e,t){if(!(e.f&32&&e.f&1024)){e.f&2048?t.d.push(e):e.f&4096&&t.m.push(e),We(e,v);for(var n=e.first;n!==null;)mt(n,t),n=n.next}}function ht(e){We(e,v);for(var t=e.first;t!==null;)ht(t),t=t.next}function gt(e){let t=0,n=It(0),r;return()=>{ln()&&(I(n),_n(()=>(t===0&&(r=ir(()=>e(()=>Vt(n)))),t+=1,()=>{ze(()=>{--t,t===0&&(r?.(),r=void 0,Vt(n))})})))}}var _t=T|E;function vt(e,t,n,r){new yt(e,t,n,r)}var yt=class{parent;is_pending=!1;transform_error;#e;#t=ye?A:null;#n;#r;#i;#a=null;#o=null;#s=null;#c=null;#l=0;#u=0;#d=!1;#f=new Set;#p=new Set;#m=null;#h=gt(()=>(this.#m=It(this.#l),()=>{this.#m=null}));constructor(e,t,n,r){this.#e=e,this.#n=t,this.#r=e=>{var t=F;t.b=this,t.f|=128,n(e)},this.parent=F.b,this.transform_error=r??this.parent?.transform_error??(e=>e),this.#i=yn(()=>{if(ye){let e=this.#t;Se();let t=e.data===`[!`;if(e.data.startsWith(`[?`)){let t=JSON.parse(e.data.slice(2));this.#_(t)}else t?this.#v():this.#g()}else this.#y()},_t),ye&&(this.#e=A)}#g(){try{this.#a=bn(()=>this.#r(this.#e))}catch(e){this.error(e)}}#_(e){let t=this.#n.failed;t&&(this.#s=bn(()=>{t(this.#e,()=>e,()=>()=>{})}))}#v(){let e=this.#n.pending;e&&(this.is_pending=!0,this.#o=bn(()=>e(this.#e)),ze(()=>{var e=this.#c=document.createDocumentFragment(),t=Yt();e.append(t),this.#a=this.#x(()=>bn(()=>this.#r(t))),this.#u===0&&(this.#e.before(e),this.#c=null,Dn(this.#o,()=>{this.#o=null}),this.#b(j))}))}#y(){try{if(this.is_pending=this.has_pending_snippet(),this.#u=0,this.#l=0,this.#a=bn(()=>{this.#r(this.#e)}),this.#u>0){var e=this.#c=document.createDocumentFragment();jn(this.#a,e);let t=this.#n.pending;this.#o=bn(()=>t(this.#e))}else this.#b(j)}catch(e){this.error(e)}}#b(e){this.is_pending=!1,e.transfer_effects(this.#f,this.#p)}defer_effect(e){qe(e,this.#f,this.#p)}is_rendered(){return!this.is_pending&&(!this.parent||this.parent.is_rendered())}has_pending_snippet(){return!!this.#n.pending}#x(e){var t=F,n=P,r=Me;Rn(this.#i),Ln(this.#i),Ne(this.#i.ctx);try{return ot.ensure(),e()}catch(e){return Ve(e),null}finally{Rn(t),Ln(n),Ne(r)}}#S(e,t){if(!this.has_pending_snippet()){this.parent&&this.parent.#S(e,t);return}this.#u+=e,this.#u===0&&(this.#b(t),this.#o&&Dn(this.#o,()=>{this.#o=null}),this.#c&&=(this.#e.before(this.#c),null))}update_pending_count(e,t){this.#S(e,t),this.#l+=e,!(!this.#m||this.#d)&&(this.#d=!0,ze(()=>{this.#d=!1,this.#m&&zt(this.#m,this.#l)}))}get_effect_pending(){return this.#h(),I(this.#m)}error(e){var t=this.#n.onerror;let n=this.#n.failed;if(!t&&!n)throw e;this.#a&&=(wn(this.#a),null),this.#o&&=(wn(this.#o),null),this.#s&&=(wn(this.#s),null),ye&&(xe(this.#t),we(),xe(Te()));var r=!1,i=!1;let a=()=>{if(r){ve();return}r=!0,i&&ge(),this.#s!==null&&Dn(this.#s,()=>{this.#s=null}),this.#x(()=>{this.#y()})},o=e=>{try{i=!0,t?.(e,a),i=!1}catch(e){He(e,this.#i&&this.#i.parent)}n&&(this.#s=this.#x(()=>{try{return bn(()=>{var t=F;t.b=this,t.f|=128,n(this.#e,()=>e,()=>a)})}catch(e){return He(e,this.#i.parent),null}}))};ze(()=>{var t;try{t=this.transform_error(e)}catch(e){He(e,this.#i&&this.#i.parent);return}typeof t==`object`&&t&&typeof t.then==`function`?t.then(o,e=>He(e,this.#i&&this.#i.parent)):o(t)})}};function bt(e,t,n,r){let i=Ie()?wt:Et;var a=e.filter(e=>!e.settled);if(n.length===0&&a.length===0){r(t.map(i));return}var o=F,s=xt(),c=a.length===1?a[0].promise:a.length>1?Promise.all(a.map(e=>e.promise)):null;function l(e){s();try{r(e)}catch(e){o.f&16384||He(e,o)}St()}if(n.length===0){c.then(()=>l(t.map(i)));return}var u=Ct();function d(){Promise.all(n.map(e=>Tt(e))).then(e=>l([...t.map(i),...e])).catch(e=>He(e,o)).finally(()=>u())}c?c.then(()=>{s(),d(),St()}):d()}function xt(){var e=F,t=P,n=Me,r=j;return function(i=!0){Rn(e),Ln(t),Ne(n),i&&!(e.f&16384)&&(r?.activate(),r?.apply())}}function St(e=!0){Rn(null),Ln(null),Ne(null),e&&j?.deactivate()}function Ct(){var e=F,t=e.b,n=j,r=t.is_rendered();return t.update_pending_count(1,n),n.increment(r,e),(i=!1)=>{t.update_pending_count(-1,n),n.decrement(r,e,i)}}function wt(e){var t=2|y,r=P!==null&&P.f&2?P:null;return F!==null&&(F.f|=E),{ctx:Me,deps:null,effects:null,equals:De,f:t,fn:e,reactions:null,rv:0,v:n,wv:0,parent:r??F,ac:null}}function Tt(e,t,r){let i=F;i===null&&oe();var a=void 0,o=It(n),s=!P,c=new Map;return gn(()=>{var t=F,n=_();a=n.promise;try{Promise.resolve(e()).then(n.resolve,n.reject).finally(St)}catch(e){n.reject(e),St()}var r=j;if(s){if(t.f&32768)var l=Ct();if(i.b.is_rendered())c.get(r)?.reject(ie),c.delete(r);else{for(let e of c.values())e.reject(ie);c.clear()}c.set(r,n)}let u=(e,n=void 0)=>{if(l&&l(n===ie),!(n===ie||t.f&16384)){if(r.activate(),n)o.f|=O,zt(o,n);else{o.f&8388608&&(o.f^=O),zt(o,e);for(let[e,t]of c){if(c.delete(e),e===r)break;t.reject(ie)}}r.deactivate()}};n.promise.then(u,e=>u(null,e||`unknown`))}),un(()=>{for(let e of c.values())e.reject(ie)}),new Promise(e=>{function t(n){function r(){n===a?e(o):t(a)}n.then(r,r)}t(a)})}function Et(e){let t=wt(e);return t.equals=ke,t}function Dt(e){var t=e.effects;if(t!==null){e.effects=null;for(var n=0;n<t.length;n+=1)wn(t[n])}}function Ot(e){for(var t=e.parent;t!==null;){if(!(t.f&2))return t.f&16384?null:t;t=t.parent}return null}function kt(e){var t,n=F;Rn(Ot(e));try{e.f&=~D,Dt(e),t=Qn(e)}finally{Rn(n)}return t}function At(e){var t=e.v,n=kt(e);if(!e.equals(n)&&(e.wv=Yn(),(!j?.is_fork||e.deps===null)&&(e.v=n,j?.capture(e,t,!0),e.deps===null))){We(e,v);return}Pn||(Qe===null?Ge(e):(ln()||j?.is_fork)&&Qe.set(e,n))}function jt(e){if(e.effects!==null)for(let t of e.effects)(t.teardown||t.ac)&&(t.teardown?.(),t.ac?.abort(ie),t.teardown=h,t.ac=null,er(t,0),Sn(t))}function Mt(e){if(e.effects!==null)for(let t of e.effects)t.teardown&&tr(t)}var Nt=new Set,Pt=new Map,Ft=!1;function It(e,t){return{f:0,v:e,reactions:null,equals:De,rv:0,wv:0}}function Lt(e,t){let n=It(e,t);return Bn(n),n}function Rt(e,t=!1,n=!0){let r=It(e);return t||(r.equals=ke),je&&n&&Me!==null&&Me.l!==null&&(Me.l.s??=[]).push(r),r}function M(e,t,n=!1){return P!==null&&(!In||P.f&131072)&&Ie()&&P.f&4325394&&(zn===null||!a.call(zn,e))&&he(),zt(e,n?Ut(t):t,rt)}function zt(e,t,n=null){if(!e.equals(t)){var r=e.v;Pn?Pt.set(e,t):Pt.set(e,r),e.v=t;var i=ot.ensure();if(i.capture(e,r),e.f&2){let t=e;e.f&2048&&kt(t),Qe===null&&Ge(t)}e.wv=Yn(),Ht(e,y,n),Ie()&&F!==null&&F.f&1024&&!(F.f&96)&&(Un===null?Wn([e]):Un.push(e)),!i.is_fork&&Nt.size>0&&!Ft&&Bt()}return t}function Bt(){Ft=!1;for(let e of Nt)e.f&1024&&We(e,b),Xn(e)&&tr(e);Nt.clear()}function Vt(e){M(e,e.v+1)}function Ht(e,t,n){var r=e.reactions;if(r!==null)for(var i=Ie(),a=r.length,o=0;o<a;o++){var s=r[o],c=s.f;if(!(!i&&s===F)){var l=(c&y)===0;if(l&&We(s,t),c&2){var u=s;Qe?.delete(u),c&65536||(c&512&&(s.f|=D),Ht(u,b,n))}else if(l){var d=s;c&16&&lt!==null&&lt.add(d),n===null?pt(d):n.push(d)}}}}function Ut(e){if(typeof e!=`object`||!e||k in e)return e;let t=p(e);if(t!==d&&t!==f)return e;var i=new Map,a=r(e),o=Lt(0),s=null,c=qn,u=e=>{if(qn===c)return e();var t=P,n=qn;Ln(null),Jn(c);var r=e();return Ln(t),Jn(n),r};return a&&i.set(`length`,Lt(e.length,s)),new Proxy(e,{defineProperty(e,t,n){(!(`value`in n)||n.configurable===!1||n.enumerable===!1||n.writable===!1)&&pe();var r=i.get(t);return r===void 0?u(()=>{var e=Lt(n.value,s);return i.set(t,e),e}):M(r,n.value,!0),!0},deleteProperty(e,t){var r=i.get(t);if(r===void 0){if(t in e){let e=u(()=>Lt(n,s));i.set(t,e),Vt(o)}}else M(r,n),Vt(o);return!0},get(t,r,a){if(r===k)return e;var o=i.get(r),c=r in t;if(o===void 0&&(!c||l(t,r)?.writable)&&(o=u(()=>Lt(Ut(c?t[r]:n),s)),i.set(r,o)),o!==void 0){var d=I(o);return d===n?void 0:d}return Reflect.get(t,r,a)},getOwnPropertyDescriptor(e,t){var r=Reflect.getOwnPropertyDescriptor(e,t);if(r&&`value`in r){var a=i.get(t);a&&(r.value=I(a))}else if(r===void 0){var o=i.get(t),s=o?.v;if(o!==void 0&&s!==n)return{enumerable:!0,configurable:!0,value:s,writable:!0}}return r},has(e,t){if(t===k)return!0;var r=i.get(t),a=r!==void 0&&r.v!==n||Reflect.has(e,t);return(r!==void 0||F!==null&&(!a||l(e,t)?.writable))&&(r===void 0&&(r=u(()=>Lt(a?Ut(e[t]):n,s)),i.set(t,r)),I(r)===n)?!1:a},set(e,t,r,c){var d=i.get(t),f=t in e;if(a&&t===`length`)for(var p=r;p<d.v;p+=1){var m=i.get(p+``);m===void 0?p in e&&(m=u(()=>Lt(n,s)),i.set(p+``,m)):M(m,n)}if(d===void 0)(!f||l(e,t)?.writable)&&(d=u(()=>Lt(void 0,s)),M(d,Ut(r)),i.set(t,d));else{f=d.v!==n;var h=u(()=>Ut(r));M(d,h)}var g=Reflect.getOwnPropertyDescriptor(e,t);if(g?.set&&g.set.call(c,r),!f){if(a&&typeof t==`string`){var _=i.get(`length`),v=Number(t);Number.isInteger(v)&&v>=_.v&&M(_,v+1)}Vt(o)}return!0},ownKeys(e){I(o);var t=Reflect.ownKeys(e).filter(e=>{var t=i.get(e);return t===void 0||t.v!==n});for(var[r,a]of i)a.v!==n&&!(r in e)&&t.push(r);return t},setPrototypeOf(){me()}})}var Wt,Gt,Kt,qt;function Jt(){if(Wt===void 0){Wt=window,Gt=/Firefox/.test(navigator.userAgent);var e=Element.prototype,t=Node.prototype,n=Text.prototype;Kt=l(t,`firstChild`).get,qt=l(t,`nextSibling`).get,m(e)&&(e.__click=void 0,e.__className=void 0,e.__attributes=null,e.__style=void 0,e.__e=void 0),m(n)&&(n.__t=void 0)}}function Yt(e=``){return document.createTextNode(e)}function Xt(e){return Kt.call(e)}function Zt(e){return qt.call(e)}function N(e,t){if(!ye)return Xt(e);var n=Xt(A);if(n===null)n=A.appendChild(Yt());else if(t&&n.nodeType!==3){var r=Yt();return n?.before(r),xe(r),r}return t&&rn(n),xe(n),n}function Qt(e,t=!1){if(!ye){var n=Xt(e);return n instanceof Comment&&n.data===``?Zt(n):n}if(t){if(A?.nodeType!==3){var r=Yt();return A?.before(r),xe(r),r}rn(A)}return A}function $t(e,t=1,n=!1){let r=ye?A:e;for(var i;t--;)i=r,r=Zt(r);if(!ye)return r;if(n){if(r?.nodeType!==3){var a=Yt();return r===null?i?.after(a):r.before(a),xe(a),a}rn(r)}return xe(r),r}function en(e){e.textContent=``}function tn(){return!Ae||lt!==null?!1:(F.f&C)!==0}function nn(e,t,n){let r=n?{is:n}:void 0;return document.createElementNS(t??`http://www.w3.org/1999/xhtml`,e,r)}function rn(e){if(e.nodeValue.length<65536)return;let t=e.nextSibling;for(;t!==null&&t.nodeType===3;)t.remove(),e.nodeValue+=t.nodeValue,t=e.nextSibling}function an(e){var t=P,n=F;Ln(null),Rn(null);try{return e()}finally{Ln(t),Rn(n)}}function on(e){F===null&&(P===null&&le(e),ce()),Pn&&se(e)}function sn(e,t){var n=t.last;n===null?t.last=t.first=e:(n.next=e,e.prev=n,t.last=e)}function cn(e,t){var n=F;n!==null&&n.f&8192&&(e|=x);var r={ctx:Me,deps:null,nodes:null,f:e|y|512,first:null,fn:t,last:null,next:null,parent:n,b:n&&n.b,prev:null,teardown:null,wv:0,ac:null},i=r;if(e&4)nt===null?ot.ensure().schedule(r):nt.push(r);else if(t!==null){try{tr(r)}catch(e){throw wn(r),e}i.deps===null&&i.teardown===null&&i.nodes===null&&i.first===i.last&&!(i.f&524288)&&(i=i.first,e&16&&e&65536&&i!==null&&(i.f|=T))}if(i!==null&&(i.parent=n,n!==null&&sn(i,n),P!==null&&P.f&2&&!(e&64))){var a=P;(a.effects??=[]).push(i)}return r}function ln(){return P!==null&&!In}function un(e){let t=cn(8,null);return We(t,v),t.teardown=e,t}function dn(e){on(`$effect`);var t=F.f;if(!P&&t&32&&!(t&32768)){var n=Me;(n.e??=[]).push(e)}else return fn(e)}function fn(e){return cn(4|ee,e)}function pn(e){ot.ensure();let t=cn(64|E,e);return()=>{wn(t)}}function mn(e){ot.ensure();let t=cn(64|E,e);return(e={})=>new Promise(n=>{e.outro?Dn(t,()=>{wn(t),n(void 0)}):(wn(t),n(void 0))})}function hn(e){return cn(4,e)}function gn(e){return cn(ne|E,e)}function _n(e,t=0){return cn(8|t,e)}function vn(e,t=[],n=[],r=[]){bt(r,t,n,t=>{cn(8,()=>e(...t.map(I)))})}function yn(e,t=0){return cn(16|t,e)}function bn(e){return cn(32|E,e)}function xn(e){var t=e.teardown;if(t!==null){let e=Pn,n=P;Fn(!0),Ln(null);try{t.call(null)}finally{Fn(e),Ln(n)}}}function Sn(e,t=!1){var n=e.first;for(e.first=e.last=null;n!==null;){let e=n.ac;e!==null&&an(()=>{e.abort(ie)});var r=n.next;n.f&64?n.parent=null:wn(n,t),n=r}}function Cn(e){for(var t=e.first;t!==null;){var n=t.next;t.f&32||wn(t),t=n}}function wn(e,t=!0){var n=!1;(t||e.f&262144)&&e.nodes!==null&&e.nodes.end!==null&&(Tn(e.nodes.start,e.nodes.end),n=!0),We(e,w),Sn(e,t&&!n),er(e,0);var r=e.nodes&&e.nodes.t;if(r!==null)for(let e of r)e.stop();xn(e),e.f^=w,e.f|=S;var i=e.parent;i!==null&&i.first!==null&&En(e),e.next=e.prev=e.teardown=e.ctx=e.deps=e.fn=e.nodes=e.ac=e.b=null}function Tn(e,t){for(;e!==null;){var n=e===t?null:Zt(e);e.remove(),e=n}}function En(e){var t=e.parent,n=e.prev,r=e.next;n!==null&&(n.next=r),r!==null&&(r.prev=n),t!==null&&(t.first===e&&(t.first=r),t.last===e&&(t.last=n))}function Dn(e,t,n=!0){var r=[];On(e,r,!0);var i=()=>{n&&wn(e),t&&t()},a=r.length;if(a>0){var o=()=>--a||i();for(var s of r)s.out(o)}else i()}function On(e,t,n){if(!(e.f&8192)){e.f^=x;var r=e.nodes&&e.nodes.t;if(r!==null)for(let e of r)(e.is_global||n)&&t.push(e);for(var i=e.first;i!==null;){var a=i.next,o=(i.f&65536)!=0||(i.f&32)!=0&&(e.f&16)!=0;On(i,t,o?n:!1),i=a}}}function kn(e){An(e,!0)}function An(e,t){if(e.f&8192){e.f^=x,e.f&1024||(We(e,y),ot.ensure().schedule(e));for(var n=e.first;n!==null;){var r=n.next,i=(n.f&65536)!=0||(n.f&32)!=0;An(n,i?t:!1),n=r}var a=e.nodes&&e.nodes.t;if(a!==null)for(let e of a)(e.is_global||t)&&e.in()}}function jn(e,t){if(e.nodes)for(var n=e.nodes.start,r=e.nodes.end;n!==null;){var i=n===r?null:Zt(n);t.append(n),n=i}}var Mn=null,Nn=!1,Pn=!1;function Fn(e){Pn=e}var P=null,In=!1;function Ln(e){P=e}var F=null;function Rn(e){F=e}var zn=null;function Bn(e){P!==null&&(!Ae||P.f&2)&&(zn===null?zn=[e]:zn.push(e))}var Vn=null,Hn=0,Un=null;function Wn(e){Un=e}var Gn=1,Kn=0,qn=Kn;function Jn(e){qn=e}function Yn(){return++Gn}function Xn(e){var t=e.f;if(t&2048)return!0;if(t&2&&(e.f&=~D),t&4096){for(var n=e.deps,r=n.length,i=0;i<r;i++){var a=n[i];if(Xn(a)&&At(a),a.wv>e.wv)return!0}t&512&&Qe===null&&We(e,v)}return!1}function Zn(e,t,n=!0){var r=e.reactions;if(r!==null&&!(!Ae&&zn!==null&&a.call(zn,e)))for(var i=0;i<r.length;i++){var o=r[i];o.f&2?Zn(o,t,!1):t===o&&(n?We(o,y):o.f&1024&&We(o,b),pt(o))}}function Qn(e){var t=Vn,n=Hn,r=Un,i=P,a=zn,o=Me,s=In,c=qn,l=e.f;Vn=null,Hn=0,Un=null,P=l&96?null:e,zn=null,Ne(e.ctx),In=!1,qn=++Kn,e.ac!==null&&(an(()=>{e.ac.abort(ie)}),e.ac=null);try{e.f|=te;var u=e.fn,d=u();e.f|=C;var f=e.deps,p=j?.is_fork;if(Vn!==null){var m;if(p||er(e,Hn),f!==null&&Hn>0)for(f.length=Hn+Vn.length,m=0;m<Vn.length;m++)f[Hn+m]=Vn[m];else e.deps=f=Vn;if(ln()&&e.f&512)for(m=Hn;m<f.length;m++)(f[m].reactions??=[]).push(e)}else !p&&f!==null&&Hn<f.length&&(er(e,Hn),f.length=Hn);if(Ie()&&Un!==null&&!In&&f!==null&&!(e.f&6146))for(m=0;m<Un.length;m++)Zn(Un[m],e);if(i!==null&&i!==e){if(Kn++,i.deps!==null)for(let e=0;e<n;e+=1)i.deps[e].rv=Kn;if(t!==null)for(let e of t)e.rv=Kn;Un!==null&&(r===null?r=Un:r.push(...Un))}return e.f&8388608&&(e.f^=O),d}catch(e){return Ve(e)}finally{e.f^=te,Vn=t,Hn=n,Un=r,P=i,zn=a,Ne(o),In=s,qn=c}}function $n(e,t){let n=t.reactions;if(n!==null){var r=i.call(n,e);if(r!==-1){var o=n.length-1;o===0?n=t.reactions=null:(n[r]=n[o],n.pop())}}if(n===null&&t.f&2&&(Vn===null||!a.call(Vn,t))){var s=t;s.f&512&&(s.f^=512,s.f&=~D),Ge(s),jt(s),er(s,0)}}function er(e,t){var n=e.deps;if(n!==null)for(var r=t;r<n.length;r++)$n(e,n[r])}function tr(e){var t=e.f;if(!(t&16384)){We(e,v);var n=F,r=Nn;F=e,Nn=!0;try{t&16777232?Cn(e):Sn(e),xn(e);var i=Qn(e);e.teardown=typeof i==`function`?i:null,e.wv=Gn}finally{Nn=r,F=n}}}function I(e){var t=(e.f&2)!=0;if(Mn?.add(e),P!==null&&!In&&!(F!==null&&F.f&16384)&&(zn===null||!a.call(zn,e))){var n=P.deps;if(P.f&2097152)e.rv<Kn&&(e.rv=Kn,Vn===null&&n!==null&&n[Hn]===e?Hn++:Vn===null?Vn=[e]:Vn.push(e));else{(P.deps??=[]).push(e);var r=e.reactions;r===null?e.reactions=[P]:a.call(r,P)||r.push(P)}}if(Pn&&Pt.has(e))return Pt.get(e);if(t){var i=e;if(Pn){var o=i.v;return(!(i.f&1024)&&i.reactions!==null||rr(i))&&(o=kt(i)),Pt.set(i,o),o}var s=(i.f&512)==0&&!In&&P!==null&&(Nn||(P.f&512)!=0),c=(i.f&C)===0;Xn(i)&&(s&&(i.f|=512),At(i)),s&&!c&&(Mt(i),nr(i))}if(Qe?.has(e))return Qe.get(e);if(e.f&8388608)throw e.v;return e.v}function nr(e){if(e.f|=512,e.deps!==null)for(let t of e.deps)(t.reactions??=[]).push(e),t.f&2&&!(t.f&512)&&(Mt(t),nr(t))}function rr(e){if(e.v===n)return!0;if(e.deps===null)return!1;for(let t of e.deps)if(Pt.has(t)||t.f&2&&rr(t))return!0;return!1}function ir(e){var t=In;try{return In=!0,e()}finally{In=t}}function ar(e){if(!(typeof e!=`object`||!e||e instanceof EventTarget)){if(k in e)or(e);else if(!Array.isArray(e))for(let t in e){let n=e[t];typeof n==`object`&&n&&k in n&&or(n)}}}function or(e,t=new Set){if(typeof e==`object`&&e&&!(e instanceof EventTarget)&&!t.has(e)){t.add(e),e instanceof Date&&e.getTime();for(let n in e)try{or(e[n],t)}catch{}let n=p(e);if(n!==Object.prototype&&n!==Array.prototype&&n!==Map.prototype&&n!==Set.prototype&&n!==Date.prototype){let t=u(n);for(let n in t){let r=t[n].get;if(r)try{r.call(e)}catch{}}}}}var sr=Symbol(`events`),cr=new Set,lr=new Set,ur=null;function dr(e){var t=this,n=t.ownerDocument,r=e.type,i=e.composedPath?.()||[],a=i[0]||e.target;ur=e;var o=0,s=ur===e&&e[sr];if(s){var l=i.indexOf(s);if(l!==-1&&(t===document||t===window)){e[sr]=t;return}var u=i.indexOf(t);if(u===-1)return;l<=u&&(o=l)}if(a=i[o]||e.target,a!==t){c(e,`currentTarget`,{configurable:!0,get(){return a||n}});var d=P,f=F;Ln(null),Rn(null);try{for(var p,m=[];a!==null;){var h=a.assignedSlot||a.parentNode||a.host||null;try{var g=a[sr]?.[r];g!=null&&(!a.disabled||e.target===a)&&g.call(a,e)}catch(e){p?m.push(e):p=e}if(e.cancelBubble||h===t||h===null)break;a=h}if(p){for(let e of m)queueMicrotask(()=>{throw e});throw p}}finally{e[sr]=t,delete e.currentTarget,Ln(d),Rn(f)}}}var fr=globalThis?.window?.trustedTypes&&globalThis.window.trustedTypes.createPolicy(`svelte-trusted-html`,{createHTML:e=>e});function pr(e){return fr?.createHTML(e)??e}function mr(e){var t=nn(`template`);return t.innerHTML=pr(e.replaceAll(`<!>`,`<!---->`)),t.content}function hr(e,t){var n=F;n.nodes===null&&(n.nodes={start:e,end:t,a:null,t:null})}function gr(e,t){var n=(t&1)!=0,r=(t&2)!=0,i,a=!e.startsWith(`<!>`);return()=>{if(ye)return hr(A,null),A;i===void 0&&(i=mr(a?e:`<!>`+e),n||(i=Xt(i)));var t=r||Gt?document.importNode(i,!0):i.cloneNode(!0);if(n){var o=Xt(t),s=t.lastChild;hr(o,s)}else hr(t,t);return t}}function _r(e=``){if(!ye){var t=Yt(e+``);return hr(t,t),t}var n=A;return n.nodeType===3?rn(n):(n.before(n=Yt()),xe(n)),hr(n,n),n}function vr(){if(ye)return hr(A,null),A;var e=document.createDocumentFragment(),t=document.createComment(``),n=Yt();return e.append(t,n),hr(t,n),e}function yr(e,t){if(ye){var n=F;(!(n.f&32768)||n.nodes.end===null)&&(n.nodes.end=A),Se();return}e!==null&&e.before(t)}[...`allowfullscreen.async.autofocus.autoplay.checked.controls.default.disabled.formnovalidate.indeterminate.inert.ismap.loop.multiple.muted.nomodule.novalidate.open.playsinline.readonly.required.reversed.seamless.selected.webkitdirectory.defer.disablepictureinpicture.disableremoteplayback`.split(`.`)];var br=[`touchstart`,`touchmove`];function xr(e){return br.includes(e)}function Sr(e,t){var n=t==null?``:typeof t==`object`?`${t}`:t;n!==(e.__t??=e.nodeValue)&&(e.__t=n,e.nodeValue=`${n}`)}function Cr(e,t){return Er(e,t)}function wr(e,n){Jt(),n.intro=n.intro??!1;let r=n.target,i=ye,a=A;try{for(var o=Xt(r);o&&(o.nodeType!==8||o.data!==`[`);)o=Zt(o);if(!o)throw t;be(!0),xe(o);let i=Er(e,{...n,anchor:o});return be(!1),i}catch(i){if(i instanceof Error&&i.message.split(`
2
+ `).some(e=>e.startsWith(`https://svelte.dev/e/`)))throw i;return i!==t&&console.warn(`Failed to hydrate: `,i),n.recover===!1&&de(),Jt(),en(r),be(!1),Cr(e,n)}finally{be(i),xe(a)}}var Tr=new Map;function Er(e,{target:n,anchor:r,props:i={},events:a,context:s,intro:c=!0,transformError:l}){Jt();var u=void 0,d=mn(()=>{var c=r??n.appendChild(Yt());vt(c,{pending:()=>{}},n=>{Pe({});var r=Me;if(s&&(r.c=s),a&&(i.$$events=a),ye&&hr(n,null),u=e(n,i)||{},ye&&(F.nodes.end=A,A===null||A.nodeType!==8||A.data!==`]`))throw _e(),t;Fe()},l);var d=new Set,f=e=>{for(var t=0;t<e.length;t++){var r=e[t];if(!d.has(r)){d.add(r);var i=xr(r);for(let e of[n,document]){var a=Tr.get(e);a===void 0&&(a=new Map,Tr.set(e,a));var o=a.get(r);o===void 0?(e.addEventListener(r,dr,{passive:i}),a.set(r,1)):a.set(r,o+1)}}}};return f(o(cr)),lr.add(f),()=>{for(var e of d)for(let r of[n,document]){var t=Tr.get(r),i=t.get(e);--i==0?(r.removeEventListener(e,dr),t.delete(e),t.size===0&&Tr.delete(r)):t.set(e,i)}lr.delete(f),c!==r&&c.parentNode?.removeChild(c)}});return Dr.set(u,d),u}var Dr=new WeakMap;function Or(e,t){let n=Dr.get(e);return n?(Dr.delete(e),n(t)):Promise.resolve()}var kr=class{anchor;#e=new Map;#t=new Map;#n=new Map;#r=new Set;#i=!0;constructor(e,t=!0){this.anchor=e,this.#i=t}#a=e=>{if(this.#e.has(e)){var t=this.#e.get(e),n=this.#t.get(t);if(n)kn(n),this.#r.delete(t);else{var r=this.#n.get(t);r&&(this.#t.set(t,r.effect),this.#n.delete(t),r.fragment.lastChild.remove(),this.anchor.before(r.fragment),n=r.effect)}for(let[t,n]of this.#e){if(this.#e.delete(t),t===e)break;let r=this.#n.get(n);r&&(wn(r.effect),this.#n.delete(n))}for(let[e,r]of this.#t){if(e===t||this.#r.has(e))continue;let i=()=>{if(Array.from(this.#e.values()).includes(e)){var t=document.createDocumentFragment();jn(r,t),t.append(Yt()),this.#n.set(e,{effect:r,fragment:t})}else wn(r);this.#r.delete(e),this.#t.delete(e)};this.#i||!n?(this.#r.add(e),Dn(r,i,!1)):i()}}};#o=e=>{this.#e.delete(e);let t=Array.from(this.#e.values());for(let[e,n]of this.#n)t.includes(e)||(wn(n.effect),this.#n.delete(e))};ensure(e,t){var n=j,r=tn();if(t&&!this.#t.has(e)&&!this.#n.has(e))if(r){var i=document.createDocumentFragment(),a=Yt();i.append(a),this.#n.set(e,{effect:bn(()=>t(a)),fragment:i})}else this.#t.set(e,bn(()=>t(this.anchor)));if(this.#e.set(n,e),r){for(let[t,r]of this.#t)t===e?n.unskip_effect(r):n.skip_effect(r);for(let[t,r]of this.#n)t===e?n.unskip_effect(r.effect):n.skip_effect(r.effect);n.oncommit(this.#a),n.ondiscard(this.#o)}else ye&&(this.anchor=A),this.#a(n)}};function Ar(e){Me===null&&ae(`onMount`),je&&Me.l!==null?jr(Me).m.push(e):dn(()=>{let t=ir(e);if(typeof t==`function`)return t})}function jr(e){var t=e.l;return t.u??={a:[],b:[],m:[]}}function Mr(e,t,n=!1){var r;ye&&(r=A,Se());var i=new kr(e),a=n?T:0;function o(e,t){if(ye){var n=Ee(r);if(e!==parseInt(n.substring(1))){var a=Te();xe(a),i.anchor=a,be(!1),i.ensure(e,t),be(!0);return}}i.ensure(e,t)}yn(()=>{var e=!1;t((t,n=0)=>{e=!0,o(n,t)}),e||o(-1,null)},a)}function Nr(e,t,n,r,i){ye&&Se();var a=t.$$slots?.[n],o=!1;a===!0&&(a=t[n===`default`?`children`:n],o=!0),a===void 0?i!==null&&i(e):a(e,o?()=>r:r)}function Pr(e,t){hn(()=>{var n=e.getRootNode(),r=n.host?n:n.head??n.ownerDocument.head;if(!r.querySelector(`#`+t.hash)){let e=nn(`style`);e.id=t.hash,e.textContent=t.code,r.appendChild(e)}})}function Fr(e,t,n){hn(()=>{var r=ir(()=>t(e,n?.())||{});if(n&&r?.update){var i=!1,a={};_n(()=>{var e=n();ar(e),i&&Oe(a,e)&&(a=e,r.update(e))}),i=!0}if(r?.destroy)return()=>r.destroy()})}function Ir(e,t,n,r){var i=!je||(n&2)!=0,a=(n&8)!=0,o=(n&16)!=0,s=r,c=!0,u=()=>(c&&(c=!1,s=o?ir(r):r),s);let d;if(a){var f=k in e||re in e;d=l(e,t)?.set??(f&&t in e?n=>e[t]=n:void 0)}var p,m=!1;a?[p,m]=Xe(()=>e[t]):p=e[t],p===void 0&&r!==void 0&&(p=u(),d&&(i&&fe(t),d(p)));var h=i?()=>{var n=e[t];return n===void 0?u():(c=!0,n)}:()=>{var n=e[t];return n!==void 0&&(s=void 0),n===void 0?s:n};if(i&&!(n&4))return h;if(d){var g=e.$$legacy;return(function(e,t){return arguments.length>0?((!i||!t||g||m)&&d(t?h():e),e):h()})}var _=!1,v=(n&1?wt:Et)(()=>(_=!1,h()));a&&I(v);var y=F;return(function(e,t){if(arguments.length>0){let n=t?I(v):i&&a?Ut(e):e;return M(v,n),_=!0,s!==void 0&&(s=n),e}return Pn&&_||y.f&16384?v.v:I(v)})}function Lr(e){return new Rr(e)}var Rr=class{#e;#t;constructor(e){var t=new Map,n=(e,n)=>{var r=Rt(n,!1,!1);return t.set(e,r),r};let r=new Proxy({...e.props||{},$$events:{}},{get(e,r){return I(t.get(r)??n(r,Reflect.get(e,r)))},has(e,r){return r===re?!0:(I(t.get(r)??n(r,Reflect.get(e,r))),Reflect.has(e,r))},set(e,r,i){return M(t.get(r)??n(r,i),i),Reflect.set(e,r,i)}});this.#t=(e.hydrate?wr:Cr)(e.component,{target:e.target,anchor:e.anchor,props:r,context:e.context,intro:e.intro??!1,recover:e.recover,transformError:e.transformError}),!Ae&&(!e?.props?.$$host||e.sync===!1)&&st(),this.#e=r.$$events;for(let e of Object.keys(this.#t))e===`$set`||e===`$destroy`||e===`$on`||c(this,e,{get(){return this.#t[e]},set(t){this.#t[e]=t},enumerable:!0});this.#t.$set=e=>{Object.assign(r,e)},this.#t.$destroy=()=>{Or(this.#t)}}$set(e){this.#t.$set(e)}$on(e,t){this.#e[e]=this.#e[e]||[];let n=(...e)=>t.call(this,...e);return this.#e[e].push(n),()=>{this.#e[e]=this.#e[e].filter(e=>e!==n)}}$destroy(){this.#t.$destroy()}},zr;typeof HTMLElement==`function`&&(zr=class extends HTMLElement{$$ctor;$$s;$$c;$$cn=!1;$$d={};$$r=!1;$$p_d={};$$l={};$$l_u=new Map;$$me;$$shadowRoot=null;constructor(e,t,n){super(),this.$$ctor=e,this.$$s=t,n&&(this.$$shadowRoot=this.attachShadow(n))}addEventListener(e,t,n){if(this.$$l[e]=this.$$l[e]||[],this.$$l[e].push(t),this.$$c){let n=this.$$c.$on(e,t);this.$$l_u.set(t,n)}super.addEventListener(e,t,n)}removeEventListener(e,t,n){if(super.removeEventListener(e,t,n),this.$$c){let e=this.$$l_u.get(t);e&&(e(),this.$$l_u.delete(t))}}async connectedCallback(){if(this.$$cn=!0,!this.$$c){if(await Promise.resolve(),!this.$$cn||this.$$c)return;function e(e){return t=>{let n=nn(`slot`);e!==`default`&&(n.name=e),yr(t,n)}}let t={},n=Vr(this);for(let r of this.$$s)r in n&&(r===`default`&&!this.$$d.children?(this.$$d.children=e(r),t.default=!0):t[r]=e(r));for(let e of this.attributes){let t=this.$$g_p(e.name);t in this.$$d||(this.$$d[t]=Br(t,e.value,this.$$p_d,`toProp`))}for(let e in this.$$p_d)!(e in this.$$d)&&this[e]!==void 0&&(this.$$d[e]=this[e],delete this[e]);this.$$c=Lr({component:this.$$ctor,target:this.$$shadowRoot||this,props:{...this.$$d,$$slots:t,$$host:this}}),this.$$me=pn(()=>{_n(()=>{this.$$r=!0;for(let e of s(this.$$c)){if(!this.$$p_d[e]?.reflect)continue;this.$$d[e]=this.$$c[e];let t=Br(e,this.$$d[e],this.$$p_d,`toAttribute`);t==null?this.removeAttribute(this.$$p_d[e].attribute||e):this.setAttribute(this.$$p_d[e].attribute||e,t)}this.$$r=!1})});for(let e in this.$$l)for(let t of this.$$l[e]){let n=this.$$c.$on(e,t);this.$$l_u.set(t,n)}this.$$l={}}}attributeChangedCallback(e,t,n){this.$$r||(e=this.$$g_p(e),this.$$d[e]=Br(e,n,this.$$p_d,`toProp`),this.$$c?.$set({[e]:this.$$d[e]}))}disconnectedCallback(){this.$$cn=!1,Promise.resolve().then(()=>{!this.$$cn&&this.$$c&&(this.$$c.$destroy(),this.$$me(),this.$$c=void 0)})}$$g_p(e){return s(this.$$p_d).find(t=>this.$$p_d[t].attribute===e||!this.$$p_d[t].attribute&&t.toLowerCase()===e)||e}});function Br(e,t,n,r){let i=n[e]?.type;if(t=i===`Boolean`&&typeof t!=`boolean`?t!=null:t,!r||!n[e])return t;if(r===`toAttribute`)switch(i){case`Object`:case`Array`:return t==null?null:JSON.stringify(t);case`Boolean`:return t?``:null;case`Number`:return t??null;default:return t}else switch(i){case`Object`:case`Array`:return t&&JSON.parse(t);case`Boolean`:return t;case`Number`:return t==null?t:+t;default:return t}}function Vr(e){let t={};return e.childNodes.forEach(e=>{t[e.slot||`default`]=!0}),t}function Hr(e,t,n,r,i,a){let o=class extends zr{constructor(){super(e,n,i),this.$$p_d=t}static get observedAttributes(){return s(t).map(e=>(t[e].attribute||e).toLowerCase())}};return s(t).forEach(e=>{c(o.prototype,e,{get(){return this.$$c&&e in this.$$c?this.$$c[e]:this.$$d[e]},set(n){n=Br(e,n,t),this.$$d[e]=n;var r=this.$$c;r&&(l(r,e)?.get?r[e]=n:r.$set({[e]:n}))}})}),r.forEach(e=>{c(o.prototype,e,{get(){return this.$$c?.[e]}})}),a&&(o=a(o)),e.element=o,o}var L=Number.isFinite||function(e){return typeof e==`number`&&isFinite(e)},Ur=Number.isSafeInteger||function(e){return typeof e==`number`&&Math.abs(e)<=Wr},Wr=2**53-1||9007199254740991,R=function(e){return e.NETWORK_ERROR=`networkError`,e.MEDIA_ERROR=`mediaError`,e.KEY_SYSTEM_ERROR=`keySystemError`,e.MUX_ERROR=`muxError`,e.OTHER_ERROR=`otherError`,e}({}),z=function(e){return e.KEY_SYSTEM_NO_KEYS=`keySystemNoKeys`,e.KEY_SYSTEM_NO_ACCESS=`keySystemNoAccess`,e.KEY_SYSTEM_NO_SESSION=`keySystemNoSession`,e.KEY_SYSTEM_NO_CONFIGURED_LICENSE=`keySystemNoConfiguredLicense`,e.KEY_SYSTEM_LICENSE_REQUEST_FAILED=`keySystemLicenseRequestFailed`,e.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED=`keySystemServerCertificateRequestFailed`,e.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED=`keySystemServerCertificateUpdateFailed`,e.KEY_SYSTEM_SESSION_UPDATE_FAILED=`keySystemSessionUpdateFailed`,e.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED=`keySystemStatusOutputRestricted`,e.KEY_SYSTEM_STATUS_INTERNAL_ERROR=`keySystemStatusInternalError`,e.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR=`keySystemDestroyMediaKeysError`,e.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR=`keySystemDestroyCloseSessionError`,e.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR=`keySystemDestroyRemoveSessionError`,e.MANIFEST_LOAD_ERROR=`manifestLoadError`,e.MANIFEST_LOAD_TIMEOUT=`manifestLoadTimeOut`,e.MANIFEST_PARSING_ERROR=`manifestParsingError`,e.MANIFEST_INCOMPATIBLE_CODECS_ERROR=`manifestIncompatibleCodecsError`,e.LEVEL_EMPTY_ERROR=`levelEmptyError`,e.LEVEL_LOAD_ERROR=`levelLoadError`,e.LEVEL_LOAD_TIMEOUT=`levelLoadTimeOut`,e.LEVEL_PARSING_ERROR=`levelParsingError`,e.LEVEL_SWITCH_ERROR=`levelSwitchError`,e.AUDIO_TRACK_LOAD_ERROR=`audioTrackLoadError`,e.AUDIO_TRACK_LOAD_TIMEOUT=`audioTrackLoadTimeOut`,e.SUBTITLE_LOAD_ERROR=`subtitleTrackLoadError`,e.SUBTITLE_TRACK_LOAD_TIMEOUT=`subtitleTrackLoadTimeOut`,e.FRAG_LOAD_ERROR=`fragLoadError`,e.FRAG_LOAD_TIMEOUT=`fragLoadTimeOut`,e.FRAG_DECRYPT_ERROR=`fragDecryptError`,e.FRAG_PARSING_ERROR=`fragParsingError`,e.FRAG_GAP=`fragGap`,e.REMUX_ALLOC_ERROR=`remuxAllocError`,e.KEY_LOAD_ERROR=`keyLoadError`,e.KEY_LOAD_TIMEOUT=`keyLoadTimeOut`,e.BUFFER_ADD_CODEC_ERROR=`bufferAddCodecError`,e.BUFFER_INCOMPATIBLE_CODECS_ERROR=`bufferIncompatibleCodecsError`,e.BUFFER_APPEND_ERROR=`bufferAppendError`,e.BUFFER_APPENDING_ERROR=`bufferAppendingError`,e.BUFFER_STALLED_ERROR=`bufferStalledError`,e.BUFFER_FULL_ERROR=`bufferFullError`,e.BUFFER_SEEK_OVER_HOLE=`bufferSeekOverHole`,e.BUFFER_NUDGE_ON_STALL=`bufferNudgeOnStall`,e.ASSET_LIST_LOAD_ERROR=`assetListLoadError`,e.ASSET_LIST_LOAD_TIMEOUT=`assetListLoadTimeout`,e.ASSET_LIST_PARSING_ERROR=`assetListParsingError`,e.INTERSTITIAL_ASSET_ITEM_ERROR=`interstitialAssetItemError`,e.INTERNAL_EXCEPTION=`internalException`,e.INTERNAL_ABORTED=`aborted`,e.ATTACH_MEDIA_ERROR=`attachMediaError`,e.UNKNOWN=`unknown`,e}({}),B=function(e){return e.MEDIA_ATTACHING=`hlsMediaAttaching`,e.MEDIA_ATTACHED=`hlsMediaAttached`,e.MEDIA_DETACHING=`hlsMediaDetaching`,e.MEDIA_DETACHED=`hlsMediaDetached`,e.MEDIA_ENDED=`hlsMediaEnded`,e.STALL_RESOLVED=`hlsStallResolved`,e.BUFFER_RESET=`hlsBufferReset`,e.BUFFER_CODECS=`hlsBufferCodecs`,e.BUFFER_CREATED=`hlsBufferCreated`,e.BUFFER_APPENDING=`hlsBufferAppending`,e.BUFFER_APPENDED=`hlsBufferAppended`,e.BUFFER_EOS=`hlsBufferEos`,e.BUFFERED_TO_END=`hlsBufferedToEnd`,e.BUFFER_FLUSHING=`hlsBufferFlushing`,e.BUFFER_FLUSHED=`hlsBufferFlushed`,e.MANIFEST_LOADING=`hlsManifestLoading`,e.MANIFEST_LOADED=`hlsManifestLoaded`,e.MANIFEST_PARSED=`hlsManifestParsed`,e.LEVEL_SWITCHING=`hlsLevelSwitching`,e.LEVEL_SWITCHED=`hlsLevelSwitched`,e.LEVEL_LOADING=`hlsLevelLoading`,e.LEVEL_LOADED=`hlsLevelLoaded`,e.LEVEL_UPDATED=`hlsLevelUpdated`,e.LEVEL_PTS_UPDATED=`hlsLevelPtsUpdated`,e.LEVELS_UPDATED=`hlsLevelsUpdated`,e.AUDIO_TRACKS_UPDATED=`hlsAudioTracksUpdated`,e.AUDIO_TRACK_SWITCHING=`hlsAudioTrackSwitching`,e.AUDIO_TRACK_SWITCHED=`hlsAudioTrackSwitched`,e.AUDIO_TRACK_LOADING=`hlsAudioTrackLoading`,e.AUDIO_TRACK_LOADED=`hlsAudioTrackLoaded`,e.AUDIO_TRACK_UPDATED=`hlsAudioTrackUpdated`,e.SUBTITLE_TRACKS_UPDATED=`hlsSubtitleTracksUpdated`,e.SUBTITLE_TRACKS_CLEARED=`hlsSubtitleTracksCleared`,e.SUBTITLE_TRACK_SWITCH=`hlsSubtitleTrackSwitch`,e.SUBTITLE_TRACK_LOADING=`hlsSubtitleTrackLoading`,e.SUBTITLE_TRACK_LOADED=`hlsSubtitleTrackLoaded`,e.SUBTITLE_TRACK_UPDATED=`hlsSubtitleTrackUpdated`,e.SUBTITLE_FRAG_PROCESSED=`hlsSubtitleFragProcessed`,e.CUES_PARSED=`hlsCuesParsed`,e.NON_NATIVE_TEXT_TRACKS_FOUND=`hlsNonNativeTextTracksFound`,e.INIT_PTS_FOUND=`hlsInitPtsFound`,e.FRAG_LOADING=`hlsFragLoading`,e.FRAG_LOAD_EMERGENCY_ABORTED=`hlsFragLoadEmergencyAborted`,e.FRAG_LOADED=`hlsFragLoaded`,e.FRAG_DECRYPTED=`hlsFragDecrypted`,e.FRAG_PARSING_INIT_SEGMENT=`hlsFragParsingInitSegment`,e.FRAG_PARSING_USERDATA=`hlsFragParsingUserdata`,e.FRAG_PARSING_METADATA=`hlsFragParsingMetadata`,e.FRAG_PARSED=`hlsFragParsed`,e.FRAG_BUFFERED=`hlsFragBuffered`,e.FRAG_CHANGED=`hlsFragChanged`,e.FPS_DROP=`hlsFpsDrop`,e.FPS_DROP_LEVEL_CAPPING=`hlsFpsDropLevelCapping`,e.MAX_AUTO_LEVEL_UPDATED=`hlsMaxAutoLevelUpdated`,e.ERROR=`hlsError`,e.DESTROYING=`hlsDestroying`,e.KEY_LOADING=`hlsKeyLoading`,e.KEY_LOADED=`hlsKeyLoaded`,e.LIVE_BACK_BUFFER_REACHED=`hlsLiveBackBufferReached`,e.BACK_BUFFER_REACHED=`hlsBackBufferReached`,e.STEERING_MANIFEST_LOADED=`hlsSteeringManifestLoaded`,e.ASSET_LIST_LOADING=`hlsAssetListLoading`,e.ASSET_LIST_LOADED=`hlsAssetListLoaded`,e.INTERSTITIALS_UPDATED=`hlsInterstitialsUpdated`,e.INTERSTITIALS_BUFFERED_TO_BOUNDARY=`hlsInterstitialsBufferedToBoundary`,e.INTERSTITIAL_ASSET_PLAYER_CREATED=`hlsInterstitialAssetPlayerCreated`,e.INTERSTITIAL_STARTED=`hlsInterstitialStarted`,e.INTERSTITIAL_ASSET_STARTED=`hlsInterstitialAssetStarted`,e.INTERSTITIAL_ASSET_ENDED=`hlsInterstitialAssetEnded`,e.INTERSTITIAL_ASSET_ERROR=`hlsInterstitialAssetError`,e.INTERSTITIAL_ENDED=`hlsInterstitialEnded`,e.INTERSTITIALS_PRIMARY_RESUMED=`hlsInterstitialsPrimaryResumed`,e.PLAYOUT_LIMIT_REACHED=`hlsPlayoutLimitReached`,e.EVENT_CUE_ENTER=`hlsEventCueEnter`,e}({}),V={MANIFEST:`manifest`,LEVEL:`level`,AUDIO_TRACK:`audioTrack`,SUBTITLE_TRACK:`subtitleTrack`},H={MAIN:`main`,AUDIO:`audio`,SUBTITLE:`subtitle`},Gr=class{constructor(e,t=0,n=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=n}sample(e,t){let n=this.alpha_**+e;this.estimate_=t*(1-n)+n*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){let e=1-this.alpha_**+this.totalWeight_;if(e)return this.estimate_/e}return this.estimate_}},Kr=class{constructor(e,t,n,r=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=n,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new Gr(e),this.fast_=new Gr(t),this.defaultTTFB_=r,this.ttfb_=new Gr(e)}update(e,t){let{slow_:n,fast_:r,ttfb_:i}=this;n.halfLife!==e&&(this.slow_=new Gr(e,n.getEstimate(),n.getTotalWeight())),r.halfLife!==t&&(this.fast_=new Gr(t,r.getEstimate(),r.getTotalWeight())),i.halfLife!==e&&(this.ttfb_=new Gr(e,i.getEstimate(),i.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);let n=8*t,r=e/1e3,i=n/r;this.fast_.sample(r,i),this.slow_.sample(r,i)}sampleTTFB(e){let t=e/1e3,n=Math.sqrt(2)*Math.exp(-(t**2)/2);this.ttfb_.sample(n,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}};function qr(e,t,n){return(t=Xr(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function U(){return U=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},U.apply(null,arguments)}function Jr(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function W(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?Jr(Object(n),!0).forEach(function(t){qr(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Jr(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function Yr(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function Xr(e){var t=Yr(e,`string`);return typeof t==`symbol`?t:t+``}var Zr=class{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;let n=`[${e}]:`;this.trace=Qr,this.debug=t.debug.bind(null,n),this.log=t.log.bind(null,n),this.warn=t.warn.bind(null,n),this.info=t.info.bind(null,n),this.error=t.error.bind(null,n)}},Qr=function(){},$r={trace:Qr,debug:Qr,log:Qr,warn:Qr,info:Qr,error:Qr};function ei(){return U({},$r)}function ti(e,t){let n=self.console[e];return n?n.bind(self.console,`${t?`[`+t+`] `:``}[${e}] >`):Qr}function ni(e,t,n){return t[e]?t[e].bind(t):ti(e,n)}var ri=ei();function ii(e,t,n){let r=ei();if(typeof console==`object`&&e===!0||typeof e==`object`){let i=[`debug`,`log`,`info`,`warn`,`error`];i.forEach(t=>{r[t]=ni(t,e,n)});try{r.log(`Debug logs enabled for "${t}" in hls.js version 1.6.15`)}catch{return ei()}i.forEach(t=>{ri[t]=ni(t,e)})}else U(ri,r);return r}var G=ri;function ai(e=!0){if(!(typeof self>`u`))return(e||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function oi(e){return typeof self<`u`&&e===self.ManagedMediaSource}function si(e,t){let n=Object.keys(e),r=Object.keys(t),i=n.length,a=r.length;return!i||!a||i===a&&!n.some(e=>r.indexOf(e)===-1)}function ci(e,t=!1){if(typeof TextDecoder<`u`){let n=new TextDecoder(`utf-8`).decode(e);if(t){let e=n.indexOf(`\0`);return e===-1?n:n.substring(0,e)}return n.replace(/\0/g,``)}let n=e.length,r,i,a,o=``,s=0;for(;s<n;){if(r=e[s++],r===0&&t)return o;if(!(r===0||r===3))switch(r>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(r);break;case 12:case 13:i=e[s++],o+=String.fromCharCode((r&31)<<6|i&63);break;case 14:i=e[s++],a=e[s++],o+=String.fromCharCode((r&15)<<12|(i&63)<<6|(a&63)<<0);break}}return o}function li(e){let t=``;for(let n=0;n<e.length;n++){let r=e[n].toString(16);r.length<2&&(r=`0`+r),t+=r}return t}function ui(e){return Uint8Array.from(e.replace(/^0x/,``).replace(/([\da-fA-F]{2}) ?/g,`0x$1 `).replace(/ +$/,``).split(` `)).buffer}function di(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,`default`)?e.default:e}var fi={exports:{}},pi;function mi(){return pi?fi.exports:(pi=1,(function(e,t){(function(t){var n=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,r=/^(?=([^\/?#]*))\1([^]*)$/,i=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(e,t,n){if(n||={},e=e.trim(),t=t.trim(),!t){if(!n.alwaysNormalize)return e;var i=o.parseURL(e);if(!i)throw Error(`Error trying to parse base URL.`);return i.path=o.normalizePath(i.path),o.buildURLFromParts(i)}var a=o.parseURL(t);if(!a)throw Error(`Error trying to parse relative URL.`);if(a.scheme)return n.alwaysNormalize?(a.path=o.normalizePath(a.path),o.buildURLFromParts(a)):t;var s=o.parseURL(e);if(!s)throw Error(`Error trying to parse base URL.`);if(!s.netLoc&&s.path&&s.path[0]!==`/`){var c=r.exec(s.path);s.netLoc=c[1],s.path=c[2]}s.netLoc&&!s.path&&(s.path=`/`);var l={scheme:s.scheme,netLoc:a.netLoc,path:null,params:a.params,query:a.query,fragment:a.fragment};if(!a.netLoc&&(l.netLoc=s.netLoc,a.path[0]!==`/`))if(!a.path)l.path=s.path,a.params||(l.params=s.params,a.query||(l.query=s.query));else{var u=s.path,d=u.substring(0,u.lastIndexOf(`/`)+1)+a.path;l.path=o.normalizePath(d)}return l.path===null&&(l.path=n.alwaysNormalize?o.normalizePath(a.path):a.path),o.buildURLFromParts(l)},parseURL:function(e){var t=n.exec(e);return t?{scheme:t[1]||``,netLoc:t[2]||``,path:t[3]||``,params:t[4]||``,query:t[5]||``,fragment:t[6]||``}:null},normalizePath:function(e){for(e=e.split(``).reverse().join(``).replace(i,``);e.length!==(e=e.replace(a,``)).length;);return e.split(``).reverse().join(``)},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}};e.exports=o})()})(fi),fi.exports)}var hi=mi(),gi=class{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}},K={AUDIO:`audio`,VIDEO:`video`,AUDIOVIDEO:`audiovideo`},_i=class{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof e==`string`&&(e={url:e}),this.base=e,Si(this,`stats`)}setByteRange(e,t){let n=e.split(`@`,2),r;r=n.length===1?t?.byteRangeEndOffset||0:parseInt(n[1]),this._byteRange=[r,parseInt(n[0])+r]}get baseurl(){return this.base.url}get byteRange(){return this._byteRange===null?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return this._streams===null&&(this._streams={[K.AUDIO]:null,[K.VIDEO]:null,[K.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){return this._stats===null&&(this._stats=new gi),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=hi.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||``}set url(e){this._url=e}clearElementaryStreamInfo(){let{elementaryStreams:e}=this;e[K.AUDIO]=null,e[K.VIDEO]=null,e[K.AUDIOVIDEO]=null}};function vi(e){return e.sn!==`initSegment`}var yi=class extends _i{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){let e=this.stats.total;if(e)return e}if(this.byteRange.length){let e=this.byteRange[0],t=this.byteRange[1];if(L(e)&&L(t))return t-e}return null}get bitrate(){return this.byteLength?this.byteLength*8/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;let{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||=t.identity.getDecryptData(this.sn);else if(!((e=this._decryptdata)!=null&&e.keyId)){let e=Object.keys(t);if(e.length===1){let n=this._decryptdata=t[e[0]]||null;n&&(this._decryptdata=n.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;let e=L(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){var t;let e=Object.keys(this.levelkeys),n=e.length;if(n>1||n===1&&(t=this.levelkeys[e[0]])!=null&&t.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!L(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return vi(this)?(this._ref||={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime},this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){let t=this.levelkeys;if(t){var n;let r=t[e];r&&!((n=this._decryptdata)!=null&&n.keyId)&&(this._decryptdata=r.getDecryptData(this.sn,t))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,n,r,i,a=!1){let{elementaryStreams:o}=this,s=o[e];if(!s){o[e]={startPTS:t,endPTS:n,startDTS:r,endDTS:i,partial:a};return}s.startPTS=Math.min(s.startPTS,t),s.endPTS=Math.max(s.endPTS,n),s.startDTS=Math.min(s.startDTS,r),s.endDTS=Math.max(s.endDTS,i)}},bi=class extends _i{constructor(e,t,n,r,i){super(n),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint(`DURATION`),this.gap=e.bool(`GAP`),this.independent=e.bool(`INDEPENDENT`),this.relurl=e.enumeratedString(`URI`),this.fragment=t,this.index=r;let a=e.enumeratedString(`BYTERANGE`);a&&this.setByteRange(a,i),i&&(this.fragOffset=i.fragOffset+i.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){let{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}};function xi(e,t){let n=Object.getPrototypeOf(e);if(n)return Object.getOwnPropertyDescriptor(n,t)||xi(n,t)}function Si(e,t){let n=xi(e,t);n&&(n.enumerable=!0,Object.defineProperty(e,t,n))}var Ci=2**32-1,wi=[].push,Ti={video:1,audio:2,id3:3,text:4};function Ei(e){return String.fromCharCode.apply(null,e)}function Di(e,t){let n=e[t]<<8|e[t+1];return n<0?65536+n:n}function q(e,t){let n=ki(e,t);return n<0?4294967296+n:n}function Oi(e,t){let n=q(e,t);return n*=2**32,n+=q(e,t+4),n}function ki(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function Ai(e){let t=e.byteLength;for(let n=0;n<t;){let r=q(e,n);if(r>8&&e[n+4]===109&&e[n+5]===111&&e[n+6]===111&&e[n+7]===102)return!0;n=r>1?n+r:t}return!1}function J(e,t){let n=[];if(!t.length)return n;let r=e.byteLength;for(let i=0;i<r;){let a=q(e,i),o=Ei(e.subarray(i+4,i+8)),s=a>1?i+a:r;if(o===t[0])if(t.length===1)n.push(e.subarray(i+8,s));else{let r=J(e.subarray(i+8,s),t.slice(1));r.length&&wi.apply(n,r)}i=s}return n}function ji(e){let t=[],n=e[0],r=8,i=q(e,r);r+=4;let a=0,o=0;n===0?(a=q(e,r),o=q(e,r+4),r+=8):(a=Oi(e,r),o=Oi(e,r+8),r+=16),r+=2;let s=e.length+o,c=Di(e,r);r+=2;for(let n=0;n<c;n++){let n=r,a=q(e,n);n+=4;let o=a&2147483647;if((a&2147483648)>>>31==1)return G.warn(`SIDX has hierarchical references (not supported)`),null;let c=q(e,n);n+=4,t.push({referenceSize:o,subsegmentDuration:c,info:{duration:c/i,start:s,end:s+o-1}}),s+=o,n+=4,r=n}return{earliestPresentationTime:a,timescale:i,version:n,referencesCount:c,references:t}}function Mi(e){let t=[],n=J(e,[`moov`,`trak`]);for(let e=0;e<n.length;e++){let r=n[e],i=J(r,[`tkhd`])[0];if(i){let e=i[0],n=q(i,e===0?12:20),a=J(r,[`mdia`,`mdhd`])[0];if(a){e=a[0];let i=q(a,e===0?12:20),o=J(r,[`mdia`,`hdlr`])[0];if(o){let e=Ei(o.subarray(8,12)),a={soun:K.AUDIO,vide:K.VIDEO}[e],s=J(r,[`mdia`,`minf`,`stbl`,`stsd`])[0],c=Ni(s);a?(t[n]={timescale:i,type:a,stsd:c},t[a]=W({timescale:i,id:n},c)):t[n]={timescale:i,type:e,stsd:c}}}}}return J(e,[`moov`,`mvex`,`trex`]).forEach(e=>{let n=t[q(e,4)];n&&(n.default={duration:q(e,12),flags:q(e,20)})}),t}function Ni(e){let t=e.subarray(8),n=t.subarray(86),r=Ei(t.subarray(4,8)),i=r,a,o=r===`enca`||r===`encv`;o&&J(J(t,[r])[0].subarray(r===`enca`?28:78),[`sinf`]).forEach(e=>{let t=J(e,[`schm`])[0];if(t){let n=Ei(t.subarray(4,8));if(n===`cbcs`||n===`cenc`){let t=J(e,[`frma`])[0];t&&(i=Ei(t))}}});let s=i;switch(i){case`avc1`:case`avc2`:case`avc3`:case`avc4`:{let e=J(n,[`avcC`])[0];e&&e.length>3&&(i+=`.`+Li(e[1])+Li(e[2])+Li(e[3]),a=Pi(s===`avc1`?`dva1`:`dvav`,n));break}case`mp4a`:{let e=J(t,[r])[0],n=J(e.subarray(28),[`esds`])[0];if(n&&n.length>7){let e=4;if(n[e++]!==3)break;e=Ii(n,e),e+=2;let t=n[e++];if(t&128&&(e+=2),t&64&&(e+=n[e++]),n[e++]!==4)break;e=Ii(n,e);let r=n[e++];if(r===64)i+=`.`+Li(r);else break;if(e+=12,n[e++]!==5)break;e=Ii(n,e);let a=n[e++],o=(a&248)>>3;o===31&&(o+=1+((a&7)<<3)+((n[e]&224)>>5)),i+=`.`+o}break}case`hvc1`:case`hev1`:{let e=J(n,[`hvcC`])[0];if(e&&e.length>12){let t=e[1],n=[``,`A`,`B`,`C`][t>>6],r=t&31,a=q(e,2),o=(t&32)>>5?`H`:`L`,s=e[12],c=e.subarray(6,12);i+=`.`+n+r,i+=`.`+Fi(a).toString(16).toUpperCase(),i+=`.`+o+s;let l=``;for(let e=c.length;e--;){let t=c[e];(t||l)&&(l=`.`+t.toString(16).toUpperCase()+l)}i+=l}a=Pi(s==`hev1`?`dvhe`:`dvh1`,n);break}case`dvh1`:case`dvhe`:case`dvav`:case`dva1`:case`dav1`:i=Pi(i,n)||i;break;case`vp09`:{let e=J(n,[`vpcC`])[0];if(e&&e.length>6){let t=e[4],n=e[5],r=e[6]>>4&15;i+=`.`+Ri(t)+`.`+Ri(n)+`.`+Ri(r)}break}case`av01`:{let e=J(n,[`av1C`])[0];if(e&&e.length>2){let t=e[1]>>>5,r=e[1]&31,o=e[2]>>>7?`H`:`M`,s=(e[2]&64)>>6,c=(e[2]&32)>>5,l=t===2&&s?c?12:10:s?10:8,u=(e[2]&16)>>4,d=(e[2]&8)>>3,f=(e[2]&4)>>2,p=e[2]&3;i+=`.`+t+`.`+Ri(r)+o+`.`+Ri(l)+`.`+u+`.`+d+f+p+`.`+Ri(1)+`.`+Ri(1)+`.`+Ri(1)+`.0`,a=Pi(`dav1`,n)}break}}return{codec:i,encrypted:o,supplemental:a}}function Pi(e,t){let n=J(t,[`dvvC`]),r=n.length?n[0]:J(t,[`dvcC`])[0];if(r){let t=r[2]>>1&127,n=r[2]<<5&32|r[3]>>3&31;return e+`.`+Ri(t)+`.`+Ri(n)}}function Fi(e){let t=0;for(let n=0;n<32;n++)t|=(e>>n&1)<<31-n;return t>>>0}function Ii(e,t){let n=t+5;for(;e[t++]&128&&t<n;);return t}function Li(e){return(`0`+e.toString(16).toUpperCase()).slice(-2)}function Ri(e){return(e<10?`0`:``)+e}function zi(e,t){if(!e||!t)return;let n=t.keyId;n&&t.isCommonEncryption&&Vi(e,(e,t)=>{let r=e.subarray(8,24);r.some(e=>e!==0)||(G.log(`[eme] Patching keyId in 'enc${t?`a`:`v`}>sinf>>tenc' box: ${li(r)} -> ${li(n)}`),e.set(n,8))})}function Bi(e){let t=[];return Vi(e,e=>t.push(e.subarray(8,24))),t}function Vi(e,t){J(e,[`moov`,`trak`]).forEach(e=>{let n=J(e,[`mdia`,`minf`,`stbl`,`stsd`])[0];if(!n)return;let r=n.subarray(8),i=J(r,[`enca`]),a=i.length>0;a||(i=J(r,[`encv`])),i.forEach(e=>{J(a?e.subarray(28):e.subarray(78),[`sinf`]).forEach(e=>{let n=Hi(e);n&&t(n,a)})})})}function Hi(e){let t=J(e,[`schm`])[0];if(t){let n=Ei(t.subarray(4,8));if(n===`cbcs`||n===`cenc`){let t=J(e,[`schi`,`tenc`])[0];if(t)return t}}}function Ui(e,t,n){let r={},i=J(e,[`moof`,`traf`]);for(let e=0;e<i.length;e++){let a=i[e],o=J(a,[`tfhd`])[0],s=q(o,4),c=t[s];if(!c)continue;r[s]||(r[s]={start:NaN,duration:0,sampleCount:0,timescale:c.timescale,type:c.type});let l=r[s],u=J(a,[`tfdt`])[0];if(u){let e=u[0],t=q(u,4);e===1&&(t===Ci?n.warn(`[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time`):(t*=Ci+1,t+=q(u,8))),L(t)&&(!L(l.start)||t<l.start)&&(l.start=t)}let d=c.default,f=q(o,0)|d?.flags,p=d?.duration||0;f&8&&(p=f&2?q(o,12):q(o,8));let m=J(a,[`trun`]),h=l.start||0,g=0,_=p;for(let e=0;e<m.length;e++){let t=m[e],n=q(t,4),r=l.sampleCount;l.sampleCount+=n;let i=t[3]&1,a=t[3]&4,o=t[2]&1,s=t[2]&2,c=t[2]&4,u=t[2]&8,d=8,f=n;for(i&&(d+=4),a&&n&&(!(t[d+1]&1)&&l.keyFrameIndex===void 0&&(l.keyFrameIndex=r),d+=4,o?(_=q(t,d),d+=4):_=p,s&&(d+=4),u&&(d+=4),h+=_,g+=_,f--);f--;)o?(_=q(t,d),d+=4):_=p,s&&(d+=4),c&&(t[d+1]&1||l.keyFrameIndex===void 0&&(l.keyFrameIndex=l.sampleCount-(f+1),l.keyFrameStart=h),d+=4),u&&(d+=4),h+=_,g+=_;!g&&p&&(g+=p*n)}l.duration+=g}if(!Object.keys(r).some(e=>r[e].duration)){let t=1/0,n=0,i=J(e,[`sidx`]);for(let e=0;e<i.length;e++){let r=ji(i[e]);if(r!=null&&r.references){t=Math.min(t,r.earliestPresentationTime/r.timescale);let e=r.references.reduce((e,t)=>e+t.info.duration||0,0);n=Math.max(n,e+r.earliestPresentationTime/r.timescale)}}n&&L(n)&&Object.keys(r).forEach(e=>{r[e].duration||(r[e].duration=n*r[e].timescale-r[e].start)})}return r}function Wi(e){let t={valid:null,remainder:null},n=J(e,[`moof`]);if(n.length<2)return t.remainder=e,t;let r=n[n.length-1];return t.valid=e.slice(0,r.byteOffset-8),t.remainder=e.slice(r.byteOffset-8),t}function Gi(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}function Ki(e,t){let n=[],r=t.samples,i=t.timescale,a=t.id,o=!1;return J(r,[`moof`]).map(s=>{let c=s.byteOffset-8;J(s,[`traf`]).map(s=>{let l=J(s,[`tfdt`]).map(e=>{let t=e[0],n=q(e,4);return t===1&&(n*=2**32,n+=q(e,8)),n/i})[0];return l!==void 0&&(e=l),J(s,[`tfhd`]).map(l=>{let u=q(l,4),d=q(l,0)&16777215,f=(d&1)!=0,p=(d&2)!=0,m=(d&8)!=0,h=0,g=(d&16)!=0,_=0,v=(d&32)!=0,y=8;u===a&&(f&&(y+=8),p&&(y+=4),m&&(h=q(l,y),y+=4),g&&(_=q(l,y),y+=4),v&&(y+=4),t.type===`video`&&(o=qi(t.codec)),J(s,[`trun`]).map(a=>{let s=a[0],l=q(a,0)&16777215,u=(l&1)!=0,d=0,f=(l&4)!=0,p=(l&256)!=0,m=0,g=(l&512)!=0,v=0,y=(l&1024)!=0,b=(l&2048)!=0,x=0,S=q(a,4),C=8;u&&(d=q(a,C),C+=4),f&&(C+=4);let w=d+c;for(let c=0;c<S;c++){if(p?(m=q(a,C),C+=4):m=h,g?(v=q(a,C),C+=4):v=_,y&&(C+=4),b&&(x=s===0?q(a,C):ki(a,C),C+=4),t.type===K.VIDEO){let t=0;for(;t<v;){let a=q(r,w);w+=4,Ji(o,r[w])&&Yi(r.subarray(w,w+a),o?2:1,e+x/i,n),w+=a,t+=a+4}}e+=m/i}}))})})}),n}function qi(e){if(!e)return!1;let t=e.substring(0,4);return t===`hvc1`||t===`hev1`||t===`dvh1`||t===`dvhe`}function Ji(e,t){if(e){let e=t>>1&63;return e===39||e===40}else return(t&31)==6}function Yi(e,t,n,r){let i=Xi(e),a=0;a+=t;let o=0,s=0,c=0;for(;a<i.length;){o=0;do{if(a>=i.length)break;c=i[a++],o+=c}while(c===255);s=0;do{if(a>=i.length)break;c=i[a++],s+=c}while(c===255);let e=i.length-a,t=a;if(s<e)a+=s;else if(s>e){G.error(`Malformed SEI payload. ${s} is too small, only ${e} bytes left to parse.`);break}if(o===4){if(i[t++]===181){let e=Di(i,t);if(t+=2,e===49){let e=q(i,t);if(t+=4,e===1195456820){let e=i[t++];if(e===3){let a=i[t++],s=31&a,c=64&a,l=c?2+s*3:0,u=new Uint8Array(l);if(c){u[0]=a;for(let e=1;e<l;e++)u[e]=i[t++]}r.push({type:e,payloadType:o,pts:n,bytes:u})}}}}}else if(o===5&&s>16){let e=[];for(let n=0;n<16;n++){let r=i[t++].toString(16);e.push(r.length==1?`0`+r:r),(n===3||n===5||n===7||n===9)&&e.push(`-`)}let a=s-16,c=new Uint8Array(a);for(let e=0;e<a;e++)c[e]=i[t++];r.push({payloadType:o,pts:n,uuid:e.join(``),userData:ci(c),userDataBytes:c})}}}function Xi(e){let t=e.byteLength,n=[],r=1;for(;r<t-2;)e[r]===0&&e[r+1]===0&&e[r+2]===3?(n.push(r+2),r+=2):r++;if(n.length===0)return e;let i=t-n.length,a=new Uint8Array(i),o=0;for(r=0;r<i;o++,r++)o===n[0]&&(o++,n.shift()),a[r]=e[o];return a}function Zi(e){let t=e[0],n=``,r=``,i=0,a=0,o=0,s=0,c=0,l=0;if(t===0){for(;Ei(e.subarray(l,l+1))!==`\0`;)n+=Ei(e.subarray(l,l+1)),l+=1;for(n+=Ei(e.subarray(l,l+1)),l+=1;Ei(e.subarray(l,l+1))!==`\0`;)r+=Ei(e.subarray(l,l+1)),l+=1;r+=Ei(e.subarray(l,l+1)),l+=1,i=q(e,12),a=q(e,16),s=q(e,20),c=q(e,24),l=28}else if(t===1){l+=4,i=q(e,l),l+=4;let t=q(e,l);l+=4;let a=q(e,l);for(l+=4,o=2**32*t+a,Ur(o)||(o=2**53-1,G.warn(`Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box`)),s=q(e,l),l+=4,c=q(e,l),l+=4;Ei(e.subarray(l,l+1))!==`\0`;)n+=Ei(e.subarray(l,l+1)),l+=1;for(n+=Ei(e.subarray(l,l+1)),l+=1;Ei(e.subarray(l,l+1))!==`\0`;)r+=Ei(e.subarray(l,l+1)),l+=1;r+=Ei(e.subarray(l,l+1)),l+=1}let u=e.subarray(l,e.byteLength);return{schemeIdUri:n,value:r,timeScale:i,presentationTime:o,presentationTimeDelta:a,eventDuration:s,id:c,payload:u}}function Qi(e,...t){let n=t.length,r=8,i=n;for(;i--;)r+=t[i].byteLength;let a=new Uint8Array(r);for(a[0]=r>>24&255,a[1]=r>>16&255,a[2]=r>>8&255,a[3]=r&255,a.set(e,4),i=0,r=8;i<n;i++)a.set(t[i],r),r+=t[i].byteLength;return a}function $i(e,t,n){if(e.byteLength!==16)throw RangeError(`Invalid system id`);let r,i;r=0,i=new Uint8Array;let a;r>0?(a=new Uint8Array(4),t.length>0&&new DataView(a.buffer).setUint32(0,t.length,!1)):a=new Uint8Array;let o=new Uint8Array(4);return n.byteLength>0&&new DataView(o.buffer).setUint32(0,n.byteLength,!1),Qi([112,115,115,104],new Uint8Array([r,0,0,0]),e,a,i,o,n)}function ea(e){let t=[];if(e instanceof ArrayBuffer){let n=e.byteLength,r=0;for(;r+32<n;){let n=ta(new DataView(e,r));t.push(n),r+=n.size}}return t}function ta(e){let t=e.getUint32(0),n=e.byteOffset,r=e.byteLength;if(r<t)return{offset:n,size:r};if(e.getUint32(4)!==1886614376)return{offset:n,size:t};let i=e.getUint32(8)>>>24;if(i!==0&&i!==1)return{offset:n,size:t};let a=e.buffer,o=li(new Uint8Array(a,n+12,16)),s=null,c=null,l=0;if(i===0)l=28;else{let i=e.getUint32(28);if(!i||r<32+i*16)return{offset:n,size:t};s=[];for(let e=0;e<i;e++)s.push(new Uint8Array(a,n+32+e*16,16));l=32+i*16}if(!l)return{offset:n,size:t};let u=e.getUint32(l);return t-32<u?{offset:n,size:t}:(c=new Uint8Array(a,n+l+4,u),{version:i,systemId:o,kids:s,data:c,offset:n,size:t})}var na=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),ra={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function ia(e,t){let n=ra[t];return!!n&&!!n[e.slice(0,4)]}function aa(e,t,n=!0){return!e.split(`,`).some(e=>!oa(e,t,n))}function oa(e,t,n=!0){return ai(n)?.isTypeSupported(sa(e,t))??!1}function sa(e,t){return`${t}/mp4;codecs=${e}`}function ca(e){if(e){let t=e.substring(0,4);return ra.video[t]}return 2}function la(e){let t=na();return e.split(`,`).reduce((e,n)=>{let r=t&&qi(n)?9:ra.video[n];return r?(r*2+e)/(e?3:2):(ra.audio[n]+e)/(e?2:1)},0)}var ua={};function da(e,t=!0){if(ua[e])return ua[e];let n={flac:[`flac`,`fLaC`,`FLAC`],opus:[`opus`,`Opus`],"mp4a.40.34":[`mp3`]}[e];for(let i=0;i<n.length;i++){var r;if(oa(n[i],`audio`,t))return ua[e]=n[i],n[i];if(n[i]===`mp3`&&(r=ai(t))!=null&&r.isTypeSupported(`audio/mpeg`))return``}return e}var fa=/flac|opus|mp4a\.40\.34/i;function pa(e,t=!0){return e.replace(fa,e=>da(e.toLowerCase(),t))}function ma(e,t){let n=[];if(e){let t=e.split(`,`);for(let e=0;e<t.length;e++)ia(t[e],`video`)||n.push(t[e])}return t&&n.push(t),n.join(`,`)}function ha(e,t){if(e&&(e.length>4||[`ac-3`,`ec-3`,`alac`,`fLaC`,`Opus`].indexOf(e)!==-1)&&(ga(e,`audio`)||ga(e,`video`)))return e;if(t){let n=t.split(`,`);if(n.length>1){if(e){for(let t=n.length;t--;)if(n[t].substring(0,4)===e.substring(0,4))return n[t]}return n[0]}}return t||e}function ga(e,t){return ia(e,t)&&oa(e,t)}function _a(e){let t=e.split(`,`);for(let e=0;e<t.length;e++){let n=t[e].split(`.`);n.length>2&&n[0]===`avc1`&&(t[e]=`avc1.${parseInt(n[1]).toString(16)}${(`000`+parseInt(n[2]).toString(16)).slice(-4)}`)}return t.join(`,`)}function va(e){if(e.startsWith(`av01.`)){let t=e.split(`.`),n=[`0`,`111`,`01`,`01`,`01`,`0`];for(let e=t.length;e>4&&e<10;e++)t[e]=n[e-4];return t.join(`.`)}return e}function ya(e){let t=ai(e)||{isTypeSupported:()=>!1};return{mpeg:t.isTypeSupported(`audio/mpeg`),mp3:t.isTypeSupported(`audio/mp4; codecs="mp3"`),ac3:t.isTypeSupported(`audio/mp4; codecs="ac-3"`)}}function ba(e){return e.replace(/^.+codecs=["']?([^"']+).*$/,`$1`)}var xa={supported:!0,powerEfficient:!0,smooth:!0},Sa={supported:!1,smooth:!1,powerEfficient:!1},Ca={supported:!0,configurations:[],decodingInfoResults:[xa]};function wa(e,t){return{supported:!1,configurations:t,decodingInfoResults:[Sa],error:e}}function Ta(e,t,n,r,i,a){let o=e.videoCodec,s=e.audioCodec?e.audioGroups:null,c=a?.audioCodec,l=a?.channels,u=l?parseInt(l):c?1/0:2,d=null;if(s!=null&&s.length)try{d=s.length===1&&s[0]?t.groups[s[0]].channels:s.reduce((e,n)=>{if(n){let r=t.groups[n];if(!r)throw Error(`Audio track group ${n} not found`);Object.keys(r.channels).forEach(t=>{e[t]=(e[t]||0)+r.channels[t]})}return e},{2:0})}catch{return!0}return o!==void 0&&(o.split(`,`).some(e=>qi(e))||e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(r,30)||e.videoRange!==`SDR`&&e.videoRange!==n||e.bitrate>Math.max(i,8e6))||!!d&&L(u)&&Object.keys(d).some(e=>parseInt(e)>u)}function Ea(e,t,n,r={}){let i=e.videoCodec;if(!i&&!e.audioCodec||!n)return Promise.resolve(Ca);let a=[],o=Da(e),s=o.length,c=Oa(e,t,s>0),l=c.length;for(let e=s||1*l||1;e--;){let t={type:`media-source`};if(s&&(t.video=o[e%s]),l){t.audio=c[e%l];let n=t.audio.bitrate;t.video&&n&&(t.video.bitrate-=n)}a.push(t)}if(i){let e=navigator.userAgent;if(i.split(`,`).some(e=>qi(e))&&na())return Promise.resolve(wa(Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${e})`),a))}return Promise.all(a.map(e=>{let t=ja(e);return r[t]||(r[t]=n.decodingInfo(e))})).then(e=>({supported:!e.some(e=>!e.supported),configurations:a,decodingInfoResults:e})).catch(e=>({supported:!1,configurations:a,decodingInfoResults:[],error:e}))}function Da(e){let t=e.videoCodec?.split(`,`),n=Aa(e),r=e.width||640,i=e.height||480,a=e.frameRate||30,o=e.videoRange.toLowerCase();return t?t.map(e=>{let t={contentType:sa(va(e),`video`),width:r,height:i,bitrate:n,framerate:a};return o!==`sdr`&&(t.transferFunction=o),t}):[]}function Oa(e,t,n){let r=e.audioCodec?.split(`,`),i=Aa(e);return r&&e.audioGroups?e.audioGroups.reduce((e,a)=>{let o=a?t.groups[a]?.tracks:null;return o?o.reduce((e,t)=>{if(t.groupId===a){let a=parseFloat(t.channels||``);r.forEach(t=>{let r={contentType:sa(t,`audio`),bitrate:n?ka(t,i):i};a&&(r.channels=``+a),e.push(r)})}return e},e):e},[]):[]}function ka(e,t){if(t<=1)return 1;let n=128e3;return e===`ec-3`?n=768e3:e===`ac-3`&&(n=64e4),Math.min(t/2,n)}function Aa(e){return Math.ceil(Math.max(e.bitrate*.9,e.averageBitrate)/1e3)*1e3||1}function ja(e){let t=``,{audio:n,video:r}=e;if(r){let e=ba(r.contentType);t+=`${e}_r${r.height}x${r.width}f${Math.ceil(r.framerate)}${r.transferFunction||`sd`}_${Math.ceil(r.bitrate/1e5)}`}if(n){let e=ba(n.contentType);t+=`${r?`_`:``}${e}_c${n.channels}`}return t}var Ma=[`NONE`,`TYPE-0`,`TYPE-1`,null];function Na(e){return Ma.indexOf(e)>-1}var Pa=[`SDR`,`PQ`,`HLG`];function Fa(e){return!!e&&Pa.indexOf(e)>-1}var Ia={No:``,Yes:`YES`,v2:`v2`};function La(e){let{canSkipUntil:t,canSkipDateRanges:n,age:r}=e,i=r<t/2;return t&&i?n?Ia.v2:Ia.Yes:Ia.No}var Ra=class{constructor(e,t,n){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=n}addDirectives(e){let t=new self.URL(e);return this.msn!==void 0&&t.searchParams.set(`_HLS_msn`,this.msn.toString()),this.part!==void 0&&t.searchParams.set(`_HLS_part`,this.part.toString()),this.skip&&t.searchParams.set(`_HLS_skip`,this.skip),t.href}},za=class{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat(`FRAME-RATE`,0),this._avgBitrate=e.attrs.decimalInteger(`AVERAGE-BANDWIDTH`),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter(e=>!!e).map(e=>e.substring(0,4)).join(`,`),`supplemental`in e){this.supplemental=e.supplemental;let t=e.supplemental?.videoCodec;t&&t!==e.videoCodec&&(this.codecSet+=`,${t.substring(0,4)}`)}this.addGroupId(`audio`,e.attrs.AUDIO),this.addGroupId(`text`,e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||``}get pathwayId(){return this.attrs[`PATHWAY-ID`]||`.`}get videoRange(){return this.attrs[`VIDEO-RANGE`]||`SDR`}get score(){return this.attrs.optionalFloat(`SCORE`,0)}get uri(){return this.url[0]||``}hasAudioGroup(e){return Ba(this._audioGroups,e)}hasSubtitleGroup(e){return Ba(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e===`audio`){let e=this._audioGroups;e||=this._audioGroups=[],e.indexOf(t)===-1&&e.push(t)}else if(e===`text`){let e=this._subtitleGroups;e||=this._subtitleGroups=[],e.indexOf(t)===-1&&e.push(t)}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){return this.audioGroups?.[0]}get textGroupId(){return this.subtitleGroups?.[0]}addFallback(){}};function Ba(e,t){return!t||!e?!1:e.indexOf(t)!==-1}function Va(){if(typeof matchMedia==`function`){let e=matchMedia(`(dynamic-range: high)`),t=matchMedia(`bad query`);if(e.media!==t.media)return e.matches===!0}return!1}function Ha(e,t){let n=!1,r=[];if(e&&(n=e!==`SDR`,r=[e]),t){r=t.allowedVideoRanges||Pa.slice(0);let e=r.join(``)!==`SDR`&&!t.videoCodec;n=t.preferHDR===void 0?e&&Va():t.preferHDR,n||(r=[`SDR`])}return{preferHDR:n,allowedVideoRanges:r}}var Ua=e=>{let t=new WeakSet;return(n,r)=>{if(e&&(r=e(n,r)),typeof r==`object`&&r){if(t.has(r))return;t.add(r)}return r}},Y=(e,t)=>JSON.stringify(e,Ua(t));function Wa(e,t,n,r,i){let a=Object.keys(e),o=r?.channels,s=r?.audioCodec,c=i?.videoCodec,l=o&&parseInt(o)===2,u=!1,d=!1,f=1/0,p=1/0,m=1/0,h=1/0,g=0,_=[],{preferHDR:v,allowedVideoRanges:y}=Ha(t,i);for(let t=a.length;t--;){let n=e[a[t]];u||=n.channels[2]>0,f=Math.min(f,n.minHeight),p=Math.min(p,n.minFramerate),m=Math.min(m,n.minBitrate),y.filter(e=>n.videoRanges[e]>0).length>0&&(d=!0)}f=L(f)?f:0,p=L(p)?p:0;let b=Math.max(1080,f),x=Math.max(30,p);m=L(m)?m:n,n=Math.max(m,n),d||(t=void 0);let S=a.length>1;return{codecSet:a.reduce((t,r)=>{let i=e[r];if(r===t)return t;if(_=d?y.filter(e=>i.videoRanges[e]>0):[],S){if(i.minBitrate>n)return Ga(r,`min bitrate of ${i.minBitrate} > current estimate of ${n}`),t;if(!i.hasDefaultAudio)return Ga(r,`no renditions with default or auto-select sound found`),t;if(s&&r.indexOf(s.substring(0,4))%5!=0)return Ga(r,`audio codec preference "${s}" not found`),t;if(o&&!l){if(!i.channels[o])return Ga(r,`no renditions with ${o} channel sound found (channels options: ${Object.keys(i.channels)})`),t}else if((!s||l)&&u&&i.channels[2]===0)return Ga(r,`no renditions with stereo sound found`),t;if(i.minHeight>b)return Ga(r,`min resolution of ${i.minHeight} > maximum of ${b}`),t;if(i.minFramerate>x)return Ga(r,`min framerate of ${i.minFramerate} > maximum of ${x}`),t;if(!_.some(e=>i.videoRanges[e]>0))return Ga(r,`no variants with VIDEO-RANGE of ${Y(_)} found`),t;if(c&&r.indexOf(c.substring(0,4))%5!=0)return Ga(r,`video codec preference "${c}" not found`),t;if(i.maxScore<g)return Ga(r,`max score of ${i.maxScore} < selected max of ${g}`),t}return t&&(la(r)>=la(t)||i.fragmentError>e[t].fragmentError)?t:(h=i.minIndex,g=i.maxScore,r)},void 0),videoRanges:_,preferHDR:v,minFramerate:p,minBitrate:m,minIndex:h}}function Ga(e,t){G.log(`[abr] start candidates with "${e}" ignored because ${t}`)}function Ka(e){return e.reduce((e,t)=>{let n=e.groups[t.groupId];n||=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1},n.tracks.push(t);let r=t.channels||`2`;return n.channels[r]=(n.channels[r]||0)+1,n.hasDefault=n.hasDefault||t.default,n.hasAutoSelect=n.hasAutoSelect||t.autoselect,n.hasDefault&&(e.hasDefaultAudio=!0),n.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function qa(e,t,n,r){return e.slice(n,r+1).reduce((e,n,r)=>{if(!n.codecSet)return e;let i=n.audioGroups,a=e[n.codecSet];a||(e[n.codecSet]=a={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:r,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!i,fragmentError:0}),a.minBitrate=Math.min(a.minBitrate,n.bitrate);let o=Math.min(n.height,n.width);return a.minHeight=Math.min(a.minHeight,o),a.minFramerate=Math.min(a.minFramerate,n.frameRate),a.minIndex=Math.min(a.minIndex,r),a.maxScore=Math.max(a.maxScore,n.score),a.fragmentError+=n.fragmentError,a.videoRanges[n.videoRange]=(a.videoRanges[n.videoRange]||0)+1,i&&i.forEach(e=>{if(!e)return;let n=t.groups[e];n&&(a.hasDefaultAudio=a.hasDefaultAudio||t.hasDefaultAudio?n.hasDefault:n.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(n.channels).forEach(e=>{a.channels[e]=(a.channels[e]||0)+n.channels[e]}))}),e},{})}function Ja(e){if(!e)return e;let{lang:t,assocLang:n,characteristics:r,channels:i,audioCodec:a}=e;return{lang:t,assocLang:n,characteristics:r,channels:i,audioCodec:a}}function Ya(e,t,n){if(`attrs`in e){let n=t.indexOf(e);if(n!==-1)return n}for(let r=0;r<t.length;r++){let i=t[r];if(Xa(e,i,n))return r}return-1}function Xa(e,t,n){let{groupId:r,name:i,lang:a,assocLang:o,default:s}=e,c=e.forced;return(r===void 0||t.groupId===r)&&(i===void 0||t.name===i)&&(a===void 0||Za(a,t.lang))&&(a===void 0||t.assocLang===o)&&(s===void 0||t.default===s)&&(c===void 0||t.forced===c)&&(!(`characteristics`in e)||Qa(e.characteristics||``,t.characteristics))&&(n===void 0||n(e,t))}function Za(e,t=`--`){return e.length===t.length?e===t:e.startsWith(t)||t.startsWith(e)}function Qa(e,t=``){let n=e.split(`,`),r=t.split(`,`);return n.length===r.length&&!n.some(e=>r.indexOf(e)===-1)}function $a(e,t){let{audioCodec:n,channels:r}=e;return(n===void 0||(t.audioCodec||``).substring(0,4)===n.substring(0,4))&&(r===void 0||r===(t.channels||`2`))}function eo(e,t,n,r,i){let a=t[r],o=t.reduce((e,t,n)=>{let r=t.uri;return(e[r]||(e[r]=[])).push(n),e},{})[a.uri];o.length>1&&(r=Math.max.apply(Math,o));let s=a.videoRange,c=a.frameRate,l=a.codecSet.substring(0,4),u=to(t,r,t=>{if(t.videoRange!==s||t.frameRate!==c||t.codecSet.substring(0,4)!==l)return!1;let r=t.audioGroups;return Ya(e,n.filter(e=>!r||r.indexOf(e.groupId)!==-1),i)>-1});return u>-1?u:to(t,r,t=>{let r=t.audioGroups;return Ya(e,n.filter(e=>!r||r.indexOf(e.groupId)!==-1),i)>-1})}function to(e,t,n){for(let r=t;r>-1;r--)if(n(e[r]))return r;for(let r=t+1;r<e.length;r++)if(n(e[r]))return r;return-1}function no(e,t){return!!e&&e!==t.loadLevelObj?.uri}var ro=class extends Zr{constructor(e){super(`abr`,e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey=``,this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=e=>{let{fragCurrent:t,partCurrent:n,hls:r}=this,{autoLevelEnabled:i,media:a}=r;if(!t||!a)return;let o=performance.now(),s=n?n.stats:t.stats,c=n?n.duration:t.duration,l=o-s.loading.start,u=r.minAutoLevel,d=t.level,f=this._nextAutoLevel;if(s.aborted||s.loaded&&s.loaded===s.total||d<=u){this.clearTimer(),this._nextAutoLevel=-1;return}if(!i)return;let p=f>-1&&f!==d,m=!!e||p;if(!m&&(a.paused||!a.playbackRate||!a.readyState))return;let h=r.mainForwardBufferInfo;if(!m&&h===null)return;let g=this.bwEstimator.getEstimateTTFB(),_=Math.abs(a.playbackRate);if(l<=Math.max(g,1e3*(c/(_*2))))return;let v=h?h.len/_:0,y=s.loading.first?s.loading.first-s.loading.start:-1,b=s.loaded&&y>-1,x=this.getBwEstimate(),S=r.levels,C=S[d],w=Math.max(s.loaded,Math.round(c*(t.bitrate||C.averageBitrate)/8)),T=b?l-y:l;T<1&&b&&(T=Math.min(l,s.loaded*8/x));let E=b?s.loaded*1e3/T:0,ee=g/1e3,D=E?(w-s.loaded)/E:w*8/x+ee;if(D<=v)return;let te=E?E*8:x,ne=(e?.details||this.hls.latestLevelDetails)?.live===!0,O=this.hls.config.abrBandWidthUpFactor,k=1/0,re;for(re=d-1;re>u;re--){let e=S[re].maxBitrate,t=!S[re].details||ne;if(k=this.getTimeToLoadFrag(ee,te,c*e,t),k<Math.min(v,c+ee))break}if(k>=D||k>c*10)return;b?this.bwEstimator.sample(l-Math.min(g,y),s.loaded):this.bwEstimator.sampleTTFB(l);let ie=S[re].maxBitrate;this.getBwEstimate()*O>ie&&this.resetEstimator(ie);let ae=this.findBestLevel(ie,u,re,0,v,1,1);ae>-1&&(re=ae),this.warn(`Fragment ${t.sn}${n?` part `+n.index:``} of level ${d} is loading too slowly;
3
+ Fragment duration: ${t.duration.toFixed(3)}
4
+ Time to underbuffer: ${v.toFixed(3)} s
5
+ Estimated load time for current fragment: ${D.toFixed(3)} s
6
+ Estimated load time for down switch fragment: ${k.toFixed(3)} s
7
+ TTFB estimate: ${y|0} ms
8
+ Current BW estimate: ${L(x)?x|0:`Unknown`} bps
9
9
  New BW estimate: ${this.getBwEstimate()|0} bps
10
- Switching to level ${W} @ ${k|0} bps`),a.nextLoadLevel=a.nextAutoLevel=W,this.clearTimer();const q=()=>{if(this.clearTimer(),this.fragCurrent===i&&this.hls.loadLevel===W&&W>0){const Z=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${W>0?"and switching down":""}
11
- Fragment duration: ${i.duration.toFixed(3)} s
12
- Time to underbuffer: ${Z.toFixed(3)} s`),i.abortRequests(),this.fragCurrent=this.partCurrent=null,W>g){let X=this.findBestLevel(this.hls.levels[g].bitrate,g,W,0,Z,1,1);X===-1&&(X=g),this.hls.nextLoadLevel=this.hls.nextAutoLevel=X,this.resetEstimator(this.hls.levels[X].bitrate)}}};y||N>B*2?q():this.timer=self.setInterval(q,B*1e3),a.trigger(m.FRAG_LOAD_EMERGENCY_ABORTED,{frag:i,part:n,stats:u})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new zh(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.FRAG_LOADING,this.onFragLoading,this),e.on(m.FRAG_LOADED,this.onFragLoaded,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this),e.on(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(m.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.FRAG_LOADING,this.onFragLoading,this),e.off(m.FRAG_LOADED,this.onFragLoaded,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this),e.off(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(m.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(m.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const s=t.frag;if(!this.ignoreFragment(s)){if(!s.bitrateTest){var i;this.fragCurrent=s,this.partCurrent=(i=t.part)!=null?i:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case R.BUFFER_ADD_CODEC_ERROR:case R.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case R.FRAG_LOAD_TIMEOUT:{const s=t.frag,{fragCurrent:i,partCurrent:n}=this;if(s&&i&&s.sn===i.sn&&s.level===i.level){const a=performance.now(),o=n?n.stats:s.stats,c=a-o.loading.start,l=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&l>-1){const h=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(c-Math.min(h,l),o.loaded)}else this.bwEstimator.sampleTTFB(c)}break}}}getTimeToLoadFrag(e,t,s,i){const n=e+s/t,a=i?e+this.lastLevelLoadSec:0;return n+a}onLevelLoaded(e,t){const s=this.hls.config,{loading:i}=t.stats,n=i.end-i.first;$(n)&&(this.lastLevelLoadSec=n/1e3),t.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:s}){const i=s?s.stats:t.stats;if(t.type===G.MAIN&&this.bwEstimator.sampleTTFB(i.loading.first-i.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const n=s?s.duration:t.duration,a=this.hls.levels[t.level],o=(a.loaded?a.loaded.bytes:0)+i.loaded,c=(a.loaded?a.loaded.duration:0)+n;a.loaded={bytes:o,duration:c},a.realBitrate=Math.round(8*o/c)}if(t.bitrateTest){const n={stats:i,frag:t,part:s,id:t.type};this.onFragBuffered(m.FRAG_BUFFERED,n),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:s,part:i}=t,n=i!=null&&i.stats.loaded?i.stats:s.stats;if(n.aborted||this.ignoreFragment(s))return;const a=n.parsing.end-n.loading.start-Math.min(n.loading.first-n.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,n.loaded),n.bwEstimate=this.getBwEstimate(),s.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==G.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,s=this.getBwEstimate(),i=this.hls.config.maxStarvationDelay,n=this.findBestLevel(s,t,e,0,i,1,1);if(n>-1)return n;const a=this.hls.firstLevel,o=Math.min(Math.max(a,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${a} clamped to ${o}`),o}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,s=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(e!==-1&&(!s||!i||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const n=s&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const a=this.hls.levels;if(a.length>Math.max(e,n)&&a[e].loadError<=a[n].loadError)return e}return this._nextAutoLevel=n,this.nextAutoLevelKey=this.getAutoLevelKey(),n}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:s}=this;if(s.levels.length<=1)return s.loadLevel;const{maxAutoLevel:i,config:n,minAutoLevel:a}=s,o=t?t.duration:e?e.duration:0,c=this.getBwEstimate(),l=this.getStarvationDelay();let u=n.abrBandWidthFactor,h=n.abrBandWidthUpFactor;if(l){const y=this.findBestLevel(c,a,i,l,0,u,h);if(y>=0)return this.rebufferNotice=-1,y}let d=o?Math.min(o,n.maxStarvationDelay):n.maxStarvationDelay;if(!l){const y=this.bitrateTestDelay;y&&(d=(o?Math.min(o,n.maxLoadingDelay):n.maxLoadingDelay)-y,this.info(`bitrate test took ${Math.round(1e3*y)}ms, set first fragment max fetchDuration to ${Math.round(1e3*d)} ms`),u=h=1)}const g=this.findBestLevel(c,a,i,l,d,u,h);if(this.rebufferNotice!==g&&(this.rebufferNotice=g,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${g}`)),g>-1)return g;const f=s.levels[a],p=s.loadLevelObj;return p&&f?.bitrate<p.bitrate?a:s.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const s=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,i=e.mainForwardBufferInfo;return(i?i.len:0)/s}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,s,i,n,a,o){var c;const l=i+n,u=this.lastLoadedFragLevel,h=u===-1?this.hls.firstLevel:u,{fragCurrent:d,partCurrent:g}=this,{levels:f,allAudioTracks:p,loadLevel:y,config:v}=this.hls;if(f.length===1)return 0;const E=f[h],T=!!((c=this.hls.latestLevelDetails)!=null&&c.live),S=y===-1||u===-1;let _,D="SDR",I=E?.frameRate||0;const{audioPreference:b,videoPreference:A}=v,x=this.audioTracksByGroup||(this.audioTracksByGroup=Mo(p));let C=-1;if(S){if(this.firstSelection!==-1)return this.firstSelection;const w=this.codecTiers||(this.codecTiers=Gd(f,x,t,s)),U=Ud(w,D,e,b,A),{codecSet:F,videoRanges:B,minFramerate:W,minBitrate:k,minIndex:O,preferHDR:q}=U;C=O,_=F,D=q?B[B.length-1]:B[0],I=W,e=Math.max(e,k),this.log(`picked start tier ${ue(U)}`)}else _=E?.codecSet,D=E?.videoRange;const M=g?g.duration:d?d.duration:0,K=this.bwEstimator.getEstimateTTFB()/1e3,V=[];for(let w=s;w>=t;w--){var N;const U=f[w],F=w>h;if(!U)continue;if(v.useMediaCapabilities&&!U.supportedResult&&!U.supportedPromise){const X=navigator.mediaCapabilities;typeof X?.decodingInfo=="function"&&Cd(U,x,D,I,e,b)?(U.supportedPromise=Co(U,x,X,this.supportedCache),U.supportedPromise.then(z=>{if(!this.hls)return;U.supportedResult=z;const Se=this.hls.levels,ve=Se.indexOf(U);z.error?this.warn(`MediaCapabilities decodingInfo error: "${z.error}" for level ${ve} ${ue(z)}`):z.supported?z.decodingInfoResults.some(Ne=>Ne.smooth===!1||Ne.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${ve} not smooth or powerEfficient: ${ue(z)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${ve} ${ue(z)}`),ve>-1&&Se.length>1&&(this.log(`Removing unsupported level ${ve}`),this.hls.removeLevel(ve),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(z=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${z}`)})):U.supportedResult=bo}if((_&&U.codecSet!==_||D&&U.videoRange!==D||F&&I>U.frameRate||!F&&I>0&&I<U.frameRate||(N=U.supportedResult)!=null&&(N=N.decodingInfoResults)!=null&&N.some(X=>X.smooth===!1))&&(!S||w!==C)){V.push(w);continue}const B=U.details,W=(g?B?.partTarget:B?.averagetargetduration)||M;let k;F?k=o*e:k=a*e;const O=M&&i>=M*2&&n===0?U.averageBitrate:U.maxBitrate,q=this.getTimeToLoadFrag(K,k,O*W,B===void 0);if(k>=O&&(w===u||U.loadError===0&&U.fragmentError===0)&&(q<=K||!$(q)||T&&!this.bitrateTestDelay||q<l)){const X=this.forcedAutoLevel;return w!==y&&(X===-1||X!==y)&&(V.length&&this.trace(`Skipped level(s) ${V.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${f[V[0]].codecs}" ${f[V[0]].videoRange}; not compatible with "${_}" ${D}`),this.info(`switch candidate:${h}->${w} adjustedbw(${Math.round(k)})-bitrate=${Math.round(k-O)} ttfb:${K.toFixed(1)} avgDuration:${W.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${q.toFixed(1)} firstSelection:${S} codecSet:${U.codecSet} videoRange:${U.videoRange} hls.loadLevel:${y}`)),S&&(this.firstSelection=w),w}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:s}=this.hls;return Math.min(Math.max(e,s),t)}}const $o={search:function(r,e){let t=0,s=r.length-1,i=null,n=null;for(;t<=s;){i=(t+s)/2|0,n=r[i];const a=e(n);if(a>0)t=i+1;else if(a<0)s=i-1;else return n}return null}};function Yd(r,e,t){if(e===null||!Array.isArray(r)||!r.length||!$(e))return null;const s=r[0].programDateTime;if(e<(s||0))return null;const i=r[r.length-1].endProgramDateTime;if(e>=(i||0))return null;for(let n=0;n<r.length;++n){const a=r[n];if(jd(e,t,a))return a}return null}function gs(r,e,t=0,s=0,i=.005){let n=null;if(r){n=e[1+r.sn-e[0].sn]||null;const o=r.endDTS-t;o>0&&o<15e-7&&(t+=15e-7),n&&r.level!==n.level&&n.end<=r.end&&(n=e[2+r.sn-e[0].sn]||null)}else t===0&&e[0].start===0&&(n=e[0]);if(n&&((!r||r.level===n.level)&&Bo(t,s,n)===0||qd(n,r,Math.min(i,s))))return n;const a=$o.search(e,Bo.bind(null,t,s));return a&&(a!==r||!n)?a:n}function qd(r,e,t){if(e&&e.start===0&&e.level<r.level&&(e.endPTS||0)>0){const s=e.tagList.reduce((i,n)=>(n[0]==="INF"&&(i+=parseFloat(n[1])),i),t);return r.start<=s}return!1}function Bo(r=0,e=0,t){if(t.start<=r&&t.start+t.duration>r)return 0;const s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-s<=r?1:t.start-s>r&&t.start?-1:0}function jd(r,e,t){const s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-s>r}function Uo(r,e,t){if(r&&r.startCC<=e&&r.endCC>=e){let s=r.fragments;const{fragmentHint:i}=r;i&&(s=s.concat(i));let n;return $o.search(s,a=>a.cc<e?1:a.cc>e?-1:(n=a,a.end<=t?1:a.start>t?-1:0)),n||null}return null}function Gi(r){switch(r.details){case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_TIMEOUT:case R.LEVEL_LOAD_TIMEOUT:case R.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Go(r){return r.details.startsWith("key")}function Ko(r){return Go(r)&&!!r.frag&&!r.frag.decryptdata}function Vo(r,e){const t=Gi(e);return r.default[`${t?"timeout":"error"}Retry`]}function Xr(r,e){const t=r.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*r.retryDelayMs,r.maxRetryDelayMs)}function Ho(r){return ae(ae({},r),{errorRetry:null,timeoutRetry:null})}function Ki(r,e,t,s){if(!r)return!1;const i=s?.code,n=e<r.maxNumRetry&&(Xd(i)||!!t);return r.shouldRetry?r.shouldRetry(r,e,t,s,n):n}function Xd(r){return zr(r)||!!r&&(r<400||r>499)}function zr(r){return r===0&&navigator.onLine===!1}var ke={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},Xe={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4};class zd extends rt{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(m.ERROR,this.onError,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(m.ERROR,this.onError,this),e.off(m.ERROR,this.onErrorOut,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return e?.type===G.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;const t=this.hls,s=t.currentLevel;return(e=t.loadLevelObj)!=null&&e.details||s===-1?t.loadLevel:s}variantHasKey(e,t){if(e){var s;if((s=e.details)!=null&&s.hasKey(t))return!0;const i=e.audioGroups;if(i)return this.hls.allAudioTracks.filter(a=>i.indexOf(a.groupId)>=0).some(a=>{var o;return(o=a.details)==null?void 0:o.hasKey(t)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var s;if(t.fatal)return;const i=this.hls,n=t.context;switch(t.details){case R.FRAG_LOAD_ERROR:case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_ERROR:case R.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case R.FRAG_PARSING_ERROR:if((s=t.frag)!=null&&s.gap){t.errorAction=Ms();return}case R.FRAG_GAP:case R.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=ke.SendAlternateToPenaltyBox;return}case R.LEVEL_EMPTY_ERROR:case R.LEVEL_PARSING_ERROR:{var a;const c=t.parent===G.MAIN?t.level:i.loadLevel;t.details===R.LEVEL_EMPTY_ERROR&&((a=t.context)!=null&&(a=a.levelDetails)!=null&&a.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,c):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,c))}return;case R.LEVEL_LOAD_ERROR:case R.LEVEL_LOAD_TIMEOUT:typeof n?.level=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.level));return;case R.AUDIO_TRACK_LOAD_ERROR:case R.AUDIO_TRACK_LOAD_TIMEOUT:case R.SUBTITLE_LOAD_ERROR:case R.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){const c=i.loadLevelObj;if(c&&(n.type===ee.AUDIO_TRACK&&c.hasAudioGroup(n.groupId)||n.type===ee.SUBTITLE_TRACK&&c.hasSubtitleGroup(n.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.loadLevel),t.errorAction.action=ke.SendAlternateToPenaltyBox,t.errorAction.flags=Xe.MoveAllAlternatesMatchingHost;return}}return;case R.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:ke.SendAlternateToPenaltyBox,flags:Xe.MoveAllAlternatesMatchingHDCP};return;case R.KEY_SYSTEM_SESSION_UPDATE_FAILED:case R.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case R.KEY_SYSTEM_NO_SESSION:t.errorAction={action:ke.SendAlternateToPenaltyBox,flags:Xe.MoveAllAlternatesMatchingKey};return;case R.BUFFER_ADD_CODEC_ERROR:case R.REMUX_ALLOC_ERROR:case R.BUFFER_APPEND_ERROR:if(!t.errorAction){var o;t.errorAction=this.getLevelSwitchAction(t,(o=t.level)!=null?o:i.loadLevel)}return;case R.INTERNAL_EXCEPTION:case R.BUFFER_APPENDING_ERROR:case R.BUFFER_FULL_ERROR:case R.LEVEL_SWITCH_ERROR:case R.BUFFER_STALLED_ERROR:case R.BUFFER_SEEK_OVER_HOLE:case R.BUFFER_NUDGE_ON_STALL:t.errorAction=Ms();return}t.type===H.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=Ms())}getPlaylistRetryOrSwitchAction(e,t){const s=this.hls,i=Vo(s.config.playlistLoadPolicy,e),n=this.playlistError++;if(Ki(i,n,Gi(e),e.response))return{action:ke.RetryRequest,flags:Xe.None,retryConfig:i,retryCount:n};const o=this.getLevelSwitchAction(e,t);return i&&(o.retryConfig=i,o.retryCount=n),o}getFragRetryOrSwitchAction(e){const t=this.hls,s=this.getVariantLevelIndex(e.frag),i=t.levels[s],{fragLoadPolicy:n,keyLoadPolicy:a}=t.config,o=Vo(Go(e)?a:n,e),c=t.levels.reduce((u,h)=>u+h.fragmentError,0);if(i&&(e.details!==R.FRAG_GAP&&i.fragmentError++,!Ko(e)&&Ki(o,c,Gi(e),e.response)))return{action:ke.RetryRequest,flags:Xe.None,retryConfig:o,retryCount:c};const l=this.getLevelSwitchAction(e,s);return o&&(l.retryConfig=o,l.retryCount=c),l}getLevelSwitchAction(e,t){const s=this.hls;t==null&&(t=s.loadLevel);const i=this.hls.levels[t];if(i){var n,a;const l=e.details;i.loadError++,l===R.BUFFER_APPEND_ERROR&&i.fragmentError++;let u=-1;const{levels:h,loadLevel:d,minAutoLevel:g,maxAutoLevel:f}=s;!s.autoLevelEnabled&&!s.config.preserveManualLevelOnError&&(s.loadLevel=-1);const p=(n=e.frag)==null?void 0:n.type,v=(p===G.AUDIO&&l===R.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(l===R.BUFFER_ADD_CODEC_ERROR||l===R.BUFFER_APPEND_ERROR))&&h.some(({audioCodec:D})=>i.audioCodec!==D),T=e.sourceBufferName==="video"&&(l===R.BUFFER_ADD_CODEC_ERROR||l===R.BUFFER_APPEND_ERROR)&&h.some(({codecSet:D,audioCodec:I})=>i.codecSet!==D&&i.audioCodec===I),{type:S,groupId:_}=(a=e.context)!=null?a:{};for(let D=h.length;D--;){const I=(D+d)%h.length;if(I!==d&&I>=g&&I<=f&&h[I].loadError===0){var o,c;const b=h[I];if(l===R.FRAG_GAP&&p===G.MAIN&&e.frag){const A=h[I].details;if(A){const x=gs(e.frag,A.fragments,e.frag.start);if(x!=null&&x.gap)continue}}else{if(S===ee.AUDIO_TRACK&&b.hasAudioGroup(_)||S===ee.SUBTITLE_TRACK&&b.hasSubtitleGroup(_))continue;if(p===G.AUDIO&&(o=i.audioGroups)!=null&&o.some(A=>b.hasAudioGroup(A))||p===G.SUBTITLE&&(c=i.subtitleGroups)!=null&&c.some(A=>b.hasSubtitleGroup(A))||v&&i.audioCodec===b.audioCodec||T&&i.codecSet===b.codecSet||!v&&i.codecSet!==b.codecSet)continue}u=I;break}}if(u>-1&&s.loadLevel!==u)return e.levelRetry=!0,this.playlistError=0,{action:ke.SendAlternateToPenaltyBox,flags:Xe.None,nextAutoLevel:u}}return{action:ke.SendAlternateToPenaltyBox,flags:Xe.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var s;switch((s=t.errorAction)==null?void 0:s.action){case ke.DoNothing:break;case ke.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==R.FRAG_GAP?t.fatal=!0:/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break}if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){const t=this.hls,s=e.errorAction;if(!s)return;const{flags:i}=s,n=s.nextAutoLevel;switch(i){case Xe.None:this.switchLevel(e,n);break;case Xe.MoveAllAlternatesMatchingHDCP:{const c=this.getVariantLevelIndex(e.frag),l=t.levels[c],u=l?.attrs["HDCP-LEVEL"];if(s.hdcpLevel=u,u==="NONE")this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(u){t.maxHdcpLevel=jr[jr.indexOf(u)-1],s.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case Xe.MoveAllAlternatesMatchingKey:{const c=e.decryptdata;if(c){const l=this.hls.levels,u=l.length;for(let d=u;d--;)if(this.variantHasKey(l[d],c)){var a,o;this.log(`Banned key found in level ${d} (${l[d].bitrate}bps) or audio group "${(a=l[d].audioGroups)==null?void 0:a.join(",")}" (${(o=e.frag)==null?void 0:o.type} fragment) ${we(c.keyId||[])}`),l[d].fragmentError++,l[d].loadError++,this.log(`Removing level ${d} with key error (${e.error})`),this.hls.removeLevel(d)}const h=e.frag;if(this.hls.levels.length<u)s.resolved=!0;else if(h&&h.type!==G.MAIN){const d=h.decryptdata;d&&!c.matches(d)&&(s.resolved=!0)}}break}}s.resolved||this.switchLevel(e,n)}switchLevel(e,t){if(t!==void 0&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===R.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){const s=qr(e.mimeType),i=this.hls.levels;for(let n=i.length;n--;)i[n][`${e.sourceBufferName}Codec`]===s&&(this.log(`Removing level ${n} for ${e.details} ("${s}" not supported)`),this.hls.removeLevel(n))}}}function Ms(r){const e={action:ke.DoNothing,flags:Xe.None};return r&&(e.resolved=!0),e}var Re={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class Qd{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e&&(e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.BUFFER_APPENDED,this.onBufferAppended,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this),e.on(m.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.BUFFER_APPENDED,this.onBufferAppended,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this),e.off(m.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const s=this.activePartLists[t];if(s)for(let i=s.length;i--;){const n=s[i];if(!n)break;if(n.start<=e&&e<=n.end&&n.loaded)return n}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,s){const{fragments:i}=this,n=Object.keys(i);for(let a=n.length;a--;){const o=i[n[a]];if(o?.body.type===t&&(!s||o.buffered)){const c=o.body;if(c.start<=e&&e<=c.end)return c}}return null}detectEvictedFragments(e,t,s,i,n){this.timeRanges&&(this.timeRanges[e]=t);const a=i?.fragment.sn||-1;Object.keys(this.fragments).forEach(o=>{const c=this.fragments[o];if(!c||a>=c.body.sn)return;if(!c.buffered&&(!c.loaded||n)){c.body.type===s&&this.removeFragment(c.body);return}const l=c.range[e];if(l){if(l.time.length===0){this.removeFragment(c.body);return}l.time.some(u=>{const h=!this.isTimeBuffered(u.startPTS,u.endPTS,t);return h&&this.removeFragment(c.body),h})}})}detectPartialFragments(e){const t=this.timeRanges;if(!t||e.frag.sn==="initSegment")return;const s=e.frag,i=Fs(s),n=this.fragments[i];if(!n||n.buffered&&s.gap)return;const a=!s.relurl;Object.keys(t).forEach(o=>{const c=s.elementaryStreams[o];if(!c)return;const l=t[o],u=a||c.partial===!0;n.range[o]=this.getBufferedTimes(s,e.part,u,l)}),n.loaded=null,Object.keys(n.range).length?(this.bufferedEnd(n,s),Vi(n)||this.removeParts(s.sn-1,s.type)):this.removeFragment(n.body)}bufferedEnd(e,t){e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&(this.endListFragments[e.body.type]=e)}removeParts(e,t){const s=this.activePartLists[t];s&&(this.activePartLists[t]=Wo(s,i=>i.fragment.sn>=e))}fragBuffered(e,t){const s=Fs(e);let i=this.fragments[s];!i&&t&&(i=this.fragments[s]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,this.bufferedEnd(i,e))}getBufferedTimes(e,t,s,i){const n={time:[],partial:s},a=e.start,o=e.end,c=e.minEndPTS||o,l=e.maxStartPTS||a;for(let u=0;u<i.length;u++){const h=i.start(u)-this.bufferPadding,d=i.end(u)+this.bufferPadding;if(l>=h&&c<=d){n.time.push({startPTS:Math.max(a,i.start(u)),endPTS:Math.min(o,i.end(u))});break}else if(a<d&&o>h){const g=Math.max(a,i.start(u)),f=Math.min(o,i.end(u));f>g&&(n.partial=!0,n.time.push({startPTS:g,endPTS:f}))}else if(o<=h)break}return n}getPartialFragment(e){let t=null,s,i,n,a=0;const{bufferPadding:o,fragments:c}=this;return Object.keys(c).forEach(l=>{const u=c[l];u&&Vi(u)&&(i=u.body.start-o,n=u.body.end+o,e>=i&&e<=n&&(s=Math.min(e-i,n-e),a<=s&&(t=u.body,a=s)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||Vi(t))}getState(e){const t=Fs(e),s=this.fragments[t];return s?s.buffered?Vi(s)?Re.PARTIAL:Re.OK:Re.APPENDING:Re.NOT_LOADED}isTimeBuffered(e,t,s){let i,n;for(let a=0;a<s.length;a++){if(i=s.start(a)-this.bufferPadding,n=s.end(a)+this.bufferPadding,e>=i&&t<=n)return!0;if(t<=i)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(t.frag.sn==="initSegment"||t.frag.bitrateTest)return;const s=t.frag,i=t.part?null:t,n=Fs(s);this.fragments[n]={body:s,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:s,part:i,timeRanges:n,type:a}=t;if(s.sn==="initSegment")return;const o=s.type;if(i){let l=this.activePartLists[o];l||(this.activePartLists[o]=l=[]),l.push(i)}this.timeRanges=n;const c=n[a];this.detectEvictedFragments(a,c,o,i)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=Fs(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,s=Object.keys(t);if(!e)return s.length>0;for(let i=s.length;i--;){const n=t[s[i]];if(n?.body.type===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,s,i,n){i&&!this.hasGaps||Object.keys(this.fragments).forEach(a=>{const o=this.fragments[a];if(!o)return;const c=o.body;c.type!==s||i&&!c.gap||c.start<t&&c.end>e&&(o.buffered||n)&&this.removeFragment(c)})}removeFragment(e){const t=Fs(e);e.clearElementaryStreamInfo();const s=this.activePartLists[e.type];if(s){const i=e.sn;this.activePartLists[e.type]=Wo(s,n=>n.fragment.sn!==i)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const t=(e=this.hls)==null||(e=e.latestLevelDetails)==null?void 0:e.partList;t&&t.forEach(s=>s.clearElementaryStreamInfo())}}function Vi(r){var e,t,s;return r.buffered&&!!(r.body.gap||(e=r.range.video)!=null&&e.partial||(t=r.range.audio)!=null&&t.partial||(s=r.range.audiovideo)!=null&&s.partial)}function Fs(r){return`${r.type}_${r.level}_${r.sn}`}function Wo(r,e){return r.filter(t=>{const s=e(t);return s||t.clearElementaryStreamInfo(),s})}var es={cbc:0,ctr:1};class Jd{constructor(e,t,s){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=s}decrypt(e,t){switch(this.aesMode){case es.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case es.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}function Zd(r){const e=r.byteLength,t=e&&new DataView(r.buffer).getUint8(e-1);return t?r.slice(0,e-t):r}class ef{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const t=new DataView(e),s=new Uint32Array(4);for(let i=0;i<4;i++)s[i]=t.getUint32(i*4);return s}initTable(){const e=this.sBox,t=this.invSBox,s=this.subMix,i=s[0],n=s[1],a=s[2],o=s[3],c=this.invSubMix,l=c[0],u=c[1],h=c[2],d=c[3],g=new Uint32Array(256);let f=0,p=0,y=0;for(y=0;y<256;y++)y<128?g[y]=y<<1:g[y]=y<<1^283;for(y=0;y<256;y++){let v=p^p<<1^p<<2^p<<3^p<<4;v=v>>>8^v&255^99,e[f]=v,t[v]=f;const E=g[f],T=g[E],S=g[T];let _=g[v]*257^v*16843008;i[f]=_<<24|_>>>8,n[f]=_<<16|_>>>16,a[f]=_<<8|_>>>24,o[f]=_,_=S*16843009^T*65537^E*257^f*16843008,l[v]=_<<24|_>>>8,u[v]=_<<16|_>>>16,h[v]=_<<8|_>>>24,d[v]=_,f?(f=E^g[g[g[S^E]]],p^=g[g[p]]):f=p=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let s=!0,i=0;for(;i<t.length&&s;)s=t[i]===this.key[i],i++;if(s)return;this.key=t;const n=this.keySize=t.length;if(n!==4&&n!==6&&n!==8)throw new Error("Invalid aes key size="+n);const a=this.ksRows=(n+6+1)*4;let o,c;const l=this.keySchedule=new Uint32Array(a),u=this.invKeySchedule=new Uint32Array(a),h=this.sBox,d=this.rcon,g=this.invSubMix,f=g[0],p=g[1],y=g[2],v=g[3];let E,T;for(o=0;o<a;o++){if(o<n){E=l[o]=t[o];continue}T=E,o%n===0?(T=T<<8|T>>>24,T=h[T>>>24]<<24|h[T>>>16&255]<<16|h[T>>>8&255]<<8|h[T&255],T^=d[o/n|0]<<24):n>6&&o%n===4&&(T=h[T>>>24]<<24|h[T>>>16&255]<<16|h[T>>>8&255]<<8|h[T&255]),l[o]=E=(l[o-n]^T)>>>0}for(c=0;c<a;c++)o=a-c,c&3?T=l[o]:T=l[o-4],c<4||o<=4?u[c]=T:u[c]=f[h[T>>>24]]^p[h[T>>>16&255]]^y[h[T>>>8&255]]^v[h[T&255]],u[c]=u[c]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,s){const i=this.keySize+6,n=this.invKeySchedule,a=this.invSBox,o=this.invSubMix,c=o[0],l=o[1],u=o[2],h=o[3],d=this.uint8ArrayToUint32Array_(s);let g=d[0],f=d[1],p=d[2],y=d[3];const v=new Int32Array(e),E=new Int32Array(v.length);let T,S,_,D,I,b,A,x,C,M,K,V,N,w;const U=this.networkToHostOrderSwap;for(;t<v.length;){for(C=U(v[t]),M=U(v[t+1]),K=U(v[t+2]),V=U(v[t+3]),I=C^n[0],b=V^n[1],A=K^n[2],x=M^n[3],N=4,w=1;w<i;w++)T=c[I>>>24]^l[b>>16&255]^u[A>>8&255]^h[x&255]^n[N],S=c[b>>>24]^l[A>>16&255]^u[x>>8&255]^h[I&255]^n[N+1],_=c[A>>>24]^l[x>>16&255]^u[I>>8&255]^h[b&255]^n[N+2],D=c[x>>>24]^l[I>>16&255]^u[b>>8&255]^h[A&255]^n[N+3],I=T,b=S,A=_,x=D,N=N+4;T=a[I>>>24]<<24^a[b>>16&255]<<16^a[A>>8&255]<<8^a[x&255]^n[N],S=a[b>>>24]<<24^a[A>>16&255]<<16^a[x>>8&255]<<8^a[I&255]^n[N+1],_=a[A>>>24]<<24^a[x>>16&255]<<16^a[I>>8&255]<<8^a[b&255]^n[N+2],D=a[x>>>24]<<24^a[I>>16&255]<<16^a[b>>8&255]<<8^a[A&255]^n[N+3],E[t]=U(T^g),E[t+1]=U(D^f),E[t+2]=U(_^p),E[t+3]=U(S^y),g=C,f=M,p=K,y=V,t=t+4}return E.buffer}}class tf{constructor(e,t,s){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=s}expandKey(){const e=sf(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}function sf(r){switch(r){case es.cbc:return"AES-CBC";case es.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${r}`)}}const rf=16;class Qr{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const s=self.crypto;s&&(this.subtle=s.subtle||s.webkitSubtle)}catch{}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const s=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?Zd(s):s}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,s,i){return this.useSoftware?new Promise((n,a)=>{const o=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(o,t,s,i);const c=this.flush();c?n(c.buffer):a(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,s,i)}softwareDecrypt(e,t,s,i){const{currentIV:n,currentResult:a,remainderData:o}=this;if(i!==es.cbc||t.byteLength!==16)return oe.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(e=nt(o,e),this.remainderData=null);const c=this.getValidChunk(e);if(!c.length)return null;n&&(s=n);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new ef),l.expandKey(t);const u=a;return this.currentResult=l.decrypt(c.buffer,0,s),this.currentIV=c.slice(-16).buffer,u||null}webCryptoDecrypt(e,t,s,i){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,s,i));this.key=t,this.fastAesKey=new tf(this.subtle,t,i)}return this.fastAesKey.expandKey().then(n=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new Jd(this.subtle,new Uint8Array(s),i).decrypt(e.buffer,n)):Promise.reject(new Error("web crypto not initialized"))).catch(n=>(oe.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${n.name}: ${n.message}`),this.onWebCryptoError(e,t,s,i)))}onWebCryptoError(e,t,s,i){const n=this.enableSoftwareAES;if(n){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,s,i);const a=this.flush();if(a)return a.buffer}throw new Error("WebCrypto"+(n?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const s=e.length-e.length%rf;return s!==e.length&&(t=e.slice(0,s),this.remainderData=e.slice(s)),t}logOnce(e){this.logEnabled&&(oe.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const Yo=Math.pow(2,17);class nf{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t){const s=e.url;if(!s)return Promise.reject(new Ft({type:H.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${s?"part list":"url"}`),networkDetails:null}));this.abort();const i=this.config,n=i.fLoader,a=i.loader;return new Promise((o,c)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(f=>f[0]==="GAP")){c(jo(e));return}else e.gap=!1;const l=this.loader=n?new n(i):new a(i),u=qo(e);e.loader=l;const h=Ho(i.fragLoadPolicy.default),d={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:Yo};e.stats=l.stats;const g={onSuccess:(f,p,y,v)=>{this.resetLoader(e,l);let E=f.data;y.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(E.slice(0,16)),E=E.slice(16)),o({frag:e,part:null,payload:E,networkDetails:v})},onError:(f,p,y,v)=>{this.resetLoader(e,l),c(new Ft({type:H.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:ae({url:s,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:y,stats:v}))},onAbort:(f,p,y)=>{this.resetLoader(e,l),c(new Ft({type:H.NETWORK_ERROR,details:R.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:y,stats:f}))},onTimeout:(f,p,y)=>{this.resetLoader(e,l),c(new Ft({type:H.NETWORK_ERROR,details:R.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:y,stats:f}))}};t&&(g.onProgress=(f,p,y,v)=>t({frag:e,part:null,payload:y,networkDetails:v})),l.load(u,d,g)})}loadPart(e,t,s){this.abort();const i=this.config,n=i.fLoader,a=i.loader;return new Promise((o,c)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){c(jo(e,t));return}const l=this.loader=n?new n(i):new a(i),u=qo(e,t);e.loader=l;const h=Ho(i.fragLoadPolicy.default),d={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Yo};t.stats=l.stats,l.load(u,d,{onSuccess:(g,f,p,y)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const v={frag:e,part:t,payload:g.data,networkDetails:y};s(v),o(v)},onError:(g,f,p,y)=>{this.resetLoader(e,l),c(new Ft({type:H.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:ae({url:u.url,data:void 0},g),error:new Error(`HTTP Error ${g.code} ${g.text}`),networkDetails:p,stats:y}))},onAbort:(g,f,p)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),c(new Ft({type:H.NETWORK_ERROR,details:R.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:p,stats:g}))},onTimeout:(g,f,p)=>{this.resetLoader(e,l),c(new Ft({type:H.NETWORK_ERROR,details:R.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:p,stats:g}))}})})}updateStatsFromPart(e,t){const s=e.stats,i=t.stats,n=i.total;if(s.loaded+=i.loaded,n){const c=Math.round(e.duration/t.duration),l=Math.min(Math.round(s.loaded/n),c),h=(c-l)*Math.round(s.loaded/l);s.total=s.loaded+h}else s.total=Math.max(s.loaded,s.total);const a=s.loading,o=i.loading;a.start?a.first+=o.first-o.start:(a.start=o.start,a.first=o.first),a.end=o.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function qo(r,e=null){const t=e||r,s={frag:r,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},i=t.byteRangeStartOffset,n=t.byteRangeEndOffset;if($(i)&&$(n)){var a;let o=i,c=n;if(r.sn==="initSegment"&&af((a=r.decryptdata)==null?void 0:a.method)){const l=n-i;l%16&&(c=n+(16-l%16)),i!==0&&(s.resetIV=!0,o=i-16)}s.rangeStart=o,s.rangeEnd=c}return s}function jo(r,e){const t=new Error(`GAP ${r.gap?"tag":"attribute"} found`),s={type:H.MEDIA_ERROR,details:R.FRAG_GAP,fatal:!1,frag:r,error:t,networkDetails:null};return e&&(s.part=e),(e||r).stats.aborted=!0,new Ft(s)}function af(r){return r==="AES-128"||r==="AES-256"}class Ft extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class Xo extends rt{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class Jr{constructor(e,t,s,i=0,n=-1,a=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=Hi(),this.buffering={audio:Hi(),video:Hi(),audiovideo:Hi()},this.level=e,this.sn=t,this.id=s,this.size=i,this.part=n,this.partial=a}}function Hi(){return{start:0,executeStart:0,executeEnd:0,end:0}}const zo={length:0,start:()=>0,end:()=>0};class j{static isBuffered(e,t){if(e){const s=j.getBuffered(e);for(let i=s.length;i--;)if(t>=s.start(i)&&t<=s.end(i))return!0}return!1}static bufferedRanges(e){if(e){const t=j.getBuffered(e);return j.timeRangesToArray(t)}return[]}static timeRangesToArray(e){const t=[];for(let s=0;s<e.length;s++)t.push({start:e.start(s),end:e.end(s)});return t}static bufferInfo(e,t,s){if(e){const i=j.bufferedRanges(e);if(i.length)return j.bufferedInfo(i,t,s)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,s){t=Math.max(0,t),e.length>1&&e.sort((u,h)=>u.start-h.start||h.end-u.end);let i=-1,n=[];if(s)for(let u=0;u<e.length;u++){t>=e[u].start&&t<=e[u].end&&(i=u);const h=n.length;if(h){const d=n[h-1].end;e[u].start-d<s?e[u].end>d&&(n[h-1].end=e[u].end):n.push(e[u])}else n.push(e[u])}else n=e;let a=0,o,c=t,l=t;for(let u=0;u<n.length;u++){const h=n[u].start,d=n[u].end;if(i===-1&&t>=h&&t<=d&&(i=u),t+s>=h&&t<d)c=h,l=d,a=l-t;else if(t+s<h){o=h;break}}return{len:a,start:c||0,end:l||0,nextStart:o,buffered:e,bufferedIndex:i}}static getBuffered(e){try{return e.buffered||zo}catch(t){return oe.log("failed to get media.buffered",t),zo}}}const Qo=/\{\$([a-zA-Z0-9-_]+)\}/g;function Jo(r){return Qo.test(r)}function Zr(r,e){if(r.variableList!==null||r.hasVariableRefs){const t=r.variableList;return e.replace(Qo,s=>{const i=s.substring(2,s.length-1),n=t?.[i];return n===void 0?(r.playlistParsingError||(r.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${i}"`)),s):n})}return e}function Zo(r,e,t){let s=r.variableList;s||(r.variableList=s={});let i,n;if("QUERYPARAM"in e){i=e.QUERYPARAM;try{const a=new self.URL(t).searchParams;if(a.has(i))n=a.get(i);else throw new Error(`"${i}" does not match any query parameter in URI: "${t}"`)}catch(a){r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else i=e.NAME,n=e.VALUE;i in s?r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${i}"`)):s[i]=n||""}function of(r,e,t){const s=e.IMPORT;if(t&&s in t){let i=r.variableList;i||(r.variableList=i={}),i[s]=t[s]}else r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${s}"`))}const lf=/^(\d+)x(\d+)$/,el=/(.+?)=(".*?"|.*?)(?:,|$)/g;class pe{constructor(e,t){typeof e=="string"&&(e=pe.parseAttrList(e,t)),le(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)==="X-")}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(t.length&1?"0":"")+t;const s=new Uint8Array(t.length/2);for(let i=0;i<t.length/2;i++)s[i]=parseInt(t.slice(i*2,i*2+2),16);return s}return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const s=this[e];return s?parseFloat(s):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){const s=this[e];return(s?s.split(/[ ,]+/):[]).reduce((i,n)=>(i[n.toLowerCase()]=!0,i),t)}bool(e){return this[e]==="YES"}decimalResolution(e){const t=lf.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let s;const i={};for(el.lastIndex=0;(s=el.exec(e))!==null;){const a=s[1].trim();let o=s[2];const c=o.indexOf('"')===0&&o.lastIndexOf('"')===o.length-1;let l=!1;if(c)o=o.slice(1,-1);else switch(a){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":l=!0}if(t&&(c||l))o=Zr(t,o);else if(!l&&!c)switch(a){case"CLOSED-CAPTIONS":if(o==="NONE")break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":oe.warn(`${e}: attribute ${a} is missing quotes`)}i[a]=o}return i}}const cf="com.apple.hls.interstitial";function uf(r){return r!=="ID"&&r!=="CLASS"&&r!=="CUE"&&r!=="START-DATE"&&r!=="DURATION"&&r!=="END-DATE"&&r!=="END-ON-NEXT"}function hf(r){return r==="SCTE35-OUT"||r==="SCTE35-IN"||r==="SCTE35-CMD"}class tl{constructor(e,t,s=0){var i;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=t?.tagAnchor||null,this.tagOrder=(i=t?.tagOrder)!=null?i:s,t){const n=t.attr;for(const a in n)if(Object.prototype.hasOwnProperty.call(e,a)&&e[a]!==n[a]){oe.warn(`DATERANGE tag attribute: "${a}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=a;break}e=le(new pe({}),n,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const n=t?.endDate||new Date(this.attr["END-DATE"]);$(n.getTime())&&(this._endDate=n)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const e=this._cue;return e===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){const{tagAnchor:e}=this;return e===null||e.programDateTime===null?(oe.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const e=this._endDate||this._dateAtEnd;if(e)return e;const t=this.duration;return t!==null?this._dateAtEnd=new Date(this._startDate.getTime()+t*1e3):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if($(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return this.class===cf}get isValid(){return!!this.id&&!this._badValueForSameId&&$(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}}const df=10;class ff{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}const t=this.lastPartSn-e.lastPartSn,s=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!s||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&s>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let s=t.decryptdata;return s||(t.setKeyFormat(e.keyFormat),s=t.decryptdata),!!s&&e.matches(s)})}get hasProgramDateTime(){return this.fragments.length?$(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||df}get drift(){const e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(t!==-1){for(let s=e.length;s--;)if(e[s].index>t)return e[s].index;return t}}return 0}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}function Wi(r,e){return r.length===e.length?!r.some((t,s)=>t!==e[s]):!1}function sl(r,e){return!r&&!e?!0:!r||!e?!1:Wi(r,e)}function Ns(r){return r==="AES-128"||r==="AES-256"||r==="AES-256-CTR"}function en(r){switch(r){case"AES-128":case"AES-256":return es.cbc;case"AES-256-CTR":return es.ctr;default:throw new Error(`invalid full segment method ${r}`)}}function tn(r){return Uint8Array.from(atob(r),e=>e.charCodeAt(0))}function sn(r){return Uint8Array.from(unescape(encodeURIComponent(r)),e=>e.charCodeAt(0))}function gf(r){const e=sn(r).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function il(r){const e=function(s,i,n){const a=s[i];s[i]=s[n],s[n]=a};e(r,0,3),e(r,1,2),e(r,4,5),e(r,6,7)}function rl(r){const e=r.split(":");let t=null;if(e[0]==="data"&&e.length===2){const s=e[1].split(";"),i=s[s.length-1].split(",");if(i.length===2){const n=i[0]==="base64",a=i[1];n?(s.splice(-1,1),t=tn(a)):t=gf(a)}}return t}const Yi=typeof self<"u"?self:void 0;var ye={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Oe={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function qi(r){switch(r){case Oe.FAIRPLAY:return ye.FAIRPLAY;case Oe.PLAYREADY:return ye.PLAYREADY;case Oe.WIDEVINE:return ye.WIDEVINE;case Oe.CLEARKEY:return ye.CLEARKEY}}function rn(r){switch(r){case ye.FAIRPLAY:return Oe.FAIRPLAY;case ye.PLAYREADY:return Oe.PLAYREADY;case ye.WIDEVINE:return Oe.WIDEVINE;case ye.CLEARKEY:return Oe.CLEARKEY}}function ri(r){const{drmSystems:e,widevineLicenseUrl:t}=r,s=e?[ye.FAIRPLAY,ye.WIDEVINE,ye.PLAYREADY,ye.CLEARKEY].filter(i=>!!e[i]):[];return!s[ye.WIDEVINE]&&t&&s.push(ye.WIDEVINE),s}const nl=(function(r){return Yi!=null&&(r=Yi.navigator)!=null&&r.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null})();function mf(r,e,t,s){let i;switch(r){case ye.FAIRPLAY:i=["cenc","sinf"];break;case ye.WIDEVINE:case ye.PLAYREADY:i=["cenc"];break;case ye.CLEARKEY:i=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${r}`)}return pf(i,e,t,s)}function pf(r,e,t,s){return[{initDataTypes:r,persistentState:s.persistentState||"optional",distinctiveIdentifier:s.distinctiveIdentifier||"optional",sessionTypes:s.sessionTypes||[s.sessionType||"temporary"],audioCapabilities:e.map(n=>({contentType:`audio/mp4; codecs=${n}`,robustness:s.audioRobustness||"",encryptionScheme:s.audioEncryptionScheme||null})),videoCapabilities:t.map(n=>({contentType:`video/mp4; codecs=${n}`,robustness:s.videoRobustness||"",encryptionScheme:s.videoEncryptionScheme||null}))}]}function yf(r){var e;return!!r&&(r.sessionType==="persistent-license"||!!((e=r.sessionTypes)!=null&&e.some(t=>t==="persistent-license")))}function al(r){const e=new Uint16Array(r.buffer,r.byteOffset,r.byteLength/2),t=String.fromCharCode.apply(null,Array.from(e)),s=t.substring(t.indexOf("<"),t.length),a=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(a){const o=a.childNodes[0]?a.childNodes[0].nodeValue:a.getAttribute("VALUE");if(o){const c=tn(o).subarray(0,16);return il(c),c}}return null}let $s={};class ts{static clearKeyUriToKeyIdMap(){$s={}}static setKeyIdForUri(e,t){$s[e]=t}static addKeyIdForUri(e){const t=Object.keys($s).length%Number.MAX_SAFE_INTEGER,s=new Uint8Array(16);return new DataView(s.buffer,12,4).setUint32(0,t),$s[e]=s,s}constructor(e,t,s,i=[1],n=null,a){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=s,this.keyFormatVersions=i,this.iv=n,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!Ns(e),a!=null&&a.startsWith("0x")&&(this.keyId=new Uint8Array(co(a)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&Wi(e.keyFormatVersions,this.keyFormatVersions)&&sl(e.iv,this.iv)&&sl(e.keyId,this.keyId)}isSupported(){if(this.method){if(Ns(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case Oe.FAIRPLAY:case Oe.WIDEVINE:case Oe.PLAYREADY:case Oe.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e,t){if(!this.encrypted||!this.uri)return null;if(Ns(this.method)){let n=this.iv;return n||(typeof e!="number"&&(oe.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),n=Ef(e)),new ts(this.method,this.uri,"identity",this.keyFormatVersions,n)}if(this.keyId){const n=$s[this.uri];if(n&&!Wi(this.keyId,n)&&ts.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const s=rl(this.uri);if(s)switch(this.keyFormat){case Oe.WIDEVINE:if(this.pssh=s,!this.keyId){const n=Sd(s.buffer);if(n.length){var i;const a=n[0];this.keyId=(i=a.kids)!=null&&i.length?a.kids[0]:null}}this.keyId||(this.keyId=ol(t));break;case Oe.PLAYREADY:{const n=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Td(n,null,s),this.keyId=al(s);break}default:{let n=s.subarray(0,16);if(n.length!==16){const a=new Uint8Array(16);a.set(n,16-n.length),n=a}this.keyId=n;break}}if(!this.keyId||this.keyId.byteLength!==16){let n;n=vf(t),n||(n=ol(t),n||(n=$s[this.uri])),n&&(this.keyId=n,ts.setKeyIdForUri(this.uri,n))}return this}}function vf(r){const e=r?.[Oe.WIDEVINE];return e?e.keyId:null}function ol(r){const e=r?.[Oe.PLAYREADY];if(e){const t=rl(e.uri);if(t)return al(t)}return null}function Ef(r){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=r>>8*(15-t)&255;return e}const ll=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,cl=/#EXT-X-MEDIA:(.*)/g,Tf=/^#EXT(?:INF|-X-TARGETDURATION):/m,nn=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Sf=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class _t{static findGroup(e,t){for(let s=0;s<e.length;s++){const i=e[s];if(i.id===t)return i}}static resolve(e,t){return Br.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return Tf.test(e)}static parseMasterPlaylist(e,t){const s=Jo(e),i={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:s},n=[];if(ll.lastIndex=0,!e.startsWith("#EXTM3U"))return i.playlistParsingError=new Error("no EXTM3U delimiter"),i;let a;for(;(a=ll.exec(e))!=null;)if(a[1]){var o;const l=new pe(a[1],i),u=Zr(i,a[2]),h={attrs:l,bitrate:l.decimalInteger("BANDWIDTH")||l.decimalInteger("AVERAGE-BANDWIDTH"),name:l.NAME,url:_t.resolve(u,t)},d=l.decimalResolution("RESOLUTION");d&&(h.width=d.width,h.height=d.height),fl(l.CODECS,h);const g=l["SUPPLEMENTAL-CODECS"];g&&(h.supplemental={},fl(g,h.supplemental)),(o=h.unknownCodecs)!=null&&o.length||n.push(h),i.levels.push(h)}else if(a[3]){const l=a[3],u=a[4];switch(l){case"SESSION-DATA":{const h=new pe(u,i),d=h["DATA-ID"];d&&(i.sessionData===null&&(i.sessionData={}),i.sessionData[d]=h);break}case"SESSION-KEY":{const h=hl(u,t,i);h.encrypted&&h.isSupported()?(i.sessionKeys===null&&(i.sessionKeys=[]),i.sessionKeys.push(h)):oe.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${u}"`);break}case"DEFINE":{{const h=new pe(u,i);Zo(i,h,t)}break}case"CONTENT-STEERING":{const h=new pe(u,i);i.contentSteering={uri:_t.resolve(h["SERVER-URI"],t),pathwayId:h["PATHWAY-ID"]||"."};break}case"START":{i.startTimeOffset=dl(u);break}}}const c=n.length>0&&n.length<i.levels.length;return i.levels=c?n:i.levels,i.levels.length===0&&(i.playlistParsingError=new Error("no levels found in manifest")),i}static parseMasterPlaylistMedia(e,t,s){let i;const n={},a=s.levels,o={AUDIO:a.map(l=>({id:l.attrs.AUDIO,audioCodec:l.audioCodec})),SUBTITLES:a.map(l=>({id:l.attrs.SUBTITLES,textCodec:l.textCodec})),"CLOSED-CAPTIONS":[]};let c=0;for(cl.lastIndex=0;(i=cl.exec(e))!==null;){const l=new pe(i[1],s),u=l.TYPE;if(u){const h=o[u],d=n[u]||[];n[u]=d;const g=l.LANGUAGE,f=l["ASSOC-LANGUAGE"],p=l.CHANNELS,y=l.CHARACTERISTICS,v=l["INSTREAM-ID"],E={attrs:l,bitrate:0,id:c++,groupId:l["GROUP-ID"]||"",name:l.NAME||g||"",type:u,default:l.bool("DEFAULT"),autoselect:l.bool("AUTOSELECT"),forced:l.bool("FORCED"),lang:g,url:l.URI?_t.resolve(l.URI,t):""};if(f&&(E.assocLang=f),p&&(E.channels=p),y&&(E.characteristics=y),v&&(E.instreamId=v),h!=null&&h.length){const T=_t.findGroup(h,E.groupId)||h[0];gl(E,T,"audioCodec"),gl(E,T,"textCodec")}d.push(E)}}return n}static parseLevelPlaylist(e,t,s,i,n,a){var o;const c={url:t},l=new ff(t),u=l.fragments,h=[];let d=null,g=0,f=0,p=0,y=0,v=0,E=null,T=new Gr(i,c),S,_,D,I=-1,b=!1,A=null,x;if(nn.lastIndex=0,l.m3u8=e,l.hasVariableRefs=Jo(e),((o=nn.exec(e))==null?void 0:o[0])!=="#EXTM3U")return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;(S=nn.exec(e))!==null;){b&&(b=!1,T=new Gr(i,c),T.playlistOffset=p,T.setStart(p),T.sn=g,T.cc=y,v&&(T.bitrate=v),T.level=s,d&&(T.initSegment=d,d.rawProgramDateTime&&(T.rawProgramDateTime=d.rawProgramDateTime,d.rawProgramDateTime=null),A&&(T.setByteRange(A),A=null)));const V=S[1];if(V){T.duration=parseFloat(V);const N=(" "+S[2]).slice(1);T.title=N||null,T.tagList.push(N?["INF",V,N]:["INF",V])}else if(S[3]){if($(T.duration)){T.playlistOffset=p,T.setStart(p),D&&pl(T,D,l),T.sn=g,T.level=s,T.cc=y,u.push(T);const N=(" "+S[3]).slice(1);T.relurl=Zr(l,N),an(T,E,h),E=T,p+=T.duration,g++,f=0,b=!0}}else{if(S=S[0].match(Sf),!S){oe.warn("No matches on slow regex match for level playlist!");continue}for(_=1;_<S.length&&S[_]===void 0;_++);const N=(" "+S[_]).slice(1),w=(" "+S[_+1]).slice(1),U=S[_+2]?(" "+S[_+2]).slice(1):null;switch(N){case"BYTERANGE":E?T.setByteRange(w,E):T.setByteRange(w);break;case"PROGRAM-DATE-TIME":T.rawProgramDateTime=w,T.tagList.push(["PROGRAM-DATE-TIME",w]),I===-1&&(I=u.length);break;case"PLAYLIST-TYPE":l.type&&Nt(l,N,S),l.type=w.toUpperCase();break;case"MEDIA-SEQUENCE":l.startSN!==0?Nt(l,N,S):u.length>0&&yl(l,N,S),g=l.startSN=parseInt(w);break;case"SKIP":{l.skippedSegments&&Nt(l,N,S);const F=new pe(w,l),B=F.decimalInteger("SKIPPED-SEGMENTS");if($(B)){l.skippedSegments+=B;for(let k=B;k--;)u.push(null);g+=B}const W=F.enumeratedString("RECENTLY-REMOVED-DATERANGES");W&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(W.split(" ")));break}case"TARGETDURATION":l.targetduration!==0&&Nt(l,N,S),l.targetduration=Math.max(parseInt(w),1);break;case"VERSION":l.version!==null&&Nt(l,N,S),l.version=parseInt(w);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":l.live||Nt(l,N,S),l.live=!1;break;case"#":(w||U)&&T.tagList.push(U?[w,U]:[w]);break;case"DISCONTINUITY":y++,T.tagList.push(["DIS"]);break;case"GAP":T.gap=!0,T.tagList.push([N]);break;case"BITRATE":T.tagList.push([N,w]),v=parseInt(w)*1e3,$(v)?T.bitrate=v:v=0;break;case"DATERANGE":{const F=new pe(w,l),B=new tl(F,l.dateRanges[F.ID],l.dateRangeTagCount);l.dateRangeTagCount++,B.isValid||l.skippedSegments?l.dateRanges[B.id]=B:oe.warn(`Ignoring invalid DATERANGE tag: "${w}"`),T.tagList.push(["EXT-X-DATERANGE",w]);break}case"DEFINE":{{const F=new pe(w,l);"IMPORT"in F?of(l,F,a):Zo(l,F,t)}break}case"DISCONTINUITY-SEQUENCE":l.startCC!==0?Nt(l,N,S):u.length>0&&yl(l,N,S),l.startCC=y=parseInt(w);break;case"KEY":{const F=hl(w,t,l);if(F.isSupported()){if(F.method==="NONE"){D=void 0;break}D||(D={});const B=D[F.keyFormat];B!=null&&B.matches(F)||(B&&(D=le({},D)),D[F.keyFormat]=F)}else oe.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${w}"`);break}case"START":l.startTimeOffset=dl(w);break;case"MAP":{const F=new pe(w,l);if(T.duration){const B=new Gr(i,c);ml(B,F,s,D),d=B,T.initSegment=d,d.rawProgramDateTime&&!T.rawProgramDateTime&&(T.rawProgramDateTime=d.rawProgramDateTime)}else{const B=T.byteRangeEndOffset;if(B){const W=T.byteRangeStartOffset;A=`${B-W}@${W}`}else A=null;ml(T,F,s,D),d=T,b=!0}d.cc=y;break}case"SERVER-CONTROL":{x&&Nt(l,N,S),x=new pe(w),l.canBlockReload=x.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=x.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&x.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=x.optionalFloat("PART-HOLD-BACK",0),l.holdBack=x.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{l.partTarget&&Nt(l,N,S);const F=new pe(w);l.partTarget=F.decimalFloatingPoint("PART-TARGET");break}case"PART":{let F=l.partList;F||(F=l.partList=[]);const B=f>0?F[F.length-1]:void 0,W=f++,k=new pe(w,l),O=new ad(k,T,c,W,B);F.push(O),T.duration+=O.duration;break}case"PRELOAD-HINT":{const F=new pe(w,l);l.preloadHint=F;break}case"RENDITION-REPORT":{const F=new pe(w,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(F);break}default:oe.warn(`line parsed but not handled: ${S}`);break}}}E&&!E.relurl?(u.pop(),p-=E.duration,l.partList&&(l.fragmentHint=E)):l.partList&&(an(T,E,h),T.cc=y,l.fragmentHint=T,D&&pl(T,D,l)),l.targetduration||(l.playlistParsingError=new Error("Missing Target Duration"));const C=u.length,M=u[0],K=u[C-1];if(p+=l.skippedSegments*l.targetduration,p>0&&C&&K){l.averagetargetduration=p/C;const V=K.sn;l.endSN=V!=="initSegment"?V:0,l.live||(K.endList=!0),I>0&&(Af(u,I),M&&h.unshift(M))}return l.fragmentHint&&(p+=l.fragmentHint.duration),l.totalduration=p,h.length&&l.dateRangeTagCount&&M&&ul(h,l),l.endCC=y,l}}function ul(r,e){let t=r.length;if(!t)if(e.hasProgramDateTime){const o=e.fragments[e.fragments.length-1];r.push(o),t++}else return;const s=r[t-1],i=e.live?1/0:e.totalduration,n=Object.keys(e.dateRanges);for(let o=n.length;o--;){const c=e.dateRanges[n[o]],l=c.startDate.getTime();c.tagAnchor=s.ref;for(let u=t;u--;){var a;if(((a=r[u])==null?void 0:a.sn)<e.startSN)break;const h=xf(e,l,r,u,i);if(h!==-1){c.tagAnchor=e.fragments[h].ref;break}}}}function xf(r,e,t,s,i){const n=t[s];if(n){const o=n.programDateTime;if(e>=o||s===0){var a;const c=(((a=t[s+1])==null?void 0:a.start)||i)-n.start;if(e<=o+c*1e3){const l=t[s].sn-r.startSN;if(l<0)return-1;const u=r.fragments;if(u.length>t.length){const d=(t[s+1]||u[u.length-1]).sn-r.startSN;for(let g=d;g>l;g--){const f=u[g].programDateTime;if(e>=f&&e<f+u[g].duration*1e3)return g}}return l}}}return-1}function hl(r,e,t){var s,i;const n=new pe(r,t),a=(s=n.METHOD)!=null?s:"",o=n.URI,c=n.hexadecimalInteger("IV"),l=n.KEYFORMATVERSIONS,u=(i=n.KEYFORMAT)!=null?i:"identity";o&&n.IV&&!c&&oe.error(`Invalid IV: ${n.IV}`);const h=o?_t.resolve(o,e):"",d=(l||"1").split("/").map(Number).filter(Number.isFinite);return new ts(a,h,u,d,c,n.KEYID)}function dl(r){const t=new pe(r).decimalFloatingPoint("TIME-OFFSET");return $(t)?t:null}function fl(r,e){let t=(r||"").split(/[ ,]+/).filter(s=>s);["video","audio","text"].forEach(s=>{const i=t.filter(n=>Hr(n,s));i.length&&(e[`${s}Codec`]=i.map(n=>n.split("/")[0]).join(","),t=t.filter(n=>i.indexOf(n)===-1))}),e.unknownCodecs=t}function gl(r,e,t){const s=e[t];s&&(r[t]=s)}function Af(r,e){let t=r[e];for(let s=e;s--;){const i=r[s];if(!i)return;i.programDateTime=t.programDateTime-i.duration*1e3,t=i}}function an(r,e,t){r.rawProgramDateTime?t.push(r):e!=null&&e.programDateTime&&(r.programDateTime=e.endProgramDateTime)}function ml(r,e,t,s){r.relurl=e.URI,e.BYTERANGE&&r.setByteRange(e.BYTERANGE),r.level=t,r.sn="initSegment",s&&(r.levelkeys=s),r.initSegment=null}function pl(r,e,t){r.levelkeys=e;const{encryptedFragments:s}=t;(!s.length||s[s.length-1].levelkeys!==e)&&Object.keys(e).some(i=>e[i].isCommonEncryption)&&s.push(r)}function Nt(r,e,t){r.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function yl(r,e,t){r.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function on(r,e){const t=e.startPTS;if($(t)){let s=0,i;e.sn>r.sn?(s=t-r.start,i=r):(s=r.start-t,i=e),i.duration!==s&&i.setDuration(s)}else e.sn>r.sn?r.cc===e.cc&&r.minEndPTS?e.setStart(r.start+(r.minEndPTS-r.start)):e.setStart(r.start+r.duration):e.setStart(Math.max(r.start-e.duration,0))}function vl(r,e,t,s,i,n,a){s-t<=0&&(a.warn("Fragment should have a positive duration",e),s=t+e.duration,n=i+e.duration);let c=t,l=s;const u=e.startPTS,h=e.endPTS;if($(u)){const v=Math.abs(u-t);r&&v>r.totalduration?a.warn(`media timestamps and playlist times differ by ${v}s for level ${e.level} ${r.url}`):$(e.deltaPTS)?e.deltaPTS=Math.max(v,e.deltaPTS):e.deltaPTS=v,c=Math.max(t,u),t=Math.min(t,u),i=e.startDTS!==void 0?Math.min(i,e.startDTS):i,l=Math.min(s,h),s=Math.max(s,h),n=e.endDTS!==void 0?Math.max(n,e.endDTS):n}const d=t-e.start;e.start!==0&&e.setStart(t),e.setDuration(s-e.start),e.startPTS=t,e.maxStartPTS=c,e.startDTS=i,e.endPTS=s,e.minEndPTS=l,e.endDTS=n;const g=e.sn;if(!r||g<r.startSN||g>r.endSN)return 0;let f;const p=g-r.startSN,y=r.fragments;for(y[p]=e,f=p;f>0;f--)on(y[f],y[f-1]);for(f=p;f<y.length-1;f++)on(y[f],y[f+1]);return r.fragmentHint&&on(y[y.length-1],r.fragmentHint),r.PTSKnown=r.alignedSliding=!0,d}function _f(r,e,t){if(r===e)return;let s=null;const i=r.fragments;for(let u=i.length-1;u>=0;u--){const h=i[u].initSegment;if(h){s=h;break}}r.fragmentHint&&delete r.fragmentHint.endPTS;let n;Rf(r,e,(u,h,d,g)=>{if((!e.startCC||e.skippedSegments)&&h.cc!==u.cc){const f=u.cc-h.cc;for(let p=d;p<g.length;p++)g[p].cc+=f;e.endCC=g[g.length-1].cc}$(u.startPTS)&&$(u.endPTS)&&(h.setStart(h.startPTS=u.startPTS),h.startDTS=u.startDTS,h.maxStartPTS=u.maxStartPTS,h.endPTS=u.endPTS,h.endDTS=u.endDTS,h.minEndPTS=u.minEndPTS,h.setDuration(u.endPTS-u.startPTS),h.duration&&(n=h),e.PTSKnown=e.alignedSliding=!0),u.hasStreams&&(h.elementaryStreams=u.elementaryStreams),h.loader=u.loader,u.hasStats&&(h.stats=u.stats),u.initSegment&&(h.initSegment=u.initSegment,s=u.initSegment)});const a=e.fragments,o=e.fragmentHint?a.concat(e.fragmentHint):a;if(s&&o.forEach(u=>{var h;u&&(!u.initSegment||u.initSegment.relurl===((h=s)==null?void 0:h.relurl))&&(u.initSegment=s)}),e.skippedSegments){if(e.deltaUpdateFailed=a.some(u=>!u),e.deltaUpdateFailed){t.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let u=e.skippedSegments;u--;)a.shift();e.startSN=a[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=If(r.dateRanges,e,t));const u=r.fragments.filter(h=>h.rawProgramDateTime);if(r.hasProgramDateTime&&!e.hasProgramDateTime)for(let h=1;h<o.length;h++)o[h].programDateTime===null&&an(o[h],o[h-1],u);ul(u,e)}e.endCC=a[a.length-1].cc}if(!e.startCC){var c;const u=xl(r,e.startSN-1);e.startCC=(c=u?.cc)!=null?c:a[0].cc}Lf(r.partList,e.partList,(u,h)=>{h.elementaryStreams=u.elementaryStreams,h.stats=u.stats}),n?vl(e,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS,t):Tl(r,e),a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=r.driftStartTime,e.driftStart=r.driftStart;const l=e.advancedDateTime;if(e.advanced&&l){const u=e.edge;e.driftStart||(e.driftStartTime=l,e.driftStart=u),e.driftEndTime=l,e.driftEnd=u}else e.driftEndTime=r.driftEndTime,e.driftEnd=r.driftEnd,e.advancedDateTime=r.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=r.requestScheduled)}function If(r,e,t){const{dateRanges:s,recentlyRemovedDateranges:i}=e,n=le({},r);i&&i.forEach(c=>{delete n[c]});const o=Object.keys(n).length;return o?(Object.keys(s).forEach(c=>{const l=n[c],u=new tl(s[c].attr,l);u.isValid?(n[c]=u,l||(u.tagOrder+=o)):t.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${ue(s[c].attr)}"`)}),n):s}function Lf(r,e,t){if(r&&e){let s=0;for(let i=0,n=r.length;i<=n;i++){const a=r[i],o=e[i+s];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?t(a,o):s--}}}function Rf(r,e,t){const s=e.skippedSegments,i=Math.max(r.startSN,e.startSN)-e.startSN,n=(r.fragmentHint?1:0)+(s?e.endSN:Math.min(r.endSN,e.endSN))-e.startSN,a=e.startSN-r.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,c=r.fragmentHint?r.fragments.concat(r.fragmentHint):r.fragments;for(let l=i;l<=n;l++){const u=c[a+l];let h=o[l];if(s&&!h&&u&&(h=e.fragments[l]=u),u&&h){t(u,h,l,o);const d=u.relurl,g=h.relurl;if(d&&bf(d,g)){e.playlistParsingError=El(`media sequence mismatch ${h.sn}:`,r,e,u,h);return}else if(u.cc!==h.cc){e.playlistParsingError=El(`discontinuity sequence mismatch (${u.cc}!=${h.cc})`,r,e,u,h);return}}}}function El(r,e,t,s,i){return new Error(`${r} ${i.url}
13
- Playlist starting @${e.startSN}
14
- ${e.m3u8}
15
-
10
+ Switching to level ${re} @ ${ie|0} bps`),r.nextLoadLevel=r.nextAutoLevel=re,this.clearTimer();let oe=()=>{if(this.clearTimer(),this.fragCurrent===t&&this.hls.loadLevel===re&&re>0){let e=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${re>0?`and switching down`:``}
11
+ Fragment duration: ${t.duration.toFixed(3)} s
12
+ Time to underbuffer: ${e.toFixed(3)} s`),t.abortRequests(),this.fragCurrent=this.partCurrent=null,re>u){let t=this.findBestLevel(this.hls.levels[u].bitrate,u,re,0,e,1,1);t===-1&&(t=u),this.hls.nextLoadLevel=this.hls.nextAutoLevel=t,this.resetEstimator(this.hls.levels[t].bitrate)}}};p||D>k*2?oe():this.timer=self.setInterval(oe,k*1e3),r.trigger(B.FRAG_LOAD_EMERGENCY_ABORTED,{frag:t,part:n,stats:s})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){let e=this.hls.config;return new Kr(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){let{hls:e}=this;e.on(B.MANIFEST_LOADING,this.onManifestLoading,this),e.on(B.FRAG_LOADING,this.onFragLoading,this),e.on(B.FRAG_LOADED,this.onFragLoaded,this),e.on(B.FRAG_BUFFERED,this.onFragBuffered,this),e.on(B.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(B.LEVEL_LOADED,this.onLevelLoaded,this),e.on(B.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(B.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(B.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e&&(e.off(B.MANIFEST_LOADING,this.onManifestLoading,this),e.off(B.FRAG_LOADING,this.onFragLoading,this),e.off(B.FRAG_LOADED,this.onFragLoaded,this),e.off(B.FRAG_BUFFERED,this.onFragBuffered,this),e.off(B.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(B.LEVEL_LOADED,this.onLevelLoaded,this),e.off(B.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(B.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(B.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=``}onFragLoading(e,t){let n=t.frag;this.ignoreFragment(n)||(n.bitrateTest||(this.fragCurrent=n,this.partCurrent=t.part??null),this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100))}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case z.BUFFER_ADD_CODEC_ERROR:case z.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case z.FRAG_LOAD_TIMEOUT:{let e=t.frag,{fragCurrent:n,partCurrent:r}=this;if(e&&n&&e.sn===n.sn&&e.level===n.level){let t=performance.now(),n=r?r.stats:e.stats,i=t-n.loading.start,a=n.loading.first?n.loading.first-n.loading.start:-1;if(n.loaded&&a>-1){let e=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(i-Math.min(e,a),n.loaded)}else this.bwEstimator.sampleTTFB(i)}break}}}getTimeToLoadFrag(e,t,n,r){return e+n/t+(r?e+this.lastLevelLoadSec:0)}onLevelLoaded(e,t){let n=this.hls.config,{loading:r}=t.stats,i=r.end-r.first;L(i)&&(this.lastLevelLoadSec=i/1e3),t.details.live?this.bwEstimator.update(n.abrEwmaSlowLive,n.abrEwmaFastLive):this.bwEstimator.update(n.abrEwmaSlowVoD,n.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:n}){let r=n?n.stats:t.stats;if(t.type===H.MAIN&&this.bwEstimator.sampleTTFB(r.loading.first-r.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){let e=n?n.duration:t.duration,i=this.hls.levels[t.level],a=(i.loaded?i.loaded.bytes:0)+r.loaded,o=(i.loaded?i.loaded.duration:0)+e;i.loaded={bytes:a,duration:o},i.realBitrate=Math.round(8*a/o)}if(t.bitrateTest){let e={stats:r,frag:t,part:n,id:t.type};this.onFragBuffered(B.FRAG_BUFFERED,e),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){let{frag:n,part:r}=t,i=r!=null&&r.stats.loaded?r.stats:n.stats;if(i.aborted||this.ignoreFragment(n))return;let a=i.parsing.end-i.loading.start-Math.min(i.loading.first-i.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,i.loaded),i.bwEstimate=this.getBwEstimate(),n.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==H.MAIN||e.sn===`initSegment`}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){let{maxAutoLevel:e,minAutoLevel:t}=this.hls,n=this.getBwEstimate(),r=this.hls.config.maxStarvationDelay,i=this.findBestLevel(n,t,e,0,r,1,1);if(i>-1)return i;let a=this.hls.firstLevel,o=Math.min(Math.max(a,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${a} clamped to ${o}`),o}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){let e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),n=this.lastLoadedFragLevel>-1;if(e!==-1&&(!t||!n||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;let r=t&&n?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){let t=this.hls.levels;if(t.length>Math.max(e,r)&&t[e].loadError<=t[r].loadError)return e}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){let{fragCurrent:e,partCurrent:t,hls:n}=this;if(n.levels.length<=1)return n.loadLevel;let{maxAutoLevel:r,config:i,minAutoLevel:a}=n,o=t?t.duration:e?e.duration:0,s=this.getBwEstimate(),c=this.getStarvationDelay(),l=i.abrBandWidthFactor,u=i.abrBandWidthUpFactor;if(c){let e=this.findBestLevel(s,a,r,c,0,l,u);if(e>=0)return this.rebufferNotice=-1,e}let d=o?Math.min(o,i.maxStarvationDelay):i.maxStarvationDelay;if(!c){let e=this.bitrateTestDelay;e&&(d=(o?Math.min(o,i.maxLoadingDelay):i.maxLoadingDelay)-e,this.info(`bitrate test took ${Math.round(1e3*e)}ms, set first fragment max fetchDuration to ${Math.round(1e3*d)} ms`),l=u=1)}let f=this.findBestLevel(s,a,r,c,d,l,u);if(this.rebufferNotice!==f&&(this.rebufferNotice=f,this.info(`${c?`rebuffering expected`:`buffer is empty`}, optimal quality level ${f}`)),f>-1)return f;let p=n.levels[a],m=n.loadLevelObj;return m&&p?.bitrate<m.bitrate?a:n.loadLevel}getStarvationDelay(){let e=this.hls,t=e.media;if(!t)return 1/0;let n=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,r=e.mainForwardBufferInfo;return(r?r.len:0)/n}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,n,r,i,a,o){var s;let c=r+i,l=this.lastLoadedFragLevel,u=l===-1?this.hls.firstLevel:l,{fragCurrent:d,partCurrent:f}=this,{levels:p,allAudioTracks:m,loadLevel:h,config:g}=this.hls;if(p.length===1)return 0;let _=p[u],v=!!((s=this.hls.latestLevelDetails)!=null&&s.live),y=h===-1||l===-1,b,x=`SDR`,S=_?.frameRate||0,{audioPreference:C,videoPreference:w}=g,T=this.audioTracksByGroup||=Ka(m),E=-1;if(y){if(this.firstSelection!==-1)return this.firstSelection;let r=Wa(this.codecTiers||=qa(p,T,t,n),x,e,C,w),{codecSet:i,videoRanges:a,minFramerate:o,minBitrate:s,minIndex:c,preferHDR:l}=r;E=c,b=i,x=l?a[a.length-1]:a[0],S=o,e=Math.max(e,s),this.log(`picked start tier ${Y(r)}`)}else b=_?.codecSet,x=_?.videoRange;let ee=f?f.duration:d?d.duration:0,D=this.bwEstimator.getEstimateTTFB()/1e3,te=[];for(let s=n;s>=t;s--){var ne;let t=p[s],d=s>u;if(!t)continue;if(g.useMediaCapabilities&&!t.supportedResult&&!t.supportedPromise){let n=navigator.mediaCapabilities;typeof n?.decodingInfo==`function`&&Ta(t,T,x,S,e,C)?(t.supportedPromise=Ea(t,T,n,this.supportedCache),t.supportedPromise.then(e=>{if(!this.hls)return;t.supportedResult=e;let n=this.hls.levels,r=n.indexOf(t);e.error?this.warn(`MediaCapabilities decodingInfo error: "${e.error}" for level ${r} ${Y(e)}`):e.supported?e.decodingInfoResults.some(e=>e.smooth===!1||e.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${r} not smooth or powerEfficient: ${Y(e)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${r} ${Y(e)}`),r>-1&&n.length>1&&(this.log(`Removing unsupported level ${r}`),this.hls.removeLevel(r),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(e=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${e}`)})):t.supportedResult=Ca}if((b&&t.codecSet!==b||x&&t.videoRange!==x||d&&S>t.frameRate||!d&&S>0&&S<t.frameRate||(ne=t.supportedResult)!=null&&(ne=ne.decodingInfoResults)!=null&&ne.some(e=>e.smooth===!1))&&(!y||s!==E)){te.push(s);continue}let m=t.details,_=(f?m?.partTarget:m?.averagetargetduration)||ee,w;w=d?o*e:a*e;let O=ee&&r>=ee*2&&i===0?t.averageBitrate:t.maxBitrate,k=this.getTimeToLoadFrag(D,w,O*_,m===void 0);if(w>=O&&(s===l||t.loadError===0&&t.fragmentError===0)&&(k<=D||!L(k)||v&&!this.bitrateTestDelay||k<c)){let e=this.forcedAutoLevel;return s!==h&&(e===-1||e!==h)&&(te.length&&this.trace(`Skipped level(s) ${te.join(`,`)} of ${n} max with CODECS and VIDEO-RANGE:"${p[te[0]].codecs}" ${p[te[0]].videoRange}; not compatible with "${b}" ${x}`),this.info(`switch candidate:${u}->${s} adjustedbw(${Math.round(w)})-bitrate=${Math.round(w-O)} ttfb:${D.toFixed(1)} avgDuration:${_.toFixed(1)} maxFetchDuration:${c.toFixed(1)} fetchDuration:${k.toFixed(1)} firstSelection:${y} codecSet:${t.codecSet} videoRange:${t.videoRange} hls.loadLevel:${h}`)),y&&(this.firstSelection=s),s}}return-1}set nextAutoLevel(e){let t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey=``,this._nextAutoLevel=t)}deriveNextAutoLevel(e){let{maxAutoLevel:t,minAutoLevel:n}=this.hls;return Math.min(Math.max(e,n),t)}},io={search:function(e,t){let n=0,r=e.length-1,i=null,a=null;for(;n<=r;){i=(n+r)/2|0,a=e[i];let o=t(a);if(o>0)n=i+1;else if(o<0)r=i-1;else return a}return null}};function ao(e,t,n){if(t===null||!Array.isArray(e)||!e.length||!L(t)||t<(e[0].programDateTime||0)||t>=(e[e.length-1].endProgramDateTime||0))return null;for(let r=0;r<e.length;++r){let i=e[r];if(lo(t,n,i))return i}return null}function oo(e,t,n=0,r=0,i=.005){let a=null;if(e){a=t[1+e.sn-t[0].sn]||null;let r=e.endDTS-n;r>0&&r<15e-7&&(n+=15e-7),a&&e.level!==a.level&&a.end<=e.end&&(a=t[2+e.sn-t[0].sn]||null)}else n===0&&t[0].start===0&&(a=t[0]);if(a&&((!e||e.level===a.level)&&co(n,r,a)===0||so(a,e,Math.min(i,r))))return a;let o=io.search(t,co.bind(null,n,r));return o&&(o!==e||!a)?o:a}function so(e,t,n){if(t&&t.start===0&&t.level<e.level&&(t.endPTS||0)>0){let r=t.tagList.reduce((e,t)=>(t[0]===`INF`&&(e+=parseFloat(t[1])),e),n);return e.start<=r}return!1}function co(e=0,t=0,n){if(n.start<=e&&n.start+n.duration>e)return 0;let r=Math.min(t,n.duration+(n.deltaPTS?n.deltaPTS:0));return n.start+n.duration-r<=e?1:n.start-r>e&&n.start?-1:0}function lo(e,t,n){let r=Math.min(t,n.duration+(n.deltaPTS?n.deltaPTS:0))*1e3;return(n.endProgramDateTime||0)-r>e}function uo(e,t,n){if(e&&e.startCC<=t&&e.endCC>=t){let r=e.fragments,{fragmentHint:i}=e;i&&(r=r.concat(i));let a;return io.search(r,e=>e.cc<t?1:e.cc>t?-1:(a=e,e.end<=n?1:e.start>n?-1:0)),a||null}return null}function fo(e){switch(e.details){case z.FRAG_LOAD_TIMEOUT:case z.KEY_LOAD_TIMEOUT:case z.LEVEL_LOAD_TIMEOUT:case z.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function po(e){return e.details.startsWith(`key`)}function mo(e){return po(e)&&!!e.frag&&!e.frag.decryptdata}function ho(e,t){let n=fo(t);return e.default[`${n?`timeout`:`error`}Retry`]}function go(e,t){let n=e.backoff===`linear`?1:2**t;return Math.min(n*e.retryDelayMs,e.maxRetryDelayMs)}function _o(e){return W(W({},e),{errorRetry:null,timeoutRetry:null})}function vo(e,t,n,r){if(!e)return!1;let i=r?.code,a=t<e.maxNumRetry&&(yo(i)||!!n);return e.shouldRetry?e.shouldRetry(e,t,n,r,a):a}function yo(e){return bo(e)||!!e&&(e<400||e>499)}function bo(e){return e===0&&navigator.onLine===!1}var xo={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},So={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8},Co=class extends Zr{constructor(e){super(`error-controller`,e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){let e=this.hls;e.on(B.ERROR,this.onError,this),e.on(B.MANIFEST_LOADING,this.onManifestLoading,this),e.on(B.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){let e=this.hls;e&&(e.off(B.ERROR,this.onError,this),e.off(B.ERROR,this.onErrorOut,this),e.off(B.MANIFEST_LOADING,this.onManifestLoading,this),e.off(B.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return e?.type===H.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;let t=this.hls,n=t.currentLevel;return(e=t.loadLevelObj)!=null&&e.details||n===-1?t.loadLevel:n}variantHasKey(e,t){if(e){var n;if((n=e.details)!=null&&n.hasKey(t))return!0;let r=e.audioGroups;if(r)return this.hls.allAudioTracks.filter(e=>r.indexOf(e.groupId)>=0).some(e=>e.details?.hasKey(t))}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var n;if(t.fatal)return;let r=this.hls,i=t.context;switch(t.details){case z.FRAG_LOAD_ERROR:case z.FRAG_LOAD_TIMEOUT:case z.KEY_LOAD_ERROR:case z.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case z.FRAG_PARSING_ERROR:if((n=t.frag)!=null&&n.gap){t.errorAction=wo();return}case z.FRAG_GAP:case z.FRAG_DECRYPT_ERROR:t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=xo.SendAlternateToPenaltyBox;return;case z.LEVEL_EMPTY_ERROR:case z.LEVEL_PARSING_ERROR:{var a;let e=t.parent===H.MAIN?t.level:r.loadLevel;t.details===z.LEVEL_EMPTY_ERROR&&(a=t.context)!=null&&(a=a.levelDetails)!=null&&a.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,e):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e))}return;case z.LEVEL_LOAD_ERROR:case z.LEVEL_LOAD_TIMEOUT:typeof i?.level==`number`&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.level));return;case z.AUDIO_TRACK_LOAD_ERROR:case z.AUDIO_TRACK_LOAD_TIMEOUT:case z.SUBTITLE_LOAD_ERROR:case z.SUBTITLE_TRACK_LOAD_TIMEOUT:if(i){let e=r.loadLevelObj;if(e&&(i.type===V.AUDIO_TRACK&&e.hasAudioGroup(i.groupId)||i.type===V.SUBTITLE_TRACK&&e.hasSubtitleGroup(i.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.loadLevel),t.errorAction.action=xo.SendAlternateToPenaltyBox,t.errorAction.flags=So.MoveAllAlternatesMatchingHost;return}}return;case z.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:xo.SendAlternateToPenaltyBox,flags:So.MoveAllAlternatesMatchingHDCP};return;case z.KEY_SYSTEM_SESSION_UPDATE_FAILED:case z.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case z.KEY_SYSTEM_NO_SESSION:t.errorAction={action:xo.SendAlternateToPenaltyBox,flags:So.MoveAllAlternatesMatchingKey};return;case z.BUFFER_ADD_CODEC_ERROR:case z.REMUX_ALLOC_ERROR:case z.BUFFER_APPEND_ERROR:t.errorAction||=this.getLevelSwitchAction(t,t.level??r.loadLevel);return;case z.INTERNAL_EXCEPTION:case z.BUFFER_APPENDING_ERROR:case z.BUFFER_FULL_ERROR:case z.LEVEL_SWITCH_ERROR:case z.BUFFER_STALLED_ERROR:case z.BUFFER_SEEK_OVER_HOLE:case z.BUFFER_NUDGE_ON_STALL:t.errorAction=wo();return}t.type===R.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=wo())}getPlaylistRetryOrSwitchAction(e,t){let n=this.hls,r=ho(n.config.playlistLoadPolicy,e),i=this.playlistError++;if(vo(r,i,fo(e),e.response))return{action:xo.RetryRequest,flags:So.None,retryConfig:r,retryCount:i};let a=this.getLevelSwitchAction(e,t);return r&&(a.retryConfig=r,a.retryCount=i),a}getFragRetryOrSwitchAction(e){let t=this.hls,n=this.getVariantLevelIndex(e.frag),r=t.levels[n],{fragLoadPolicy:i,keyLoadPolicy:a}=t.config,o=ho(po(e)?a:i,e),s=t.levels.reduce((e,t)=>e+t.fragmentError,0);if(r&&(e.details!==z.FRAG_GAP&&r.fragmentError++,!mo(e)&&vo(o,s,fo(e),e.response)))return{action:xo.RetryRequest,flags:So.None,retryConfig:o,retryCount:s};let c=this.getLevelSwitchAction(e,n);return o&&(c.retryConfig=o,c.retryCount=s),c}getLevelSwitchAction(e,t){let n=this.hls;t??=n.loadLevel;let r=this.hls.levels[t];if(r){let t=e.details;r.loadError++,t===z.BUFFER_APPEND_ERROR&&r.fragmentError++;let o=-1,{levels:s,loadLevel:c,minAutoLevel:l,maxAutoLevel:u}=n;!n.autoLevelEnabled&&!n.config.preserveManualLevelOnError&&(n.loadLevel=-1);let d=e.frag?.type,f=(d===H.AUDIO&&t===z.FRAG_PARSING_ERROR||e.sourceBufferName===`audio`&&(t===z.BUFFER_ADD_CODEC_ERROR||t===z.BUFFER_APPEND_ERROR))&&s.some(({audioCodec:e})=>r.audioCodec!==e),p=e.sourceBufferName===`video`&&(t===z.BUFFER_ADD_CODEC_ERROR||t===z.BUFFER_APPEND_ERROR)&&s.some(({codecSet:e,audioCodec:t})=>r.codecSet!==e&&r.audioCodec===t),{type:m,groupId:h}=e.context??{};for(let n=s.length;n--;){let g=(n+c)%s.length;if(g!==c&&g>=l&&g<=u&&s[g].loadError===0){var i,a;let n=s[g];if(t===z.FRAG_GAP&&d===H.MAIN&&e.frag){let t=s[g].details;if(t){let n=oo(e.frag,t.fragments,e.frag.start);if(n!=null&&n.gap)continue}}else if(m===V.AUDIO_TRACK&&n.hasAudioGroup(h)||m===V.SUBTITLE_TRACK&&n.hasSubtitleGroup(h))continue;else if(d===H.AUDIO&&(i=r.audioGroups)!=null&&i.some(e=>n.hasAudioGroup(e))||d===H.SUBTITLE&&(a=r.subtitleGroups)!=null&&a.some(e=>n.hasSubtitleGroup(e))||f&&r.audioCodec===n.audioCodec||p&&r.codecSet===n.codecSet||!f&&r.codecSet!==n.codecSet)continue;o=g;break}}if(o>-1&&n.loadLevel!==o)return e.levelRetry=!0,this.playlistError=0,{action:xo.SendAlternateToPenaltyBox,flags:So.None,nextAutoLevel:o}}return{action:xo.SendAlternateToPenaltyBox,flags:So.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){switch(t.errorAction?.action){case xo.DoNothing:break;case xo.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==z.FRAG_GAP?t.fatal=!0:/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break;case xo.RetryRequest:break}if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){let t=this.hls,n=e.errorAction;if(!n)return;let{flags:r}=n,i=n.nextAutoLevel;switch(r){case So.None:this.switchLevel(e,i);break;case So.MoveAllAlternatesMatchingHDCP:{let r=this.getVariantLevelIndex(e.frag),i=t.levels[r]?.attrs[`HDCP-LEVEL`];if(n.hdcpLevel=i,i===`NONE`)this.warn(`HDCP policy resticted output with HDCP-LEVEL=NONE`);else if(i){t.maxHdcpLevel=Ma[Ma.indexOf(i)-1],n.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case So.MoveAllAlternatesMatchingKey:{let t=e.decryptdata;if(t){let r=this.hls.levels,i=r.length;for(let n=i;n--;)this.variantHasKey(r[n],t)&&(this.log(`Banned key found in level ${n} (${r[n].bitrate}bps) or audio group "${r[n].audioGroups?.join(`,`)}" (${e.frag?.type} fragment) ${li(t.keyId||[])}`),r[n].fragmentError++,r[n].loadError++,this.log(`Removing level ${n} with key error (${e.error})`),this.hls.removeLevel(n));let a=e.frag;if(this.hls.levels.length<i)n.resolved=!0;else if(a&&a.type!==H.MAIN){let e=a.decryptdata;e&&!t.matches(e)&&(n.resolved=!0)}}break}}n.resolved||this.switchLevel(e,i)}switchLevel(e,t){if(t!==void 0&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===z.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!==`audiovideo`)){let t=ba(e.mimeType),n=this.hls.levels;for(let r=n.length;r--;)n[r][`${e.sourceBufferName}Codec`]===t&&(this.log(`Removing level ${r} for ${e.details} ("${t}" not supported)`),this.hls.removeLevel(r))}}};function wo(e){let t={action:xo.DoNothing,flags:So.None};return e&&(t.resolved=!0),t}var To={NOT_LOADED:`NOT_LOADED`,APPENDING:`APPENDING`,PARTIAL:`PARTIAL`,OK:`OK`},Eo=class{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){let{hls:e}=this;e&&(e.on(B.MANIFEST_LOADING,this.onManifestLoading,this),e.on(B.BUFFER_APPENDED,this.onBufferAppended,this),e.on(B.FRAG_BUFFERED,this.onFragBuffered,this),e.on(B.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){let{hls:e}=this;e&&(e.off(B.MANIFEST_LOADING,this.onManifestLoading,this),e.off(B.BUFFER_APPENDED,this.onBufferAppended,this),e.off(B.FRAG_BUFFERED,this.onFragBuffered,this),e.off(B.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){let n=this.activePartLists[t];if(n)for(let t=n.length;t--;){let r=n[t];if(!r)break;if(r.start<=e&&e<=r.end&&r.loaded)return r}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,n){let{fragments:r}=this,i=Object.keys(r);for(let a=i.length;a--;){let o=r[i[a]];if(o?.body.type===t&&(!n||o.buffered)){let t=o.body;if(t.start<=e&&e<=t.end)return t}}return null}detectEvictedFragments(e,t,n,r,i){this.timeRanges&&(this.timeRanges[e]=t);let a=r?.fragment.sn||-1;Object.keys(this.fragments).forEach(r=>{let o=this.fragments[r];if(!o||a>=o.body.sn)return;if(!o.buffered&&(!o.loaded||i)){o.body.type===n&&this.removeFragment(o.body);return}let s=o.range[e];if(s){if(s.time.length===0){this.removeFragment(o.body);return}s.time.some(e=>{let n=!this.isTimeBuffered(e.startPTS,e.endPTS,t);return n&&this.removeFragment(o.body),n})}})}detectPartialFragments(e){let t=this.timeRanges;if(!t||e.frag.sn===`initSegment`)return;let n=e.frag,r=Oo(n),i=this.fragments[r];if(!i||i.buffered&&n.gap)return;let a=!n.relurl;Object.keys(t).forEach(r=>{let o=n.elementaryStreams[r];if(!o)return;let s=t[r],c=a||o.partial===!0;i.range[r]=this.getBufferedTimes(n,e.part,c,s)}),i.loaded=null,Object.keys(i.range).length?(this.bufferedEnd(i,n),Do(i)||this.removeParts(n.sn-1,n.type)):this.removeFragment(i.body)}bufferedEnd(e,t){e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&(this.endListFragments[e.body.type]=e)}removeParts(e,t){let n=this.activePartLists[t];n&&(this.activePartLists[t]=ko(n,t=>t.fragment.sn>=e))}fragBuffered(e,t){let n=Oo(e),r=this.fragments[n];!r&&t&&(r=this.fragments[n]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),r&&(r.loaded=null,this.bufferedEnd(r,e))}getBufferedTimes(e,t,n,r){let i={time:[],partial:n},a=e.start,o=e.end,s=e.minEndPTS||o,c=e.maxStartPTS||a;for(let e=0;e<r.length;e++){let t=r.start(e)-this.bufferPadding,n=r.end(e)+this.bufferPadding;if(c>=t&&s<=n){i.time.push({startPTS:Math.max(a,r.start(e)),endPTS:Math.min(o,r.end(e))});break}else if(a<n&&o>t){let t=Math.max(a,r.start(e)),n=Math.min(o,r.end(e));n>t&&(i.partial=!0,i.time.push({startPTS:t,endPTS:n}))}else if(o<=t)break}return i}getPartialFragment(e){let t=null,n,r,i,a=0,{bufferPadding:o,fragments:s}=this;return Object.keys(s).forEach(c=>{let l=s[c];l&&Do(l)&&(r=l.body.start-o,i=l.body.end+o,e>=r&&e<=i&&(n=Math.min(e-r,i-e),a<=n&&(t=l.body,a=n)))}),t}isEndListAppended(e){let t=this.endListFragments[e];return t!==void 0&&(t.buffered||Do(t))}getState(e){let t=Oo(e),n=this.fragments[t];return n?n.buffered?Do(n)?To.PARTIAL:To.OK:To.APPENDING:To.NOT_LOADED}isTimeBuffered(e,t,n){let r,i;for(let a=0;a<n.length;a++){if(r=n.start(a)-this.bufferPadding,i=n.end(a)+this.bufferPadding,e>=r&&t<=i)return!0;if(t<=r)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(t.frag.sn===`initSegment`||t.frag.bitrateTest)return;let n=t.frag,r=t.part?null:t,i=Oo(n);this.fragments[i]={body:n,appendedPTS:null,loaded:r,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){let{frag:n,part:r,timeRanges:i,type:a}=t;if(n.sn===`initSegment`)return;let o=n.type;if(r){let e=this.activePartLists[o];e||(this.activePartLists[o]=e=[]),e.push(r)}this.timeRanges=i;let s=i[a];this.detectEvictedFragments(a,s,o,r)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){let t=Oo(e);return!!this.fragments[t]}hasFragments(e){let{fragments:t}=this,n=Object.keys(t);if(!e)return n.length>0;for(let r=n.length;r--;)if(t[n[r]]?.body.type===e)return!0;return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,n,r,i){r&&!this.hasGaps||Object.keys(this.fragments).forEach(a=>{let o=this.fragments[a];if(!o)return;let s=o.body;s.type!==n||r&&!s.gap||s.start<t&&s.end>e&&(o.buffered||i)&&this.removeFragment(s)})}removeFragment(e){let t=Oo(e);e.clearElementaryStreamInfo();let n=this.activePartLists[e.type];if(n){let t=e.sn;this.activePartLists[e.type]=ko(n,e=>e.fragment.sn!==t)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;let t=(e=this.hls)==null||(e=e.latestLevelDetails)==null?void 0:e.partList;t&&t.forEach(e=>e.clearElementaryStreamInfo())}};function Do(e){var t,n,r;return e.buffered&&!!(e.body.gap||(t=e.range.video)!=null&&t.partial||(n=e.range.audio)!=null&&n.partial||(r=e.range.audiovideo)!=null&&r.partial)}function Oo(e){return`${e.type}_${e.level}_${e.sn}`}function ko(e,t){return e.filter(e=>{let n=t(e);return n||e.clearElementaryStreamInfo(),n})}var Ao={cbc:0,ctr:1},jo=class{constructor(e,t,n){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=n}decrypt(e,t){switch(this.aesMode){case Ao.cbc:return this.subtle.decrypt({name:`AES-CBC`,iv:this.aesIV},t,e);case Ao.ctr:return this.subtle.decrypt({name:`AES-CTR`,counter:this.aesIV,length:64},t,e);default:throw Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}};function Mo(e){let t=e.byteLength,n=t&&new DataView(e.buffer).getUint8(t-1);return n?e.slice(0,t-n):e}var No=class{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array,this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){let t=new DataView(e),n=new Uint32Array(4);for(let e=0;e<4;e++)n[e]=t.getUint32(e*4);return n}initTable(){let e=this.sBox,t=this.invSBox,n=this.subMix,r=n[0],i=n[1],a=n[2],o=n[3],s=this.invSubMix,c=s[0],l=s[1],u=s[2],d=s[3],f=new Uint32Array(256),p=0,m=0,h=0;for(h=0;h<256;h++)h<128?f[h]=h<<1:f[h]=h<<1^283;for(h=0;h<256;h++){let n=m^m<<1^m<<2^m<<3^m<<4;n=n>>>8^n&255^99,e[p]=n,t[n]=p;let s=f[p],h=f[s],g=f[h],_=f[n]*257^n*16843008;r[p]=_<<24|_>>>8,i[p]=_<<16|_>>>16,a[p]=_<<8|_>>>24,o[p]=_,_=g*16843009^h*65537^s*257^p*16843008,c[n]=_<<24|_>>>8,l[n]=_<<16|_>>>16,u[n]=_<<8|_>>>24,d[n]=_,p?(p=s^f[f[f[g^s]]],m^=f[f[m]]):p=m=1}}expandKey(e){let t=this.uint8ArrayToUint32Array_(e),n=!0,r=0;for(;r<t.length&&n;)n=t[r]===this.key[r],r++;if(n)return;this.key=t;let i=this.keySize=t.length;if(i!==4&&i!==6&&i!==8)throw Error(`Invalid aes key size=`+i);let a=this.ksRows=(i+6+1)*4,o,s,c=this.keySchedule=new Uint32Array(a),l=this.invKeySchedule=new Uint32Array(a),u=this.sBox,d=this.rcon,f=this.invSubMix,p=f[0],m=f[1],h=f[2],g=f[3],_,v;for(o=0;o<a;o++){if(o<i){_=c[o]=t[o];continue}v=_,o%i===0?(v=v<<8|v>>>24,v=u[v>>>24]<<24|u[v>>>16&255]<<16|u[v>>>8&255]<<8|u[v&255],v^=d[o/i|0]<<24):i>6&&o%i===4&&(v=u[v>>>24]<<24|u[v>>>16&255]<<16|u[v>>>8&255]<<8|u[v&255]),c[o]=_=(c[o-i]^v)>>>0}for(s=0;s<a;s++)o=a-s,v=s&3?c[o]:c[o-4],s<4||o<=4?l[s]=v:l[s]=p[u[v>>>24]]^m[u[v>>>16&255]]^h[u[v>>>8&255]]^g[u[v&255]],l[s]=l[s]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,n){let r=this.keySize+6,i=this.invKeySchedule,a=this.invSBox,o=this.invSubMix,s=o[0],c=o[1],l=o[2],u=o[3],d=this.uint8ArrayToUint32Array_(n),f=d[0],p=d[1],m=d[2],h=d[3],g=new Int32Array(e),_=new Int32Array(g.length),v,y,b,x,S,C,w,T,E,ee,D,te,ne,O,k=this.networkToHostOrderSwap;for(;t<g.length;){for(E=k(g[t]),ee=k(g[t+1]),D=k(g[t+2]),te=k(g[t+3]),S=E^i[0],C=te^i[1],w=D^i[2],T=ee^i[3],ne=4,O=1;O<r;O++)v=s[S>>>24]^c[C>>16&255]^l[w>>8&255]^u[T&255]^i[ne],y=s[C>>>24]^c[w>>16&255]^l[T>>8&255]^u[S&255]^i[ne+1],b=s[w>>>24]^c[T>>16&255]^l[S>>8&255]^u[C&255]^i[ne+2],x=s[T>>>24]^c[S>>16&255]^l[C>>8&255]^u[w&255]^i[ne+3],S=v,C=y,w=b,T=x,ne+=4;v=a[S>>>24]<<24^a[C>>16&255]<<16^a[w>>8&255]<<8^a[T&255]^i[ne],y=a[C>>>24]<<24^a[w>>16&255]<<16^a[T>>8&255]<<8^a[S&255]^i[ne+1],b=a[w>>>24]<<24^a[T>>16&255]<<16^a[S>>8&255]<<8^a[C&255]^i[ne+2],x=a[T>>>24]<<24^a[S>>16&255]<<16^a[C>>8&255]<<8^a[w&255]^i[ne+3],_[t]=k(v^f),_[t+1]=k(x^p),_[t+2]=k(b^m),_[t+3]=k(y^h),f=E,p=ee,m=D,h=te,t+=4}return _.buffer}},Po=class{constructor(e,t,n){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=n}expandKey(){let e=Fo(this.aesMode);return this.subtle.importKey(`raw`,this.key,{name:e},!1,[`encrypt`,`decrypt`])}};function Fo(e){switch(e){case Ao.cbc:return`AES-CBC`;case Ao.ctr:return`AES-CTR`;default:throw Error(`[FastAESKey] invalid aes mode ${e}`)}}var Io=16,Lo=class{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{let e=self.crypto;e&&(this.subtle=e.subtle||e.webkitSubtle)}catch{}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){let{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;let n=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?Mo(n):n}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&=null}decrypt(e,t,n,r){return this.useSoftware?new Promise((i,a)=>{let o=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(o,t,n,r);let s=this.flush();s?i(s.buffer):a(Error(`[softwareDecrypt] Failed to decrypt data`))}):this.webCryptoDecrypt(new Uint8Array(e),t,n,r)}softwareDecrypt(e,t,n,r){let{currentIV:i,currentResult:a,remainderData:o}=this;if(r!==Ao.cbc||t.byteLength!==16)return G.warn(`SoftwareDecrypt: can only handle AES-128-CBC`),null;this.logOnce(`JS AES decrypt`),o&&(e=Gi(o,e),this.remainderData=null);let s=this.getValidChunk(e);if(!s.length)return null;i&&(n=i);let c=this.softwareDecrypter;c||=this.softwareDecrypter=new No,c.expandKey(t);let l=a;return this.currentResult=c.decrypt(s.buffer,0,n),this.currentIV=s.slice(-16).buffer,l||null}webCryptoDecrypt(e,t,n,r){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,n,r));this.key=t,this.fastAesKey=new Po(this.subtle,t,r)}return this.fastAesKey.expandKey().then(t=>this.subtle?(this.logOnce(`WebCrypto AES decrypt`),new jo(this.subtle,new Uint8Array(n),r).decrypt(e.buffer,t)):Promise.reject(Error(`web crypto not initialized`))).catch(i=>(G.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${i.name}: ${i.message}`),this.onWebCryptoError(e,t,n,r)))}onWebCryptoError(e,t,n,r){let i=this.enableSoftwareAES;if(i){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,n,r);let i=this.flush();if(i)return i.buffer}throw Error(`WebCrypto`+(i?` and softwareDecrypt`:``)+`: failed to decrypt data`)}getValidChunk(e){let t=e,n=e.length-e.length%Io;return n!==e.length&&(t=e.slice(0,n),this.remainderData=e.slice(n)),t}logOnce(e){this.logEnabled&&=(G.log(`[decrypter]: ${e}`),!1)}},Ro=2**17,zo=class{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&=(this.loader.destroy(),null)}abort(){this.loader&&this.loader.abort()}load(e,t){let n=e.url;if(!n)return Promise.reject(new Uo({type:R.NETWORK_ERROR,details:z.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:Error(`Fragment does not have a ${n?`part list`:`url`}`),networkDetails:null}));this.abort();let r=this.config,i=r.fLoader,a=r.loader;return new Promise((o,s)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(e=>e[0]===`GAP`)){s(Vo(e));return}else e.gap=!1;let c=this.loader=i?new i(r):new a(r),l=Bo(e);e.loader=c;let u=_o(r.fragLoadPolicy.default),d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn===`initSegment`?1/0:Ro};e.stats=c.stats;let f={onSuccess:(t,n,r,i)=>{this.resetLoader(e,c);let a=t.data;r.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(a.slice(0,16)),a=a.slice(16)),o({frag:e,part:null,payload:a,networkDetails:i})},onError:(t,r,i,a)=>{this.resetLoader(e,c),s(new Uo({type:R.NETWORK_ERROR,details:z.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:W({url:n,data:void 0},t),error:Error(`HTTP Error ${t.code} ${t.text}`),networkDetails:i,stats:a}))},onAbort:(t,n,r)=>{this.resetLoader(e,c),s(new Uo({type:R.NETWORK_ERROR,details:z.INTERNAL_ABORTED,fatal:!1,frag:e,error:Error(`Aborted`),networkDetails:r,stats:t}))},onTimeout:(t,n,r)=>{this.resetLoader(e,c),s(new Uo({type:R.NETWORK_ERROR,details:z.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:Error(`Timeout after ${d.timeout}ms`),networkDetails:r,stats:t}))}};t&&(f.onProgress=(n,r,i,a)=>t({frag:e,part:null,payload:i,networkDetails:a})),c.load(l,d,f)})}loadPart(e,t,n){this.abort();let r=this.config,i=r.fLoader,a=r.loader;return new Promise((o,s)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){s(Vo(e,t));return}let c=this.loader=i?new i(r):new a(r),l=Bo(e,t);e.loader=c;let u=_o(r.fragLoadPolicy.default),d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Ro};t.stats=c.stats,c.load(l,d,{onSuccess:(r,i,a,s)=>{this.resetLoader(e,c),this.updateStatsFromPart(e,t);let l={frag:e,part:t,payload:r.data,networkDetails:s};n(l),o(l)},onError:(n,r,i,a)=>{this.resetLoader(e,c),s(new Uo({type:R.NETWORK_ERROR,details:z.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:W({url:l.url,data:void 0},n),error:Error(`HTTP Error ${n.code} ${n.text}`),networkDetails:i,stats:a}))},onAbort:(n,r,i)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,c),s(new Uo({type:R.NETWORK_ERROR,details:z.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:Error(`Aborted`),networkDetails:i,stats:n}))},onTimeout:(n,r,i)=>{this.resetLoader(e,c),s(new Uo({type:R.NETWORK_ERROR,details:z.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:Error(`Timeout after ${d.timeout}ms`),networkDetails:i,stats:n}))}})})}updateStatsFromPart(e,t){let n=e.stats,r=t.stats,i=r.total;if(n.loaded+=r.loaded,i){let r=Math.round(e.duration/t.duration),a=Math.min(Math.round(n.loaded/i),r),o=(r-a)*Math.round(n.loaded/a);n.total=n.loaded+o}else n.total=Math.max(n.loaded,n.total);let a=n.loading,o=r.loading;a.start?a.first+=o.first-o.start:(a.start=o.start,a.first=o.first),a.end=o.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}};function Bo(e,t=null){let n=t||e,r={frag:e,part:t,responseType:`arraybuffer`,url:n.url,headers:{},rangeStart:0,rangeEnd:0},i=n.byteRangeStartOffset,a=n.byteRangeEndOffset;if(L(i)&&L(a)){let t=i,n=a;if(e.sn===`initSegment`&&Ho(e.decryptdata?.method)){let e=a-i;e%16&&(n=a+(16-e%16)),i!==0&&(r.resetIV=!0,t=i-16)}r.rangeStart=t,r.rangeEnd=n}return r}function Vo(e,t){let n=Error(`GAP ${e.gap?`tag`:`attribute`} found`),r={type:R.MEDIA_ERROR,details:z.FRAG_GAP,fatal:!1,frag:e,error:n,networkDetails:null};return t&&(r.part=t),(t||e).stats.aborted=!0,new Uo(r)}function Ho(e){return e===`AES-128`||e===`AES-256`}var Uo=class extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}},Wo=class extends Zr{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}},Go=class{constructor(e,t,n,r=0,i=-1,a=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=Ko(),this.buffering={audio:Ko(),video:Ko(),audiovideo:Ko()},this.level=e,this.sn=t,this.id=n,this.size=r,this.part=i,this.partial=a}};function Ko(){return{start:0,executeStart:0,executeEnd:0,end:0}}var qo={length:0,start:()=>0,end:()=>0},X=class e{static isBuffered(t,n){if(t){let r=e.getBuffered(t);for(let e=r.length;e--;)if(n>=r.start(e)&&n<=r.end(e))return!0}return!1}static bufferedRanges(t){if(t){let n=e.getBuffered(t);return e.timeRangesToArray(n)}return[]}static timeRangesToArray(e){let t=[];for(let n=0;n<e.length;n++)t.push({start:e.start(n),end:e.end(n)});return t}static bufferInfo(t,n,r){if(t){let i=e.bufferedRanges(t);if(i.length)return e.bufferedInfo(i,n,r)}return{len:0,start:n,end:n,bufferedIndex:-1}}static bufferedInfo(e,t,n){t=Math.max(0,t),e.length>1&&e.sort((e,t)=>e.start-t.start||t.end-e.end);let r=-1,i=[];if(n)for(let a=0;a<e.length;a++){t>=e[a].start&&t<=e[a].end&&(r=a);let o=i.length;if(o){let t=i[o-1].end;e[a].start-t<n?e[a].end>t&&(i[o-1].end=e[a].end):i.push(e[a])}else i.push(e[a])}else i=e;let a=0,o,s=t,c=t;for(let e=0;e<i.length;e++){let l=i[e].start,u=i[e].end;if(r===-1&&t>=l&&t<=u&&(r=e),t+n>=l&&t<u)s=l,c=u,a=c-t;else if(t+n<l){o=l;break}}return{len:a,start:s||0,end:c||0,nextStart:o,buffered:e,bufferedIndex:r}}static getBuffered(e){try{return e.buffered||qo}catch(e){return G.log(`failed to get media.buffered`,e),qo}}},Jo=/\{\$([a-zA-Z0-9-_]+)\}/g;function Yo(e){return Jo.test(e)}function Xo(e,t){if(e.variableList!==null||e.hasVariableRefs){let n=e.variableList;return t.replace(Jo,t=>{let r=t.substring(2,t.length-1),i=n?.[r];return i===void 0?(e.playlistParsingError||=Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${r}"`),t):i})}return t}function Zo(e,t,n){let r=e.variableList;r||(e.variableList=r={});let i,a;if(`QUERYPARAM`in t){i=t.QUERYPARAM;try{let e=new self.URL(n).searchParams;if(e.has(i))a=e.get(i);else throw Error(`"${i}" does not match any query parameter in URI: "${n}"`)}catch(t){e.playlistParsingError||=Error(`EXT-X-DEFINE QUERYPARAM: ${t.message}`)}}else i=t.NAME,a=t.VALUE;i in r?e.playlistParsingError||=Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${i}"`):r[i]=a||``}function Qo(e,t,n){let r=t.IMPORT;if(n&&r in n){let t=e.variableList;t||(e.variableList=t={}),t[r]=n[r]}else e.playlistParsingError||=Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${r}"`)}var $o=/^(\d+)x(\d+)$/,es=/(.+?)=(".*?"|.*?)(?:,|$)/g,ts=class e{constructor(t,n){typeof t==`string`&&(t=e.parseAttrList(t,n)),U(this,t)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)===`X-`)}decimalInteger(e){let t=parseInt(this[e],10);return t>2**53-1?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||`0x`).slice(2);t=(t.length&1?`0`:``)+t;let n=new Uint8Array(t.length/2);for(let e=0;e<t.length/2;e++)n[e]=parseInt(t.slice(e*2,e*2+2),16);return n}return null}hexadecimalIntegerAsNumber(e){let t=parseInt(this[e],16);return t>2**53-1?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){let n=this[e];return n?parseFloat(n):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){let n=this[e];return(n?n.split(/[ ,]+/):[]).reduce((e,t)=>(e[t.toLowerCase()]=!0,e),t)}bool(e){return this[e]===`YES`}decimalResolution(e){let t=$o.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let n,r={};for(es.lastIndex=0;(n=es.exec(e))!==null;){let i=n[1].trim(),a=n[2],o=a.indexOf(`"`)===0&&a.lastIndexOf(`"`)===a.length-1,s=!1;if(o)a=a.slice(1,-1);else switch(i){case`IV`:case`SCTE35-CMD`:case`SCTE35-IN`:case`SCTE35-OUT`:s=!0}if(t&&(o||s))a=Xo(t,a);else if(!s&&!o)switch(i){case`CLOSED-CAPTIONS`:if(a===`NONE`)break;case`ALLOWED-CPC`:case`CLASS`:case`ASSOC-LANGUAGE`:case`AUDIO`:case`BYTERANGE`:case`CHANNELS`:case`CHARACTERISTICS`:case`CODECS`:case`DATA-ID`:case`END-DATE`:case`GROUP-ID`:case`ID`:case`IMPORT`:case`INSTREAM-ID`:case`KEYFORMAT`:case`KEYFORMATVERSIONS`:case`LANGUAGE`:case`NAME`:case`PATHWAY-ID`:case`QUERYPARAM`:case`RECENTLY-REMOVED-DATERANGES`:case`SERVER-URI`:case`STABLE-RENDITION-ID`:case`STABLE-VARIANT-ID`:case`START-DATE`:case`SUBTITLES`:case`SUPPLEMENTAL-CODECS`:case`URI`:case`VALUE`:case`VIDEO`:case`X-ASSET-LIST`:case`X-ASSET-URI`:G.warn(`${e}: attribute ${i} is missing quotes`)}r[i]=a}return r}},ns=`com.apple.hls.interstitial`;function rs(e){return e!==`ID`&&e!==`CLASS`&&e!==`CUE`&&e!==`START-DATE`&&e!==`DURATION`&&e!==`END-DATE`&&e!==`END-ON-NEXT`}function is(e){return e===`SCTE35-OUT`||e===`SCTE35-IN`||e===`SCTE35-CMD`}var as=class{constructor(e,t,n=0){if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=t?.tagAnchor||null,this.tagOrder=t?.tagOrder??n,t){let n=t.attr;for(let t in n)if(Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==n[t]){G.warn(`DATERANGE tag attribute: "${t}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=t;break}e=U(new ts({}),n,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e[`START-DATE`]),`END-DATE`in this.attr){let e=t?.endDate||new Date(this.attr[`END-DATE`]);L(e.getTime())&&(this._endDate=e)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){let e=this._cue;return e===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?`CUE`:`X-CUE`,{pre:!1,post:!1,once:!1}):e}get startTime(){let{tagAnchor:e}=this;return e===null||e.programDateTime===null?(G.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){let e=this._endDate||this._dateAtEnd;if(e)return e;let t=this.duration;return t===null?null:this._dateAtEnd=new Date(this._startDate.getTime()+t*1e3)}get duration(){if(`DURATION`in this.attr){let e=this.attr.decimalFloatingPoint(`DURATION`);if(L(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return`PLANNED-DURATION`in this.attr?this.attr.decimalFloatingPoint(`PLANNED-DURATION`):null}get endOnNext(){return this.attr.bool(`END-ON-NEXT`)}get isInterstitial(){return this.class===ns}get isValid(){return!!this.id&&!this._badValueForSameId&&L(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||`X-ASSET-URI`in this.attr||`X-ASSET-LIST`in this.attr)}},os=10,ss=class{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8=``,this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}let t=this.lastPartSn-e.lastPartSn,n=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!n||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&n>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let n=t.decryptdata;return n||=(t.setKeyFormat(e.keyFormat),t.decryptdata),!!n&&e.matches(n)})}get hasProgramDateTime(){return this.fragments.length?L(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||os}get drift(){let e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){let e=this.partList;if(e){let t=this.lastPartIndex;if(t!==-1){for(let n=e.length;n--;)if(e[n].index>t)return e[n].index;return t}}return 0}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){let e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}};function cs(e,t){return e.length===t.length?!e.some((e,n)=>e!==t[n]):!1}function ls(e,t){return!e&&!t?!0:!e||!t?!1:cs(e,t)}function us(e){return e===`AES-128`||e===`AES-256`||e===`AES-256-CTR`}function ds(e){switch(e){case`AES-128`:case`AES-256`:return Ao.cbc;case`AES-256-CTR`:return Ao.ctr;default:throw Error(`invalid full segment method ${e}`)}}function fs(e){return Uint8Array.from(atob(e),e=>e.charCodeAt(0))}function ps(e){return Uint8Array.from(unescape(encodeURIComponent(e)),e=>e.charCodeAt(0))}function ms(e){let t=ps(e).subarray(0,16),n=new Uint8Array(16);return n.set(t,16-t.length),n}function hs(e){let t=function(e,t,n){let r=e[t];e[t]=e[n],e[n]=r};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}function gs(e){let t=e.split(`:`),n=null;if(t[0]===`data`&&t.length===2){let e=t[1].split(`;`),r=e[e.length-1].split(`,`);if(r.length===2){let t=r[0]===`base64`,i=r[1];t?(e.splice(-1,1),n=fs(i)):n=ms(i)}}return n}var _s=typeof self<`u`?self:void 0,vs={CLEARKEY:`org.w3.clearkey`,FAIRPLAY:`com.apple.fps`,PLAYREADY:`com.microsoft.playready`,WIDEVINE:`com.widevine.alpha`},ys={CLEARKEY:`org.w3.clearkey`,FAIRPLAY:`com.apple.streamingkeydelivery`,PLAYREADY:`com.microsoft.playready`,WIDEVINE:`urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed`};function bs(e){switch(e){case ys.FAIRPLAY:return vs.FAIRPLAY;case ys.PLAYREADY:return vs.PLAYREADY;case ys.WIDEVINE:return vs.WIDEVINE;case ys.CLEARKEY:return vs.CLEARKEY}}function xs(e){switch(e){case vs.FAIRPLAY:return ys.FAIRPLAY;case vs.PLAYREADY:return ys.PLAYREADY;case vs.WIDEVINE:return ys.WIDEVINE;case vs.CLEARKEY:return ys.CLEARKEY}}function Ss(e){let{drmSystems:t,widevineLicenseUrl:n}=e,r=t?[vs.FAIRPLAY,vs.WIDEVINE,vs.PLAYREADY,vs.CLEARKEY].filter(e=>!!t[e]):[];return!r[vs.WIDEVINE]&&n&&r.push(vs.WIDEVINE),r}var Cs=function(e){return _s!=null&&(e=_s.navigator)!=null&&e.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function ws(e,t,n,r){let i;switch(e){case vs.FAIRPLAY:i=[`cenc`,`sinf`];break;case vs.WIDEVINE:case vs.PLAYREADY:i=[`cenc`];break;case vs.CLEARKEY:i=[`cenc`,`keyids`];break;default:throw Error(`Unknown key-system: ${e}`)}return Ts(i,t,n,r)}function Ts(e,t,n,r){return[{initDataTypes:e,persistentState:r.persistentState||`optional`,distinctiveIdentifier:r.distinctiveIdentifier||`optional`,sessionTypes:r.sessionTypes||[r.sessionType||`temporary`],audioCapabilities:t.map(e=>({contentType:`audio/mp4; codecs=${e}`,robustness:r.audioRobustness||``,encryptionScheme:r.audioEncryptionScheme||null})),videoCapabilities:n.map(e=>({contentType:`video/mp4; codecs=${e}`,robustness:r.videoRobustness||``,encryptionScheme:r.videoEncryptionScheme||null}))}]}function Es(e){var t;return!!e&&(e.sessionType===`persistent-license`||!!((t=e.sessionTypes)!=null&&t.some(e=>e===`persistent-license`)))}function Ds(e){let t=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),n=String.fromCharCode.apply(null,Array.from(t)),r=n.substring(n.indexOf(`<`),n.length),i=new DOMParser().parseFromString(r,`text/xml`).getElementsByTagName(`KID`)[0];if(i){let e=i.childNodes[0]?i.childNodes[0].nodeValue:i.getAttribute(`VALUE`);if(e){let t=fs(e).subarray(0,16);return hs(t),t}}return null}var Os={},ks=class e{static clearKeyUriToKeyIdMap(){Os={}}static setKeyIdForUri(e,t){Os[e]=t}static addKeyIdForUri(e){let t=Object.keys(Os).length%(2**53-1),n=new Uint8Array(16);return new DataView(n.buffer,12,4).setUint32(0,t),Os[e]=n,n}constructor(e,t,n,r=[1],i=null,a){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=n,this.keyFormatVersions=r,this.iv=i,this.encrypted=e?e!==`NONE`:!1,this.isCommonEncryption=this.encrypted&&!us(e),a!=null&&a.startsWith(`0x`)&&(this.keyId=new Uint8Array(ui(a)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&cs(e.keyFormatVersions,this.keyFormatVersions)&&ls(e.iv,this.iv)&&ls(e.keyId,this.keyId)}isSupported(){if(this.method){if(us(this.method)||this.method===`NONE`)return!0;if(this.keyFormat===`identity`)return this.method===`SAMPLE-AES`;switch(this.keyFormat){case ys.FAIRPLAY:case ys.WIDEVINE:case ys.PLAYREADY:case ys.CLEARKEY:return[`SAMPLE-AES`,`SAMPLE-AES-CENC`,`SAMPLE-AES-CTR`].indexOf(this.method)!==-1}}return!1}getDecryptData(t,n){if(!this.encrypted||!this.uri)return null;if(us(this.method)){let n=this.iv;return n||=(typeof t!=`number`&&(G.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0),Ms(t)),new e(this.method,this.uri,`identity`,this.keyFormatVersions,n)}if(this.keyId){let t=Os[this.uri];if(t&&!cs(this.keyId,t)&&e.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}let r=gs(this.uri);if(r)switch(this.keyFormat){case ys.WIDEVINE:if(this.pssh=r,!this.keyId){let e=ea(r.buffer);if(e.length){var i;let t=e[0];this.keyId=(i=t.kids)!=null&&i.length?t.kids[0]:null}}this.keyId||=js(n);break;case ys.PLAYREADY:this.pssh=$i(new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]),null,r),this.keyId=Ds(r);break;default:{let e=r.subarray(0,16);if(e.length!==16){let t=new Uint8Array(16);t.set(e,16-e.length),e=t}this.keyId=e;break}}if(!this.keyId||this.keyId.byteLength!==16){let t;t=As(n),t||(t=js(n),t||=Os[this.uri]),t&&(this.keyId=t,e.setKeyIdForUri(this.uri,t))}return this}};function As(e){let t=e?.[ys.WIDEVINE];return t?t.keyId:null}function js(e){let t=e?.[ys.PLAYREADY];if(t){let e=gs(t.uri);if(e)return Ds(e)}return null}function Ms(e){let t=new Uint8Array(16);for(let n=12;n<16;n++)t[n]=e>>8*(15-n)&255;return t}var Ns=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,Ps=/#EXT-X-MEDIA:(.*)/g,Fs=/^#EXT(?:INF|-X-TARGETDURATION):/m,Is=new RegExp([`#EXTINF:\\s*(\\d*(?:\\.\\d+)?)(?:,(.*)\\s+)?`,`(?!#) *(\\S[^\\r\\n]*)`,`#.*`].join(`|`),`g`),Ls=new RegExp([`#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)`,`#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\\d+)`,`#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)`,`(#)([^:]*):(.*)`,`(#)(.*)(?:.*)\\r?\\n?`].join(`|`)),Rs=class e{static findGroup(e,t){for(let n=0;n<e.length;n++){let r=e[n];if(r.id===t)return r}}static resolve(e,t){return hi.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return Fs.test(e)}static parseMasterPlaylist(t,n){let r={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:Yo(t)},i=[];if(Ns.lastIndex=0,!t.startsWith(`#EXTM3U`))return r.playlistParsingError=Error(`no EXTM3U delimiter`),r;let a;for(;(a=Ns.exec(t))!=null;)if(a[1]){var o;let t=new ts(a[1],r),s=Xo(r,a[2]),c={attrs:t,bitrate:t.decimalInteger(`BANDWIDTH`)||t.decimalInteger(`AVERAGE-BANDWIDTH`),name:t.NAME,url:e.resolve(s,n)},l=t.decimalResolution(`RESOLUTION`);l&&(c.width=l.width,c.height=l.height),Us(t.CODECS,c);let u=t[`SUPPLEMENTAL-CODECS`];u&&(c.supplemental={},Us(u,c.supplemental)),(o=c.unknownCodecs)!=null&&o.length||i.push(c),r.levels.push(c)}else if(a[3]){let t=a[3],i=a[4];switch(t){case`SESSION-DATA`:{let e=new ts(i,r),t=e[`DATA-ID`];t&&(r.sessionData===null&&(r.sessionData={}),r.sessionData[t]=e);break}case`SESSION-KEY`:{let e=Vs(i,n,r);e.encrypted&&e.isSupported()?(r.sessionKeys===null&&(r.sessionKeys=[]),r.sessionKeys.push(e)):G.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${i}"`);break}case`DEFINE`:Zo(r,new ts(i,r),n);break;case`CONTENT-STEERING`:{let t=new ts(i,r);r.contentSteering={uri:e.resolve(t[`SERVER-URI`],n),pathwayId:t[`PATHWAY-ID`]||`.`};break}case`START`:r.startTimeOffset=Hs(i);break}}return r.levels=i.length>0&&i.length<r.levels.length?i:r.levels,r.levels.length===0&&(r.playlistParsingError=Error(`no levels found in manifest`)),r}static parseMasterPlaylistMedia(t,n,r){let i,a={},o=r.levels,s={AUDIO:o.map(e=>({id:e.attrs.AUDIO,audioCodec:e.audioCodec})),SUBTITLES:o.map(e=>({id:e.attrs.SUBTITLES,textCodec:e.textCodec})),"CLOSED-CAPTIONS":[]},c=0;for(Ps.lastIndex=0;(i=Ps.exec(t))!==null;){let t=new ts(i[1],r),o=t.TYPE;if(o){let r=s[o],i=a[o]||[];a[o]=i;let l=t.LANGUAGE,u=t[`ASSOC-LANGUAGE`],d=t.CHANNELS,f=t.CHARACTERISTICS,p=t[`INSTREAM-ID`],m={attrs:t,bitrate:0,id:c++,groupId:t[`GROUP-ID`]||``,name:t.NAME||l||``,type:o,default:t.bool(`DEFAULT`),autoselect:t.bool(`AUTOSELECT`),forced:t.bool(`FORCED`),lang:l,url:t.URI?e.resolve(t.URI,n):``};if(u&&(m.assocLang=u),d&&(m.channels=d),f&&(m.characteristics=f),p&&(m.instreamId=p),r!=null&&r.length){let t=e.findGroup(r,m.groupId)||r[0];Ws(m,t,`audioCodec`),Ws(m,t,`textCodec`)}i.push(m)}}return a}static parseLevelPlaylist(e,t,n,r,i,a){let o={url:t},s=new ss(t),c=s.fragments,l=[],u=null,d=0,f=0,p=0,m=0,h=0,g=null,_=new yi(r,o),v,y,b,x=-1,S=!1,C=null,w;if(Is.lastIndex=0,s.m3u8=e,s.hasVariableRefs=Yo(e),Is.exec(e)?.[0]!==`#EXTM3U`)return s.playlistParsingError=Error(`Missing format identifier #EXTM3U`),s;for(;(v=Is.exec(e))!==null;){S&&(S=!1,_=new yi(r,o),_.playlistOffset=p,_.setStart(p),_.sn=d,_.cc=m,h&&(_.bitrate=h),_.level=n,u&&(_.initSegment=u,u.rawProgramDateTime&&(_.rawProgramDateTime=u.rawProgramDateTime,u.rawProgramDateTime=null),C&&=(_.setByteRange(C),null)));let e=v[1];if(e){_.duration=parseFloat(e);let t=(` `+v[2]).slice(1);_.title=t||null,_.tagList.push(t?[`INF`,e,t]:[`INF`,e])}else if(v[3]){if(L(_.duration)){_.playlistOffset=p,_.setStart(p),b&&Js(_,b,s),_.sn=d,_.level=n,_.cc=m,c.push(_);let e=(` `+v[3]).slice(1);_.relurl=Xo(s,e),Ks(_,g,l),g=_,p+=_.duration,d++,f=0,S=!0}}else{if(v=v[0].match(Ls),!v){G.warn(`No matches on slow regex match for level playlist!`);continue}for(y=1;y<v.length&&v[y]===void 0;y++);let e=(` `+v[y]).slice(1),i=(` `+v[y+1]).slice(1),l=v[y+2]?(` `+v[y+2]).slice(1):null;switch(e){case`BYTERANGE`:g?_.setByteRange(i,g):_.setByteRange(i);break;case`PROGRAM-DATE-TIME`:_.rawProgramDateTime=i,_.tagList.push([`PROGRAM-DATE-TIME`,i]),x===-1&&(x=c.length);break;case`PLAYLIST-TYPE`:s.type&&Ys(s,e,v),s.type=i.toUpperCase();break;case`MEDIA-SEQUENCE`:s.startSN===0?c.length>0&&Xs(s,e,v):Ys(s,e,v),d=s.startSN=parseInt(i);break;case`SKIP`:{s.skippedSegments&&Ys(s,e,v);let t=new ts(i,s),n=t.decimalInteger(`SKIPPED-SEGMENTS`);if(L(n)){s.skippedSegments+=n;for(let e=n;e--;)c.push(null);d+=n}let r=t.enumeratedString(`RECENTLY-REMOVED-DATERANGES`);r&&(s.recentlyRemovedDateranges=(s.recentlyRemovedDateranges||[]).concat(r.split(` `)));break}case`TARGETDURATION`:s.targetduration!==0&&Ys(s,e,v),s.targetduration=Math.max(parseInt(i),1);break;case`VERSION`:s.version!==null&&Ys(s,e,v),s.version=parseInt(i);break;case`INDEPENDENT-SEGMENTS`:break;case`ENDLIST`:s.live||Ys(s,e,v),s.live=!1;break;case`#`:(i||l)&&_.tagList.push(l?[i,l]:[i]);break;case`DISCONTINUITY`:m++,_.tagList.push([`DIS`]);break;case`GAP`:_.gap=!0,_.tagList.push([e]);break;case`BITRATE`:_.tagList.push([e,i]),h=parseInt(i)*1e3,L(h)?_.bitrate=h:h=0;break;case`DATERANGE`:{let e=new ts(i,s),t=new as(e,s.dateRanges[e.ID],s.dateRangeTagCount);s.dateRangeTagCount++,t.isValid||s.skippedSegments?s.dateRanges[t.id]=t:G.warn(`Ignoring invalid DATERANGE tag: "${i}"`),_.tagList.push([`EXT-X-DATERANGE`,i]);break}case`DEFINE`:{let e=new ts(i,s);`IMPORT`in e?Qo(s,e,a):Zo(s,e,t)}break;case`DISCONTINUITY-SEQUENCE`:s.startCC===0?c.length>0&&Xs(s,e,v):Ys(s,e,v),s.startCC=m=parseInt(i);break;case`KEY`:{let e=Vs(i,t,s);if(e.isSupported()){if(e.method===`NONE`){b=void 0;break}b||={};let t=b[e.keyFormat];t!=null&&t.matches(e)||(t&&(b=U({},b)),b[e.keyFormat]=e)}else G.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${i}"`);break}case`START`:s.startTimeOffset=Hs(i);break;case`MAP`:{let e=new ts(i,s);if(_.duration){let t=new yi(r,o);qs(t,e,n,b),u=t,_.initSegment=u,u.rawProgramDateTime&&!_.rawProgramDateTime&&(_.rawProgramDateTime=u.rawProgramDateTime)}else{let t=_.byteRangeEndOffset;if(t){let e=_.byteRangeStartOffset;C=`${t-e}@${e}`}else C=null;qs(_,e,n,b),u=_,S=!0}u.cc=m;break}case`SERVER-CONTROL`:w&&Ys(s,e,v),w=new ts(i),s.canBlockReload=w.bool(`CAN-BLOCK-RELOAD`),s.canSkipUntil=w.optionalFloat(`CAN-SKIP-UNTIL`,0),s.canSkipDateRanges=s.canSkipUntil>0&&w.bool(`CAN-SKIP-DATERANGES`),s.partHoldBack=w.optionalFloat(`PART-HOLD-BACK`,0),s.holdBack=w.optionalFloat(`HOLD-BACK`,0);break;case`PART-INF`:s.partTarget&&Ys(s,e,v),s.partTarget=new ts(i).decimalFloatingPoint(`PART-TARGET`);break;case`PART`:{let e=s.partList;e||=s.partList=[];let t=f>0?e[e.length-1]:void 0,n=f++,r=new bi(new ts(i,s),_,o,n,t);e.push(r),_.duration+=r.duration;break}case`PRELOAD-HINT`:s.preloadHint=new ts(i,s);break;case`RENDITION-REPORT`:{let e=new ts(i,s);s.renditionReports=s.renditionReports||[],s.renditionReports.push(e);break}default:G.warn(`line parsed but not handled: ${v}`);break}}}g&&!g.relurl?(c.pop(),p-=g.duration,s.partList&&(s.fragmentHint=g)):s.partList&&(Ks(_,g,l),_.cc=m,s.fragmentHint=_,b&&Js(_,b,s)),s.targetduration||(s.playlistParsingError=Error(`Missing Target Duration`));let T=c.length,E=c[0],ee=c[T-1];if(p+=s.skippedSegments*s.targetduration,p>0&&T&&ee){s.averagetargetduration=p/T;let e=ee.sn;s.endSN=e===`initSegment`?0:e,s.live||(ee.endList=!0),x>0&&(Gs(c,x),E&&l.unshift(E))}return s.fragmentHint&&(p+=s.fragmentHint.duration),s.totalduration=p,l.length&&s.dateRangeTagCount&&E&&zs(l,s),s.endCC=m,s}};function zs(e,t){let n=e.length;if(!n)if(t.hasProgramDateTime){let r=t.fragments[t.fragments.length-1];e.push(r),n++}else return;let r=e[n-1],i=t.live?1/0:t.totalduration,a=Object.keys(t.dateRanges);for(let o=a.length;o--;){let s=t.dateRanges[a[o]],c=s.startDate.getTime();s.tagAnchor=r.ref;for(let r=n;r--&&!(e[r]?.sn<t.startSN);){let n=Bs(t,c,e,r,i);if(n!==-1){s.tagAnchor=t.fragments[n].ref;break}}}}function Bs(e,t,n,r,i){let a=n[r];if(a){let o=a.programDateTime;if((t>=o||r===0)&&t<=o+((n[r+1]?.start||i)-a.start)*1e3){let i=n[r].sn-e.startSN;if(i<0)return-1;let a=e.fragments;if(a.length>n.length){let o=(n[r+1]||a[a.length-1]).sn-e.startSN;for(let e=o;e>i;e--){let n=a[e].programDateTime;if(t>=n&&t<n+a[e].duration*1e3)return e}}return i}}return-1}function Vs(e,t,n){let r=new ts(e,n),i=r.METHOD??``,a=r.URI,o=r.hexadecimalInteger(`IV`),s=r.KEYFORMATVERSIONS,c=r.KEYFORMAT??`identity`;return a&&r.IV&&!o&&G.error(`Invalid IV: ${r.IV}`),new ks(i,a?Rs.resolve(a,t):``,c,(s||`1`).split(`/`).map(Number).filter(Number.isFinite),o,r.KEYID)}function Hs(e){let t=new ts(e).decimalFloatingPoint(`TIME-OFFSET`);return L(t)?t:null}function Us(e,t){let n=(e||``).split(/[ ,]+/).filter(e=>e);[`video`,`audio`,`text`].forEach(e=>{let r=n.filter(t=>ia(t,e));r.length&&(t[`${e}Codec`]=r.map(e=>e.split(`/`)[0]).join(`,`),n=n.filter(e=>r.indexOf(e)===-1))}),t.unknownCodecs=n}function Ws(e,t,n){let r=t[n];r&&(e[n]=r)}function Gs(e,t){let n=e[t];for(let r=t;r--;){let t=e[r];if(!t)return;t.programDateTime=n.programDateTime-t.duration*1e3,n=t}}function Ks(e,t,n){e.rawProgramDateTime?n.push(e):t!=null&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime)}function qs(e,t,n,r){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=n,e.sn=`initSegment`,r&&(e.levelkeys=r),e.initSegment=null}function Js(e,t,n){e.levelkeys=t;let{encryptedFragments:r}=n;(!r.length||r[r.length-1].levelkeys!==t)&&Object.keys(t).some(e=>t[e].isCommonEncryption)&&r.push(e)}function Ys(e,t,n){e.playlistParsingError=Error(`#EXT-X-${t} must not appear more than once (${n[0]})`)}function Xs(e,t,n){e.playlistParsingError=Error(`#EXT-X-${t} must appear before the first Media Segment (${n[0]})`)}function Zs(e,t){let n=t.startPTS;if(L(n)){let r=0,i;t.sn>e.sn?(r=n-e.start,i=e):(r=e.start-n,i=t),i.duration!==r&&i.setDuration(r)}else t.sn>e.sn?e.cc===t.cc&&e.minEndPTS?t.setStart(e.start+(e.minEndPTS-e.start)):t.setStart(e.start+e.duration):t.setStart(Math.max(e.start-t.duration,0))}function Qs(e,t,n,r,i,a,o){r-n<=0&&(o.warn(`Fragment should have a positive duration`,t),r=n+t.duration,a=i+t.duration);let s=n,c=r,l=t.startPTS,u=t.endPTS;if(L(l)){let d=Math.abs(l-n);e&&d>e.totalduration?o.warn(`media timestamps and playlist times differ by ${d}s for level ${t.level} ${e.url}`):L(t.deltaPTS)?t.deltaPTS=Math.max(d,t.deltaPTS):t.deltaPTS=d,s=Math.max(n,l),n=Math.min(n,l),i=t.startDTS===void 0?i:Math.min(i,t.startDTS),c=Math.min(r,u),r=Math.max(r,u),a=t.endDTS===void 0?a:Math.max(a,t.endDTS)}let d=n-t.start;t.start!==0&&t.setStart(n),t.setDuration(r-t.start),t.startPTS=n,t.maxStartPTS=s,t.startDTS=i,t.endPTS=r,t.minEndPTS=c,t.endDTS=a;let f=t.sn;if(!e||f<e.startSN||f>e.endSN)return 0;let p,m=f-e.startSN,h=e.fragments;for(h[m]=t,p=m;p>0;p--)Zs(h[p],h[p-1]);for(p=m;p<h.length-1;p++)Zs(h[p],h[p+1]);return e.fragmentHint&&Zs(h[h.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,d}function $s(e,t,n){if(e===t)return;let r=null,i=e.fragments;for(let e=i.length-1;e>=0;e--){let t=i[e].initSegment;if(t){r=t;break}}e.fragmentHint&&delete e.fragmentHint.endPTS;let a;nc(e,t,(e,n,i,o)=>{if((!t.startCC||t.skippedSegments)&&n.cc!==e.cc){let r=e.cc-n.cc;for(let e=i;e<o.length;e++)o[e].cc+=r;t.endCC=o[o.length-1].cc}L(e.startPTS)&&L(e.endPTS)&&(n.setStart(n.startPTS=e.startPTS),n.startDTS=e.startDTS,n.maxStartPTS=e.maxStartPTS,n.endPTS=e.endPTS,n.endDTS=e.endDTS,n.minEndPTS=e.minEndPTS,n.setDuration(e.endPTS-e.startPTS),n.duration&&(a=n),t.PTSKnown=t.alignedSliding=!0),e.hasStreams&&(n.elementaryStreams=e.elementaryStreams),n.loader=e.loader,e.hasStats&&(n.stats=e.stats),e.initSegment&&(n.initSegment=e.initSegment,r=e.initSegment)});let o=t.fragments,s=t.fragmentHint?o.concat(t.fragmentHint):o;if(r&&s.forEach(e=>{e&&(!e.initSegment||e.initSegment.relurl===r?.relurl)&&(e.initSegment=r)}),t.skippedSegments){if(t.deltaUpdateFailed=o.some(e=>!e),t.deltaUpdateFailed){n.warn(`[level-helper] Previous playlist missing segments skipped in delta playlist`);for(let e=t.skippedSegments;e--;)o.shift();t.startSN=o[0].sn}else{t.canSkipDateRanges&&(t.dateRanges=ec(e.dateRanges,t,n));let r=e.fragments.filter(e=>e.rawProgramDateTime);if(e.hasProgramDateTime&&!t.hasProgramDateTime)for(let e=1;e<s.length;e++)s[e].programDateTime===null&&Ks(s[e],s[e-1],r);zs(r,t)}t.endCC=o[o.length-1].cc}t.startCC||=sc(e,t.startSN-1)?.cc??o[0].cc,tc(e.partList,t.partList,(e,t)=>{t.elementaryStreams=e.elementaryStreams,t.stats=e.stats}),a?Qs(t,a,a.startPTS,a.endPTS,a.startDTS,a.endDTS,n):ic(e,t),o.length&&(t.totalduration=t.edge-o[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;let c=t.advancedDateTime;if(t.advanced&&c){let e=t.edge;t.driftStart||=(t.driftStartTime=c,e),t.driftEndTime=c,t.driftEnd=e}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime;t.requestScheduled===-1&&(t.requestScheduled=e.requestScheduled)}function ec(e,t,n){let{dateRanges:r,recentlyRemovedDateranges:i}=t,a=U({},e);i&&i.forEach(e=>{delete a[e]});let o=Object.keys(a).length;return o?(Object.keys(r).forEach(e=>{let t=a[e],i=new as(r[e].attr,t);i.isValid?(a[e]=i,t||(i.tagOrder+=o)):n.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${Y(r[e].attr)}"`)}),a):r}function tc(e,t,n){if(e&&t){let r=0;for(let i=0,a=e.length;i<=a;i++){let a=e[i],o=t[i+r];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?n(a,o):r--}}}function nc(e,t,n){let r=t.skippedSegments,i=Math.max(e.startSN,t.startSN)-t.startSN,a=(e.fragmentHint?1:0)+(r?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,o=t.startSN-e.startSN,s=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,c=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments;for(let l=i;l<=a;l++){let i=c[o+l],a=s[l];if(r&&!a&&i&&(a=t.fragments[l]=i),i&&a){n(i,a,l,s);let r=i.relurl,o=a.relurl;if(r&&dc(r,o)){t.playlistParsingError=rc(`media sequence mismatch ${a.sn}:`,e,t,i,a);return}else if(i.cc!==a.cc){t.playlistParsingError=rc(`discontinuity sequence mismatch (${i.cc}!=${a.cc})`,e,t,i,a);return}}}}function rc(e,t,n,r,i){return Error(`${e} ${i.url}
16
13
  Playlist starting @${t.startSN}
17
- ${t.m3u8}`)}function Tl(r,e,t=!0){const s=e.startSN+e.skippedSegments-r.startSN,i=r.fragments,n=s>=0;let a=0;if(n&&s<i.length)a=i[s].start;else if(n&&e.startSN===r.endSN+1)a=r.fragmentEnd;else if(n&&t)a=r.fragmentStart+s*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)a=r.fragmentStart;else return;ln(e,a)}function ln(r,e){if(e){const t=r.fragments;for(let s=r.skippedSegments;s<t.length;s++)t[s].addStart(e);r.fragmentHint&&r.fragmentHint.addStart(e)}}function Sl(r,e=1/0){let t=1e3*r.targetduration;if(r.updated){const s=r.fragments;if(s.length&&t*4>e){const n=s[s.length-1].duration*1e3;n<t&&(t=n)}}else t/=2;return Math.round(t)}function xl(r,e,t){if(!r)return null;let s=r.fragments[e-r.startSN];return s||(s=r.fragmentHint,s&&s.sn===e)?s:e<r.startSN&&t&&t.sn===e?t:null}function Al(r,e,t){return r?_l(r.partList,e,t):null}function _l(r,e,t){if(r)for(let s=r.length;s--;){const i=r[s];if(i.index===t&&i.fragment.sn===e)return i}return null}function Il(r){r.forEach((e,t)=>{var s;(s=e.details)==null||s.fragments.forEach(i=>{i.level=t,i.initSegment&&(i.initSegment.level=t)})})}function bf(r,e){return r!==e&&e?Ll(r)!==Ll(e):!1}function Ll(r){return r.replace(/\?[^?]*$/,"")}function ni(r,e){for(let s=0,i=r.length;s<i;s++){var t;if(((t=r[s])==null?void 0:t.cc)===e)return r[s]}return null}function Df(r,e){return!!(r&&e.startCC<r.endCC&&e.endCC>r.startCC)}function Rl(r,e){const t=r.start+e;r.startPTS=t,r.setStart(t),r.endPTS=t+r.duration}function bl(r,e){const t=e.fragments;for(let s=0,i=t.length;s<i;s++)Rl(t[s],r);e.fragmentHint&&Rl(e.fragmentHint,r),e.alignedSliding=!0}function Cf(r,e){r&&(Dl(e,r),e.alignedSliding||ji(e,r),!e.alignedSliding&&!e.skippedSegments&&Tl(r,e,!1))}function Dl(r,e){if(!Df(e,r))return;const t=Math.min(e.endCC,r.endCC),s=ni(e.fragments,t),i=ni(r.fragments,t);if(!s||!i)return;oe.log(`Aligning playlist at start of dicontinuity sequence ${t}`);const n=s.start-i.start;bl(n,r)}function ji(r,e){if(!r.hasProgramDateTime||!e.hasProgramDateTime)return;const t=r.fragments,s=e.fragments;if(!t.length||!s.length)return;let i,n;const a=Math.min(e.endCC,r.endCC);e.startCC<a&&r.startCC<a&&(i=ni(s,a),n=ni(t,a)),(!i||!n)&&(i=s[Math.floor(s.length/2)],n=ni(t,i.cc)||t[Math.floor(t.length/2)]);const o=i.programDateTime,c=n.programDateTime;if(!o||!c)return;const l=(c-o)/1e3-(n.start-i.start);bl(l,r)}function Ue(r,e,t){He(r,e,t),r.addEventListener(e,t)}function He(r,e,t){r.removeEventListener(e,t)}const Pf={toString:function(r){let e="";const t=r.length;for(let s=0;s<t;s++)e+=`[${r.start(s).toFixed(3)}-${r.end(s).toFixed(3)}]`;return e}},P={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"};class cn extends Xo{constructor(e,t,s,i,n){super(i,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=P.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:a,fragCurrent:o,media:c,mediaBuffer:l,state:u}=this,h=c?c.currentTime:0,d=j.bufferInfo(l||c,h,a.maxBufferHole),g=!d.len;if(this.log(`Media seeking to ${$(h)?h.toFixed(3):h}, state: ${u}, ${g?"out of":"in"} buffer`),this.state===P.ENDED)this.resetLoadingState();else if(o){const f=a.maxFragLookUpTolerance,p=o.start-f,y=o.start+o.duration+f;if(g||y<d.start||p>d.end){const v=h>y;(h<p||v)&&(v&&o.loader&&(this.log(`Cancelling fragment load for seek (sn: ${o.sn})`),o.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(c){this.fragmentTracker.removeFragmentsInRange(h,1/0,this.playlistType,!0);const f=this.lastCurrentTime;if(h>f&&(this.lastCurrentTime=h),!this.loadingParts){const p=Math.max(d.end,h),y=this.shouldLoadParts(this.getLevelDetails(),p);y&&(this.log(`LL-Part loading ON after seeking to ${h.toFixed(2)} with buffer @${p.toFixed(2)}`),this.loadingParts=y)}}this.hls.hasEnoughToStart||(this.log(`Setting ${g?"startPosition":"nextLoadPosition"} to ${h} for seek without enough to start`),this.nextLoadPosition=h,g&&(this.startPosition=h)),g&&this.state===P.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=n,this.hls=e,this.fragmentLoader=new nf(e.config),this.keyLoader=s,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Qr(e.config)}registerListeners(){const{hls:e}=this;e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(m.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===P.STOPPED)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;e!=null&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=P.STOPPED}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;return t===-1&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;const s=e.end||0,i=this.config.timelineOffset||0;if(s<=i)return!1;const n=e.buffered;this.config.maxBufferHole&&n&&n.length>1&&(e=j.bufferedInfo(n,e.start,0));const a=e.nextStart;if(a&&a>i&&a<t.edge||this.media.currentTime<e.start)return!1;const c=t.partList;if(c!=null&&c.length){const u=c[c.length-1];return j.isBuffered(this.media,u.start+u.duration/2)}const l=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(l)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){const e=this.config.timelineOffset;if(e){var t;return((t=this.getLevelDetails())==null?void 0:t.appliedTimelineOffset)||e}return 0}onMediaAttached(e,t){const s=this.media=this.mediaBuffer=t.media;Ue(s,"seeking",this.onMediaSeeking),Ue(s,"ended",this.onMediaEnded);const i=this.config;this.levels&&i.autoStartLoad&&this.state===P.STOPPED&&this.startLoad(i.startPosition)}onMediaDetaching(e,t){const s=!!t.transferMedia,i=this.media;if(i!==null){if(i.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),He(i,"seeking",this.onMediaSeeking),He(i,"ended",this.onMediaEnded),this.keyLoader&&!s&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,s){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=P.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,s){this.startFragRequested=!0,this._loadFragForPlayback(e,t,s)}_loadFragForPlayback(e,t,s){const i=n=>{const a=n.frag;if(this.fragContextChanged(a)){this.warn(`${a.type} sn: ${a.sn}${n.part?" part: "+n.part.index:""} of ${this.fragInfo(a,!1,n.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(a);return}a.stats.chunkCount++,this._handleFragmentLoadProgress(n)};this._doFragLoad(e,t,s,i).then(n=>{if(!n)return;const a=this.state,o=n.frag;if(this.fragContextChanged(o)){(a===P.FRAG_LOADING||!this.fragCurrent&&a===P.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=P.IDLE);return}"payload"in n&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level}`),this.hls.trigger(m.FRAG_LOADED,n)),this._handleFragmentLoadComplete(n)}).catch(n=>{this.state===P.STOPPED||this.state===P.ERROR||(this.warn(`Frag error: ${n?.message||n}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:s}=this;if(s.getState(e)===Re.APPENDING){const n=e.type,a=this.getFwdBufferInfo(this.mediaBuffer,n),o=Math.max(e.duration,a?a.len:this.config.maxBufferLength),c=this.backtrackFragment;((c?e.sn-c.sn:0)===1||this.reduceMaxBufferLength(o,e.duration))&&s.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?s.removeAllFragments():s.hasParts(e.type)&&(s.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),s.getState(e)===Re.PARTIAL&&s.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const t=e.details;return t?.live&&t.type!=="EVENT"&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,s=null){if(!(e-t))return;const i={startOffset:e,endOffset:t,type:s};this.hls.trigger(m.BUFFER_FLUSHING,i)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(s=>{const i=s?.frag;if(!i||this.fragContextChanged(i)||!this.levels)throw new Error("init load aborted");return s}).then(s=>{const{hls:i}=this,{frag:n,payload:a}=s,o=n.decryptdata;if(a&&a.byteLength>0&&o!=null&&o.key&&o.iv&&Ns(o.method)){const c=self.performance.now();return this.decrypter.decrypt(new Uint8Array(a),o.key.buffer,o.iv.buffer,en(o.method)).catch(l=>{throw i.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:R.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:n}),l}).then(l=>{const u=self.performance.now();return i.trigger(m.FRAG_DECRYPTED,{frag:n,payload:l,stats:{tstart:c,tdecrypt:u}}),s.payload=l,this.completeInitSegmentLoad(s)})}return this.completeInitSegmentLoad(s)}).catch(s=>{this.state===P.STOPPED||this.state===P.ERROR||(this.warn(s),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const s=e.frag.stats;this.state!==P.STOPPED&&(this.state=P.IDLE),e.frag.data=new Uint8Array(e.payload),s.parsing.start=s.buffering.start=self.performance.now(),s.parsing.end=s.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var s,i;const n=e.tracks;if(n&&!t.encrypted&&((s=n.audio)!=null&&s.encrypted||(i=n.video)!=null&&i.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const a=this.media,o=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${a?"attached mediaKeys: "+a.mediaKeys:"detached"})`);return this.warn(o.message),!a||a.mediaKeys?!1:(this.hls.trigger(m.ERROR,{type:H.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_KEYS,fatal:!1,error:o,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){const s=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${s?Pf.toString(j.getBuffered(s)):"(detached)"})`),xe(e)){var i;if(e.type!==G.SUBTITLE){const a=e.elementaryStreams;if(!Object.keys(a).some(o=>!!a[o])){this.state=P.IDLE;return}}const n=(i=this.levels)==null?void 0:i[e.level];n!=null&&n.fragmentError&&(this.log(`Resetting level fragment error count of ${n.fragmentError} on frag buffered`),n.fragmentError=0)}this.state=P.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:s,part:i,partsLoaded:n}=e,a=!n||n.length===0||n.some(c=>!c),o=new Jr(s.level,s.sn,s.stats.chunkCount+1,0,i?i.index:-1,!a);t.flush(o)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,s=null,i){var n;this.fragCurrent=e;const a=t.details;if(!this.levels||!a)throw new Error(`frag load aborted, missing level${a?"":" detail"}s`);let o=null;if(e.encrypted&&!((n=e.decryptdata)!=null&&n.key)){if(this.log(`Loading key for ${e.sn} of [${a.startSN}-${a.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=P.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then(d=>{if(!this.fragContextChanged(d.frag))return this.hls.trigger(m.KEY_LOADED,d),this.state===P.KEY_LOADING&&(this.state=P.IDLE),d}),this.hls.trigger(m.KEY_LOADING,{frag:e}),this.fragCurrent===null)return this.log("context changed in KEY_LOADING"),Promise.resolve(null)}else e.encrypted||(o=this.keyLoader.loadClear(e,a.encryptedFragments,this.startFragRequested),o&&this.log("[eme] blocking frag load until media-keys acquired"));const c=this.fragPrevious;if(xe(e)&&(!c||e.sn!==c.sn)){const d=this.shouldLoadParts(t.details,e.end);d!==this.loadingParts&&(this.log(`LL-Part loading ${d?"ON":"OFF"} loading sn ${c?.sn}->${e.sn}`),this.loadingParts=d)}if(s=Math.max(e.start,s||0),this.loadingParts&&xe(e)){const d=a.partList;if(d&&i){s>a.fragmentEnd&&a.fragmentHint&&(e=a.fragmentHint);const g=this.getNextPart(d,e,s);if(g>-1){const f=d[g];e=this.fragCurrent=f.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${f.index} (${g}/${d.length-1}) of ${this.fragInfo(e,!1,f)}) cc: ${e.cc} [${a.startSN}-${a.endSN}], target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=f.start+f.duration,this.state=P.FRAG_LOADING;let p;return o?p=o.then(y=>!y||this.fragContextChanged(y.frag)?null:this.doFragPartsLoad(e,f,t,i)).catch(y=>this.handleFragLoadError(y)):p=this.doFragPartsLoad(e,f,t,i).catch(y=>this.handleFragLoadError(y)),this.hls.trigger(m.FRAG_LOADING,{frag:e,part:f,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):p}else if(!e.url||this.loadedEndOfParts(d,s))return Promise.resolve(null)}}if(xe(e)&&this.loadingParts){var l;this.log(`LL-Part loading OFF after next part miss @${s.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${(l=a.partList)==null?void 0:l.filter(d=>d.loaded).map(d=>`[${d.start}-${d.end}]`)}`),this.loadingParts=!1}else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${"["+a.startSN+"-"+a.endSN+"]"}, target: ${parseFloat(s.toFixed(3))}`),$(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=P.FRAG_LOADING;const u=this.config.progressive&&e.type!==G.SUBTITLE;let h;return u&&o?h=o.then(d=>!d||this.fragContextChanged(d.frag)?null:this.fragmentLoader.load(e,i)).catch(d=>this.handleFragLoadError(d)):h=Promise.all([this.fragmentLoader.load(e,u?i:void 0),o]).then(([d])=>(!u&&i&&i(d),d)).catch(d=>this.handleFragLoadError(d)),this.hls.trigger(m.FRAG_LOADING,{frag:e,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):h}doFragPartsLoad(e,t,s,i){return new Promise((n,a)=>{var o;const c=[],l=(o=s.details)==null?void 0:o.partList,u=h=>{this.fragmentLoader.loadPart(e,h,i).then(d=>{c[h.index]=d;const g=d.part;this.hls.trigger(m.FRAG_LOADED,d);const f=Al(s.details,e.sn,h.index+1)||_l(l,e.sn,h.index+1);if(f)u(f);else return n({frag:e,part:g,partsLoaded:c})}).catch(a)};u(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===R.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===H.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(m.ERROR,t)}else this.hls.trigger(m.ERROR,{type:H.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==P.PARSING){!this.fragCurrent&&this.state!==P.STOPPED&&this.state!==P.ERROR&&(this.state=P.IDLE);return}const{frag:s,part:i,level:n}=t,a=self.performance.now();s.stats.parsing.end=a,i&&(i.stats.parsing.end=a);const o=this.getLevelDetails(),l=o&&s.sn>o.endSN||this.shouldLoadParts(o,s.end);l!==this.loadingParts&&(this.log(`LL-Part loading ${l?"ON":"OFF"} after parsing segment ending @${s.end.toFixed(2)}`),this.loadingParts=l),this.updateLevelTiming(s,i,n,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var s;const n=e.partList[0];if(n.fragment.type===G.SUBTITLE)return!1;const a=n.end+(((s=e.fragmentHint)==null?void 0:s.duration)||0);if(t>=a){var i;if((this.hls.hasEnoughToStart?((i=this.media)==null?void 0:i.currentTime)||this.lastCurrentTime:this.getLoadPosition())>n.start-n.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:s}=this,{level:i,sn:n,part:a}=e;if(!(t!=null&&t[i]))return this.warn(`Levels object was unset while buffering fragment ${n} of ${this.playlistLabel()} ${i}. The current chunk will not be buffered.`),null;const o=t[i],c=o.details,l=a>-1?Al(c,n,a):null,u=l?l.fragment:xl(c,n,s);return u?(s&&s!==u&&(u.stats=s.stats),{frag:u,part:l,level:o}):null}bufferFragmentData(e,t,s,i,n){if(this.state!==P.PARSING)return;const{data1:a,data2:o}=e;let c=a;if(o&&(c=nt(a,o)),!c.length)return;const l=this.initPTS[t.cc],u=l?-l.baseTime/l.timescale:void 0,h={type:e.type,frag:t,part:s,chunkMeta:i,offset:u,parent:t.type,data:c};if(this.hls.trigger(m.BUFFER_APPENDING,h),e.dropped&&e.independent&&!s){if(n)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!j.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const s=t.currentTime,i=j.bufferInfo(t,s,0),n=e.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,n*.25),o=Math.max(Math.min(e.start-a,i.end-a),s+a);e.start-o>a&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){var s;const i=this.getLoadPosition();if(!$(i))return null;const a=this.lastCurrentTime>i||(s=this.media)!=null&&s.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,i,t,a)}getFwdBufferInfoAtPos(e,t,s,i){const n=j.bufferInfo(e,t,i);if(n.len===0&&n.nextStart!==void 0){const a=this.fragmentTracker.getBufferedFrag(t,s);if(a&&(n.nextStart<=a.end||a.gap)){const o=Math.max(Math.min(n.nextStart,a.end)-t,i);return j.bufferInfo(e,t,o)}}return n}getMaxBufferLength(e){const{config:t}=this;let s;return e?s=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):s=t.maxBufferLength,Math.min(s,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){const s=this.config,i=Math.max(Math.min(e-t,s.maxBufferLength),t),n=Math.max(e-t*3,s.maxMaxBufferLength/2,i);return n>=i?(s.maxMaxBufferLength=n,this.warn(`Reduce max buffer length to ${n}s`),!0):!1}getAppendedFrag(e,t=G.MAIN){const s=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return s&&"fragment"in s?s.fragment:s}getNextFragment(e,t){const s=t.fragments,i=s.length;if(!i)return null;const{config:n}=this,a=s[0].start,o=n.lowLatencyMode&&!!t.partList;let c=null;if(t.live){const h=n.initialLiveManifestSize;if(i<h)return this.warn(`Not enough fragments to start playback (have: ${i}, need: ${h})`),null;if(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<a){var l;o&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),c=this.getInitialLiveFragment(t);const d=this.hls.startPosition,g=this.hls.liveSyncPosition,f=c?(d!==-1&&d>=a?d:g)||c.start:e;this.log(`Setting startPosition to ${f} to match start frag at live edge. mainStart: ${d} liveSyncPosition: ${g} frag.start: ${(l=c)==null?void 0:l.start}`),this.startPosition=this.nextLoadPosition=f}}else e<=a&&(c=s[0]);if(!c){const h=this.loadingParts?t.partEnd:t.fragmentEnd;c=this.getFragmentAtPosition(e,h,t)}let u=this.filterReplacedPrimary(c,t);if(!u&&c){const h=c.sn-t.startSN;u=this.filterReplacedPrimary(s[h+1]||null,t)}return this.mapToInitFragWhenRequired(u)}isLoopLoading(e,t){const s=this.fragmentTracker.getState(e);return(s===Re.OK||s===Re.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,s,i,n){let a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t),a&&!a.gap&&s.nextStart)){const o=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,i,0);if(o!==null&&s.len+o.len>=n){const c=a.sn;return this.loopSn!==c&&(this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${c}`),this.loopSn=c),null}}return this.loopSn=void 0,a}get primaryPrefetch(){if(Cl(this.config)){var e;if((e=this.hls.interstitialsManager)==null||(e=e.playingItem)==null?void 0:e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(Cl(this.config)&&e.type!==G.SUBTITLE){const s=this.hls.interstitialsManager,i=s?.bufferingItem;if(i){const a=i.event;if(a){if(a.appendInPlace||Math.abs(e.start-i.start)>1||i.start===0)return null}else if(e.end<=i.start&&t?.live===!1||e.start>i.end&&i.nextEvent&&(i.nextEvent.appendInPlace||e.start-i.end>1))return null}const n=s?.playerQueue;if(n)for(let a=n.length;a--;){const o=n[a].interstitial;if(o.appendInPlace&&e.start>=o.startTime&&e.end<=o.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!e.initSegment.data&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,s){let i=-1,n=!1,a=!0;for(let o=0,c=e.length;o<c;o++){const l=e[o];if(a=a&&!l.independent,i>-1&&s<l.start)break;const u=l.loaded;u?i=-1:(n||(l.independent||a)&&l.fragment===t)&&(l.fragment!==t&&this.warn(`Need buffer at ${s} but next unloaded part starts at ${l.start}`),i=o),n=u}return i}loadedEndOfParts(e,t){let s;for(let i=e.length;i--;){if(s=e[i],!s.loaded)return!1;if(t>s.start)return!0}return!1}getInitialLiveFragment(e){const t=e.fragments,s=this.fragPrevious;let i=null;if(s){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`),i=Yd(t,s.endProgramDateTime,this.config.maxFragLookUpTolerance)),!i){const n=s.sn+1;if(n>=e.startSN&&n<=e.endSN){const a=t[n-e.startSN];s.cc===a.cc&&(i=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${i.sn}`))}i||(i=Uo(e,s.cc,s.end),i&&this.log(`Live playlist, switching playlist, load frag with same CC: ${i.sn}`))}}else{const n=this.hls.liveSyncPosition;n!==null&&(i=this.getFragmentAtPosition(n,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i}getFragmentAtPosition(e,t,s){const{config:i}=this;let{fragPrevious:n}=this,{fragments:a,endSN:o}=s;const{fragmentHint:c}=s,{maxFragLookUpTolerance:l}=i,u=s.partList,h=!!(this.loadingParts&&u!=null&&u.length&&c);h&&!this.bitrateTest&&u[u.length-1].fragment.sn===c.sn&&(a=a.concat(c),o=c.sn);let d;if(e<t){var g;const p=e<this.lastCurrentTime||e>t-l||(g=this.media)!=null&&g.paused||!this.startFragRequested?0:l;d=gs(n,a,e,p)}else d=a[a.length-1];if(d){const f=d.sn-s.startSN,p=this.fragmentTracker.getState(d);if((p===Re.OK||p===Re.PARTIAL&&d.gap)&&(n=d),n&&d.sn===n.sn&&(!h||u[0].fragment.sn>d.sn||!s.live)&&d.level===n.level){const v=a[f+1];d.sn<o&&this.fragmentTracker.getState(v)!==Re.OK?d=v:d=null}}return d}alignPlaylists(e,t,s){const i=e.fragments.length;if(!i)return this.warn("No fragments in live playlist"),0;const n=e.fragmentStart,a=!t,o=e.alignedSliding&&$(n);if(a||!o&&!n){Cf(s,e);const c=e.fragmentStart;return this.log(`Live playlist sliding: ${c.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${i}`),c}return n}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let s=this.startPosition;s<t&&(s=-1);const i=this.timelineOffset;if(s===-1){const n=this.startTimeOffset!==null,a=n?this.startTimeOffset:e.startTimeOffset;a!==null&&$(a)?(s=t+a,a<0&&(s+=e.edge),s=Math.min(Math.max(t,s),t+e.totalduration),this.log(`Setting startPosition to ${s} for start time offset ${a} found in ${n?"multivariant":"media"} playlist`),this.startPosition=s):e.live?(s=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${s}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=s=0),this.lastCurrentTime=s+i}this.nextLoadPosition=s+i}getLoadPosition(){var e;const{media:t}=this;let s=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t?s=t.currentTime:this.nextLoadPosition>=0&&(s=this.nextLoadPosition),s}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&xe(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==P.FRAG_LOADING_WAITING_RETRY)&&(this.state=P.IDLE)}onFragmentOrKeyLoadError(e,t){var s;if(t.chunkMeta&&!t.frag){const v=this.getCurrentContext(t.chunkMeta);v&&(t.frag=v.frag)}const i=t.frag;if(!i||i.type!==e||!this.levels)return;if(this.fragContextChanged(i)){var n;this.warn(`Frag load error must match current frag to retry ${i.url} > ${(n=this.fragCurrent)==null?void 0:n.url}`);return}const a=t.details===R.FRAG_GAP;a&&this.fragmentTracker.fragBuffered(i,!0);const o=t.errorAction;if(!o){this.state=P.ERROR;return}const{action:c,flags:l,retryCount:u=0,retryConfig:h}=o,d=!!h,g=d&&c===ke.RetryRequest,f=d&&!o.resolved&&l===Xe.MoveAllAlternatesMatchingHost,p=(s=this.hls.latestLevelDetails)==null?void 0:s.live;if(!g&&f&&xe(i)&&!i.endList&&p&&!Ko(t))this.resetFragmentErrors(e),this.treatAsGap(i),o.resolved=!0;else if((g||f)&&u<h.maxNumRetry){var y;const v=zr((y=t.response)==null?void 0:y.code),E=Xr(h,u);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+E,this.state=P.FRAG_LOADING_WAITING_RETRY,o.resolved=!0,v){this.log("Waiting for connection (offline)"),this.retryDate=1/0,t.reason="offline";return}this.warn(`Fragment ${i.sn} of ${e} ${i.level} errored with ${t.details}, retrying loading ${u+1}/${h.maxNumRetry} in ${E}ms`)}else if(h)if(this.resetFragmentErrors(e),u<h.maxNumRetry)!a&&c!==ke.RemoveAlternatePermanently&&(o.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${u})`);return}else c===ke.SendAlternateToPenaltyBox?this.state=P.WAITING_LEVEL:this.state=P.ERROR;this.tickImmediate()}checkRetryDate(){const e=self.performance.now(),t=this.retryDate,s=t===1/0;(!t||e>=t||s&&!zr(0))&&(s&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=P.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===P.PARSING||this.state===P.PARSED){const t=e.frag,s=e.parent,i=this.getFwdBufferInfo(this.mediaBuffer,s),n=i&&i.len>.5;n&&this.reduceMaxBufferLength(i.len,t?.duration||10);const a=!n;return a&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${s} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1}resetFragmentErrors(e){e===G.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==P.STOPPED&&(this.state=P.IDLE)}afterBufferFlushed(e,t,s){if(!e)return;const i=j.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,i,s),this.state===P.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==P.STOPPED&&(this.state=P.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const e=this.levelLastLoaded,t=e?e.details:null;t!=null&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${e.level===-1?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,s,i){const n=s.details;if(!n){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((c,l)=>{const u=e.elementaryStreams[l];if(u){const h=u.endPTS-u.startPTS;if(h<=0)return this.warn(`Could not parse fragment ${e.sn} ${l} duration reliably (${h})`),c||!1;const d=i?0:vl(n,e,u.startPTS,u.endPTS,u.startDTS,u.endDTS,this);return this.hls.trigger(m.LEVEL_PTS_UPDATED,{details:n,level:s,drift:d,type:l,frag:e,start:u.startPTS,end:u.endPTS}),!0}return c},!1)){var o;const c=((o=this.transmuxer)==null?void 0:o.error)===null;if((s.fragmentError===0||c&&(s.fragmentError<2||e.endList))&&this.treatAsGap(e,s),c){const l=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(l.message),this.hls.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,error:l,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=P.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(m.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===G.MAIN?"level":"track"}fragInfo(e,t=!0,s){var i,n;return`${this.playlistLabel()} ${e.level} (${s?"part":"frag"}:[${((i=t&&!s?e.startPTS:(s||e).start)!=null?i:NaN).toFixed(3)}-${((n=t&&!s?e.endPTS:(s||e).end)!=null?n:NaN).toFixed(3)}]${s&&e.type==="main"?"INDEPENDENT="+(s.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}function Cl(r){return!!r.interstitialsController&&r.enableInterstitialPlayback!==!1}class Pl{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let s;if(e.length)e.length===1?s=e[0]:s=wf(e,t);else return new Uint8Array(0);return this.reset(),s}reset(){this.chunks.length=0,this.dataLength=0}}function wf(r,e){const t=new Uint8Array(e);let s=0;for(let i=0;i<r.length;i++){const n=r[i];t.set(n,s),s+=n.length}return t}var un={exports:{}},wl;function kf(){return wl||(wl=1,(function(r){var e=Object.prototype.hasOwnProperty,t="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(t=!1));function i(c,l,u){this.fn=c,this.context=l,this.once=u||!1}function n(c,l,u,h,d){if(typeof u!="function")throw new TypeError("The listener must be a function");var g=new i(u,h||c,d),f=t?t+l:l;return c._events[f]?c._events[f].fn?c._events[f]=[c._events[f],g]:c._events[f].push(g):(c._events[f]=g,c._eventsCount++),c}function a(c,l){--c._eventsCount===0?c._events=new s:delete c._events[l]}function o(){this._events=new s,this._eventsCount=0}o.prototype.eventNames=function(){var l=[],u,h;if(this._eventsCount===0)return l;for(h in u=this._events)e.call(u,h)&&l.push(t?h.slice(1):h);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(u)):l},o.prototype.listeners=function(l){var u=t?t+l:l,h=this._events[u];if(!h)return[];if(h.fn)return[h.fn];for(var d=0,g=h.length,f=new Array(g);d<g;d++)f[d]=h[d].fn;return f},o.prototype.listenerCount=function(l){var u=t?t+l:l,h=this._events[u];return h?h.fn?1:h.length:0},o.prototype.emit=function(l,u,h,d,g,f){var p=t?t+l:l;if(!this._events[p])return!1;var y=this._events[p],v=arguments.length,E,T;if(y.fn){switch(y.once&&this.removeListener(l,y.fn,void 0,!0),v){case 1:return y.fn.call(y.context),!0;case 2:return y.fn.call(y.context,u),!0;case 3:return y.fn.call(y.context,u,h),!0;case 4:return y.fn.call(y.context,u,h,d),!0;case 5:return y.fn.call(y.context,u,h,d,g),!0;case 6:return y.fn.call(y.context,u,h,d,g,f),!0}for(T=1,E=new Array(v-1);T<v;T++)E[T-1]=arguments[T];y.fn.apply(y.context,E)}else{var S=y.length,_;for(T=0;T<S;T++)switch(y[T].once&&this.removeListener(l,y[T].fn,void 0,!0),v){case 1:y[T].fn.call(y[T].context);break;case 2:y[T].fn.call(y[T].context,u);break;case 3:y[T].fn.call(y[T].context,u,h);break;case 4:y[T].fn.call(y[T].context,u,h,d);break;default:if(!E)for(_=1,E=new Array(v-1);_<v;_++)E[_-1]=arguments[_];y[T].fn.apply(y[T].context,E)}}return!0},o.prototype.on=function(l,u,h){return n(this,l,u,h,!1)},o.prototype.once=function(l,u,h){return n(this,l,u,h,!0)},o.prototype.removeListener=function(l,u,h,d){var g=t?t+l:l;if(!this._events[g])return this;if(!u)return a(this,g),this;var f=this._events[g];if(f.fn)f.fn===u&&(!d||f.once)&&(!h||f.context===h)&&a(this,g);else{for(var p=0,y=[],v=f.length;p<v;p++)(f[p].fn!==u||d&&!f[p].once||h&&f[p].context!==h)&&y.push(f[p]);y.length?this._events[g]=y.length===1?y[0]:y:a(this,g)}return this},o.prototype.removeAllListeners=function(l){var u;return l?(u=t?t+l:l,this._events[u]&&a(this,u)):(this._events=new s,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,r.exports=o})(un)),un.exports}var Of=kf(),hn=rd(Of);const ai="1.6.15",Bs={};function Mf(){return typeof __HLS_WORKER_BUNDLE__=="function"}function Ff(){const r=Bs[ai];if(r)return r.clientCount++,r;const e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),t=self.URL.createObjectURL(e),i={worker:new self.Worker(t),objectURL:t,clientCount:1};return Bs[ai]=i,i}function Nf(r){const e=Bs[r];if(e)return e.clientCount++,e;const t=new self.URL(r,self.location.href).href,i={worker:new self.Worker(t),scriptURL:t,clientCount:1};return Bs[r]=i,i}function $f(r){const e=Bs[r||ai];if(e&&e.clientCount--===1){const{worker:s,objectURL:i}=e;delete Bs[r||ai],i&&self.URL.revokeObjectURL(i),s.terminate()}}function kl(r,e){return e+10<=r.length&&r[e]===51&&r[e+1]===68&&r[e+2]===73&&r[e+3]<255&&r[e+4]<255&&r[e+6]<128&&r[e+7]<128&&r[e+8]<128&&r[e+9]<128}function dn(r,e){return e+10<=r.length&&r[e]===73&&r[e+1]===68&&r[e+2]===51&&r[e+3]<255&&r[e+4]<255&&r[e+6]<128&&r[e+7]<128&&r[e+8]<128&&r[e+9]<128}function Xi(r,e){let t=0;return t=(r[e]&127)<<21,t|=(r[e+1]&127)<<14,t|=(r[e+2]&127)<<7,t|=r[e+3]&127,t}function oi(r,e){const t=e;let s=0;for(;dn(r,e);){s+=10;const i=Xi(r,e+6);s+=i,kl(r,e+10)&&(s+=10),e+=s}if(s>0)return r.subarray(t,t+s)}function Bf(r,e,t,s){const i=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],n=e[t+2],a=n>>2&15;if(a>12){const g=new Error(`invalid ADTS sampling index:${a}`);r.emit(m.ERROR,m.ERROR,{type:H.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!0,error:g,reason:g.message});return}const o=(n>>6&3)+1,c=e[t+3]>>6&3|(n&1)<<2,l="mp4a.40."+o,u=i[a];let h=a;(o===5||o===29)&&(h-=3);const d=[o<<3|(h&14)>>1,(h&1)<<7|c<<3];return oe.log(`manifest codec:${s}, parsed codec:${l}, channels:${c}, rate:${u} (ADTS object type:${o} sampling index:${a})`),{config:d,samplerate:u,channelCount:c,codec:l,parsedCodec:l,manifestCodec:s}}function Ol(r,e){return r[e]===255&&(r[e+1]&246)===240}function Ml(r,e){return r[e+1]&1?7:9}function fn(r,e){return(r[e+3]&3)<<11|r[e+4]<<3|(r[e+5]&224)>>>5}function Uf(r,e){return e+5<r.length}function zi(r,e){return e+1<r.length&&Ol(r,e)}function Gf(r,e){return Uf(r,e)&&Ol(r,e)&&fn(r,e)<=r.length-e}function Kf(r,e){if(zi(r,e)){const t=Ml(r,e);if(e+t>=r.length)return!1;const s=fn(r,e);if(s<=t)return!1;const i=e+s;return i===r.length||zi(r,i)}return!1}function Fl(r,e,t,s,i){if(!r.samplerate){const n=Bf(e,t,s,i);if(!n)return;le(r,n)}}function Nl(r){return 1024*9e4/r}function Vf(r,e){const t=Ml(r,e);if(e+t<=r.length){const s=fn(r,e)-t;if(s>0)return{headerLength:t,frameLength:s}}}function $l(r,e,t,s,i){const n=Nl(r.samplerate),a=s+i*n,o=Vf(e,t);let c;if(o){const{frameLength:h,headerLength:d}=o,g=d+h,f=Math.max(0,t+g-e.length);f?(c=new Uint8Array(g-d),c.set(e.subarray(t+d,e.length),0)):c=e.subarray(t+d,t+g);const p={unit:c,pts:a};return f||r.samples.push(p),{sample:p,length:g,missing:f}}const l=e.length-t;return c=new Uint8Array(l),c.set(e.subarray(t,e.length),0),{sample:{unit:c,pts:a},length:l,missing:-1}}function Hf(r,e){return dn(r,e)&&Xi(r,e+6)+10<=r.length-e}function Wf(r){return r instanceof ArrayBuffer?r:r.byteOffset==0&&r.byteLength==r.buffer.byteLength?r.buffer:new Uint8Array(r).buffer}function gn(r,e=0,t=1/0){return Yf(r,e,t,Uint8Array)}function Yf(r,e,t,s){const i=qf(r);let n=1;"BYTES_PER_ELEMENT"in s&&(n=s.BYTES_PER_ELEMENT);const a=jf(r)?r.byteOffset:0,o=(a+r.byteLength)/n,c=(a+e)/n,l=Math.floor(Math.max(0,Math.min(c,o))),u=Math.floor(Math.min(l+Math.max(t,0),o));return new s(i,l,u-l)}function qf(r){return r instanceof ArrayBuffer?r:r.buffer}function jf(r){return r&&r.buffer instanceof ArrayBuffer&&r.byteLength!==void 0&&r.byteOffset!==void 0}function Xf(r){const e={key:r.type,description:"",data:"",mimeType:null,pictureType:null},t=3;if(r.size<2)return;if(r.data[0]!==t){console.log("Ignore frame with unrecognized character encoding");return}const s=r.data.subarray(1).indexOf(0);if(s===-1)return;const i=je(gn(r.data,1,s)),n=r.data[2+s],a=r.data.subarray(3+s).indexOf(0);if(a===-1)return;const o=je(gn(r.data,3+s,a));let c;return i==="-->"?c=je(gn(r.data,4+s+a)):c=Wf(r.data.subarray(4+s+a)),e.mimeType=i,e.pictureType=n,e.description=o,e.data=c,e}function zf(r){if(r.size<2)return;const e=je(r.data,!0),t=new Uint8Array(r.data.subarray(e.length+1));return{key:r.type,info:e,data:t.buffer}}function Qf(r){if(r.size<2)return;if(r.type==="TXXX"){let t=1;const s=je(r.data.subarray(t),!0);t+=s.length+1;const i=je(r.data.subarray(t));return{key:r.type,info:s,data:i}}const e=je(r.data.subarray(1));return{key:r.type,info:"",data:e}}function Jf(r){if(r.type==="WXXX"){if(r.size<2)return;let t=1;const s=je(r.data.subarray(t),!0);t+=s.length+1;const i=je(r.data.subarray(t));return{key:r.type,info:s,data:i}}const e=je(r.data);return{key:r.type,info:"",data:e}}function Zf(r){return r.type==="PRIV"?zf(r):r.type[0]==="W"?Jf(r):r.type==="APIC"?Xf(r):Qf(r)}function eg(r){const e=String.fromCharCode(r[0],r[1],r[2],r[3]),t=Xi(r,4),s=10;return{type:e,size:t,data:r.subarray(s,s+t)}}const Qi=10,tg=10;function Bl(r){let e=0;const t=[];for(;dn(r,e);){const s=Xi(r,e+6);r[e+5]>>6&1&&(e+=Qi),e+=Qi;const i=e+s;for(;e+tg<i;){const n=eg(r.subarray(e)),a=Zf(n);a&&t.push(a),e+=n.size+Qi}kl(r,e)&&(e+=Qi)}return t}function Ul(r){return r&&r.key==="PRIV"&&r.info==="com.apple.streaming.transportStreamTimestamp"}function sg(r){if(r.data.byteLength===8){const e=new Uint8Array(r.data),t=e[3]&1;let s=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return s/=45,t&&(s+=4772185884e-2),Math.round(s)}}function mn(r){const e=Bl(r);for(let t=0;t<e.length;t++){const s=e[t];if(Ul(s))return sg(s)}}let ze=(function(r){return r.audioId3="org.id3",r.dateRange="com.apple.quicktime.HLS",r.emsg="https://aomedia.org/emsg/ID3",r.misbklv="urn:misb:KLV:bin:1910.1",r})({});function It(r="",e=9e4){return{type:r,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class pn{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,s,i){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,s){}demux(e,t){this.cachedData&&(e=nt(this.cachedData,e),this.cachedData=null);let s=oi(e,0),i=s?s.length:0,n;const a=this._audioTrack,o=this._id3Track,c=s?mn(s):void 0,l=e.length;for((this.basePTS===null||this.frameIndex===0&&$(c))&&(this.basePTS=ig(c,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),s&&s.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:ze.audioId3,duration:Number.POSITIVE_INFINITY});i<l;){if(this.canParse(e,i)){const u=this.appendFrame(a,e,i);u?(this.frameIndex++,this.lastPTS=u.sample.pts,i+=u.length,n=i):i=l}else Hf(e,i)?(s=oi(e,i),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:ze.audioId3,duration:Number.POSITIVE_INFINITY}),i+=s.length,n=i):i++;if(i===l&&n!==l){const u=e.slice(n);this.cachedData?this.cachedData=nt(this.cachedData,u):this.cachedData=u}}return{audioTrack:a,videoTrack:It(),id3Track:o,textTrack:It()}}demuxSampleAes(e,t,s){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:It(),id3Track:this._id3Track,textTrack:It()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const ig=(r,e,t)=>{if($(r))return r*90;const s=t?t.baseTime*9e4/t.timescale:0;return e*9e4+s};let Ji=null;const rg=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],ng=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],ag=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],og=[0,1,1,4];function Gl(r,e,t,s,i){if(t+24>e.length)return;const n=Kl(e,t);if(n&&t+n.frameLength<=e.length){const a=n.samplesPerFrame*9e4/n.sampleRate,o=s+i*a,c={unit:e.subarray(t,t+n.frameLength),pts:o,dts:o};return r.config=[],r.channelCount=n.channelCount,r.samplerate=n.sampleRate,r.samples.push(c),{sample:c,length:n.frameLength,missing:0}}}function Kl(r,e){const t=r[e+1]>>3&3,s=r[e+1]>>1&3,i=r[e+2]>>4&15,n=r[e+2]>>2&3;if(t!==1&&i!==0&&i!==15&&n!==3){const a=r[e+2]>>1&1,o=r[e+3]>>6,c=t===3?3-s:s===3?3:4,l=rg[c*14+i-1]*1e3,h=ng[(t===3?0:t===2?1:2)*3+n],d=o===3?1:2,g=ag[t][s],f=og[s],p=g*8*f,y=Math.floor(g*l/h+a)*f;if(Ji===null){const T=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Ji=T?parseInt(T[1]):0}return Ji&&Ji<=87&&s===2&&l>=224e3&&o===0&&(r[e+3]=r[e+3]|128),{sampleRate:h,channelCount:d,frameLength:y,samplesPerFrame:p}}}function yn(r,e){return r[e]===255&&(r[e+1]&224)===224&&(r[e+1]&6)!==0}function Vl(r,e){return e+1<r.length&&yn(r,e)}function lg(r,e){return yn(r,e)&&4<=r.length-e}function Hl(r,e){if(e+1<r.length&&yn(r,e)){const s=Kl(r,e);let i=4;s!=null&&s.frameLength&&(i=s.frameLength);const n=e+i;return n===r.length||Vl(r,n)}return!1}class cg extends pn{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;const s=oi(e,0);let i=s?.length||0;if(Hl(e,i))return!1;for(let n=e.length;i<n;i++)if(Kf(e,i))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return Gf(e,t)}appendFrame(e,t,s){Fl(e,this.observer,t,s,e.manifestCodec);const i=$l(e,t,s,this.basePTS,this.frameIndex);if(i&&i.missing===0)return i}}const Wl=(r,e)=>{let t=0,s=5;e+=s;const i=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;s>0;){a[0]=r[e];const o=Math.min(s,8),c=8-o;n[0]=4278190080>>>24+c<<c,i[0]=(a[0]&n[0])>>c,t=t?t<<o|i[0]:i[0],e+=1,s-=o}return t};class ug extends pn{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,s){const i=Yl(e,t,s,this.basePTS,this.frameIndex);if(i!==-1)return{sample:e.samples[e.samples.length-1],length:i,missing:0}}static probe(e){if(!e)return!1;const t=oi(e,0);if(!t)return!1;const s=t.length;return e[s]===11&&e[s+1]===119&&mn(t)!==void 0&&Wl(e,s)<16}}function Yl(r,e,t,s,i){if(t+8>e.length||e[t]!==11||e[t+1]!==119)return-1;const n=e[t+4]>>6;if(n>=3)return-1;const o=[48e3,44100,32e3][n],c=e[t+4]&63,u=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][c*3+n]*2;if(t+u>e.length)return-1;const h=e[t+6]>>5;let d=0;h===2?d+=2:(h&1&&h!==1&&(d+=2),h&4&&(d+=2));const g=(e[t+6]<<8|e[t+7])>>12-d&1,p=[2,1,2,3,3,4,4,5][h]+g,y=e[t+5]>>3,v=e[t+5]&7,E=new Uint8Array([n<<6|y<<1|v>>2,(v&3)<<6|h<<3|g<<2|c>>4,c<<4&224]),T=1536/o*9e4,S=s+i*T,_=e.subarray(t,t+u);return r.config=E,r.channelCount=p,r.samplerate=o,r.samples.push({unit:_,pts:S}),u}class hg extends pn{resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=oi(e,0);let s=t?.length||0;if(t&&e[s]===11&&e[s+1]===119&&mn(t)!==void 0&&Wl(e,s)<=16)return!1;for(let i=e.length;s<i;s++)if(Hl(e,s))return oe.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return lg(e,t)}appendFrame(e,t,s){if(this.basePTS!==null)return Gl(e,t,s,this.basePTS,this.frameIndex)}}const dg=/\/emsg[-/]ID3/i;class fg{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,s,i){const n=this.videoTrack=It("video",1),a=this.audioTrack=It("audio",1),o=this.txtTrack=It("text",1);if(this.id3Track=It("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const c=Eo(e);if(c.video){const{id:l,timescale:u,codec:h,supplemental:d}=c.video;n.id=l,n.timescale=o.timescale=u,n.codec=h,n.supplemental=d}if(c.audio){const{id:l,timescale:u,codec:h}=c.audio;a.id=l,a.timescale=u,a.codec=h}o.id=mo.text,n.sampleDuration=0,n.duration=a.duration=i}resetContiguity(){this.remainderData=null}static probe(e){return cd(e)}demux(e,t){this.timeOffset=t;let s=e;const i=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=nt(this.remainderData,e));const o=pd(s);this.remainderData=o.remainder,i.samples=o.valid||new Uint8Array}else i.samples=s;const a=this.extractID3Track(i,t);return n.samples=xo(t,i),{videoTrack:i,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,s=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const i=this.extractID3Track(t,this.timeOffset);return s.samples=xo(e,t),{videoTrack:t,audioTrack:It(),id3Track:i,textTrack:It()}}extractID3Track(e,t){const s=this.id3Track;if(e.samples.length){const i=J(e.samples,["emsg"]);i&&i.forEach(n=>{const a=vd(n);if(dg.test(a.schemeIdUri)){const o=ql(a,t);let c=a.eventDuration===4294967295?Number.POSITIVE_INFINITY:a.eventDuration/a.timeScale;c<=.001&&(c=Number.POSITIVE_INFINITY);const l=a.payload;s.samples.push({data:l,len:l.byteLength,dts:o,pts:o,type:ze.emsg,duration:c})}else if(this.config.enableEmsgKLVMetadata&&a.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const o=ql(a,t);s.samples.push({data:a.payload,len:a.payload.byteLength,dts:o,pts:o,type:ze.misbklv,duration:Number.POSITIVE_INFINITY})}})}return s}demuxSampleAes(e,t,s){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}}function ql(r,e){return $(r.presentationTime)?r.presentationTime/r.timeScale:e+r.presentationTimeDelta/r.timeScale}class gg{constructor(e,t,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new Qr(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,es.cbc)}decryptAacSample(e,t,s){const i=e[t].unit;if(i.length<=16)return;const n=i.subarray(16,i.length-i.length%16),a=n.buffer.slice(n.byteOffset,n.byteOffset+n.length);this.decryptBuffer(a).then(o=>{const c=new Uint8Array(o);i.set(c,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,s)}).catch(s)}decryptAacSamples(e,t,s){for(;;t++){if(t>=e.length){s();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,s),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=Math.floor((e.length-48)/160)*16+16,s=new Int8Array(t);let i=0;for(let n=32;n<e.length-16;n+=160,i+=16)s.set(e.subarray(n,n+16),i);return s}getAvcDecryptedUnit(e,t){const s=new Uint8Array(t);let i=0;for(let n=32;n<e.length-16;n+=160,i+=16)e.set(s.subarray(i,i+16),n);return e}decryptAvcSample(e,t,s,i,n){const a=Ao(n.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then(c=>{n.data=this.getAvcDecryptedUnit(a,c),this.decrypter.isSync()||this.decryptAvcSamples(e,t,s+1,i)}).catch(i)}decryptAvcSamples(e,t,s,i){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,s=0){if(t>=e.length){i();return}const n=e[t].units;for(;!(s>=n.length);s++){const a=n[s];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(e,t,s,i,a),!this.decrypter.isSync()))return}}}}class jl{constructor(){this.VideoSample=null}createVideoSample(e,t,s){return{key:e,frame:!1,pts:t,dts:s,units:[],length:0}}getLastNalUnit(e){var t;let s=this.VideoSample,i;if((!s||s.units.length===0)&&(s=e[e.length-1]),(t=s)!=null&&t.units){const n=s.units;i=n[n.length-1]}return i}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const s=t.samples,i=s.length;if(i){const n=s[i-1];e.pts=n.pts,e.dts=n.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,s){const i=t.byteLength;let n=e.naluState||0;const a=n,o=[];let c=0,l,u,h,d=-1,g=0;for(n===-1&&(d=0,g=this.getNALuType(t,0),n=0,c=1);c<i;){if(l=t[c++],!n){n=l?0:1;continue}if(n===1){n=l?0:2;continue}if(!l)n=3;else if(l===1){if(u=c-n-1,d>=0){const f={data:t.subarray(d,u),type:g};o.push(f)}else{const f=this.getLastNalUnit(e.samples);f&&(a&&c<=4-a&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-a)),u>0&&(f.data=nt(f.data,t.subarray(0,u)),f.state=0))}c<i?(h=this.getNALuType(t,c),d=c,g=h,n=0):n=-1}else n=0}if(d>=0&&n>=0){const f={data:t.subarray(d,i),type:g,state:n};o.push(f)}if(o.length===0){const f=this.getLastNalUnit(e.samples);f&&(f.data=nt(f.data,t))}return e.naluState=n,o}}class li{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,t=this.bytesAvailable,s=e.byteLength-t,i=new Uint8Array(4),n=Math.min(4,t);if(n===0)throw new Error("no bytes available");i.set(e.subarray(s,s+n)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=n*8,this.bytesAvailable-=n}skipBits(e){let t;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const s=this.word>>>32-t;if(e>32&&oe.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return t=e-t,t>0&&this.bitsAvailable?s<<t|this.readBits(t):s}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if((this.word&2147483648>>>e)!==0)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class mg extends jl{parsePES(e,t,s,i){const n=this.parseNALu(e,s.data,i);let a=this.VideoSample,o,c=!1;s.data=null,a&&n.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),n.forEach(l=>{var u,h;switch(l.type){case 1:{let p=!1;o=!0;const y=l.data;if(c&&y.length>4){const v=this.readSliceType(y);(v===2||v===4||v===7||v===9)&&(p=!0)}if(p){var d;(d=a)!=null&&d.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.frame=!0,a.key=p;break}case 5:o=!0,(u=a)!=null&&u.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 6:{o=!0,Vr(l.data,1,s.pts,t.samples);break}case 7:{var g,f;o=!0,c=!0;const p=l.data,y=this.readSPS(p);if(!e.sps||e.width!==y.width||e.height!==y.height||((g=e.pixelRatio)==null?void 0:g[0])!==y.pixelRatio[0]||((f=e.pixelRatio)==null?void 0:f[1])!==y.pixelRatio[1]){e.width=y.width,e.height=y.height,e.pixelRatio=y.pixelRatio,e.sps=[p];const v=p.subarray(1,4);let E="avc1.";for(let T=0;T<3;T++){let S=v[T].toString(16);S.length<2&&(S="0"+S),E+=S}e.codec=E}break}case 8:o=!0,e.pps=[l.data];break;case 9:o=!0,e.audFound=!0,(h=a)!=null&&h.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;case 12:o=!0;break;default:o=!1;break}a&&o&&a.units.push(l)}),i&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){const t=new li(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let s=8,i=8,n;for(let a=0;a<e;a++)i!==0&&(n=t.readEG(),i=(s+n+256)%256),s=i===0?s:i}readSPS(e){const t=new li(e);let s=0,i=0,n=0,a=0,o,c,l;const u=t.readUByte.bind(t),h=t.readBits.bind(t),d=t.readUEG.bind(t),g=t.readBoolean.bind(t),f=t.skipBits.bind(t),p=t.skipEG.bind(t),y=t.skipUEG.bind(t),v=this.skipScalingList.bind(this);u();const E=u();if(h(5),f(3),u(),y(),E===100||E===110||E===122||E===244||E===44||E===83||E===86||E===118||E===128){const b=d();if(b===3&&f(1),y(),y(),f(1),g())for(c=b!==3?8:12,l=0;l<c;l++)g()&&(l<6?v(16,t):v(64,t))}y();const T=d();if(T===0)d();else if(T===1)for(f(1),p(),p(),o=d(),l=0;l<o;l++)p();y(),f(1);const S=d(),_=d(),D=h(1);D===0&&f(1),f(1),g()&&(s=d(),i=d(),n=d(),a=d());let I=[1,1];if(g()&&g())switch(u()){case 1:I=[1,1];break;case 2:I=[12,11];break;case 3:I=[10,11];break;case 4:I=[16,11];break;case 5:I=[40,33];break;case 6:I=[24,11];break;case 7:I=[20,11];break;case 8:I=[32,11];break;case 9:I=[80,33];break;case 10:I=[18,11];break;case 11:I=[15,11];break;case 12:I=[64,33];break;case 13:I=[160,99];break;case 14:I=[4,3];break;case 15:I=[3,2];break;case 16:I=[2,1];break;case 255:{I=[u()<<8|u(),u()<<8|u()];break}}return{width:Math.ceil((S+1)*16-s*2-i*2),height:(2-D)*(_+1)*16-(D?2:4)*(n+a),pixelRatio:I}}}class pg extends jl{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,s,i){const n=this.parseNALu(e,s.data,i);let a=this.VideoSample,o,c=!1;s.data=null,a&&n.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),n.forEach(l=>{var u,h;switch(l.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||(a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),a.frame=!0,o=!0;break;case 16:case 17:case 18:case 21:if(o=!0,c){var d;(d=a)!=null&&d.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 19:case 20:o=!0,(u=a)!=null&&u.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 39:o=!0,Vr(l.data,2,s.pts,t.samples);break;case 32:o=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=le(e.params,this.readVPS(l.data)),this.initVPS=l.data),e.vps=[l.data];break;case 33:if(o=!0,c=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],l.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const g=this.readSPS(l.data);e.width=g.width,e.height=g.height,e.pixelRatio=g.pixelRatio,e.codec=g.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(const f in g.params)e.params[f]=g.params[f]}this.pushParameterSet(e.sps,l.data,e.vps),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0;break;case 34:if(o=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];const g=this.readPPS(l.data);for(const f in g)e.params[f]=g[f]}this.pushParameterSet(e.pps,l.data,e.vps)}break;case 35:o=!0,e.audFound=!0,(h=a)!=null&&h.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;default:o=!1;break}a&&o&&a.units.push(l)}),i&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}pushParameterSet(e,t,s){(s&&s[0]===this.initVPS||!s&&!e.length)&&e.push(t)}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let s=0;for(let i=0;i<e.byteLength;i++)i>=2&&e[i]===3&&e[i-1]===0&&e[i-2]===0||(t[s]=e[i],s++);return new Uint8Array(t.buffer,0,s)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new li(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);const s=t.readBits(3),i=t.readBoolean();return{numTemporalLayers:s+1,temporalIdNested:i}}readSPS(e){const t=new li(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const s=t.readBits(3);t.readBoolean();const i=t.readBits(2),n=t.readBoolean(),a=t.readBits(5),o=t.readUByte(),c=t.readUByte(),l=t.readUByte(),u=t.readUByte(),h=t.readUByte(),d=t.readUByte(),g=t.readUByte(),f=t.readUByte(),p=t.readUByte(),y=t.readUByte(),v=t.readUByte(),E=[],T=[];for(let ie=0;ie<s;ie++)E.push(t.readBoolean()),T.push(t.readBoolean());if(s>0)for(let ie=s;ie<8;ie++)t.readBits(2);for(let ie=0;ie<s;ie++)E[ie]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),T[ie]&&t.readUByte();t.readUEG();const S=t.readUEG();S==3&&t.skipBits(1);const _=t.readUEG(),D=t.readUEG(),I=t.readBoolean();let b=0,A=0,x=0,C=0;I&&(b+=t.readUEG(),A+=t.readUEG(),x+=t.readUEG(),C+=t.readUEG());const M=t.readUEG(),K=t.readUEG(),V=t.readUEG(),N=t.readBoolean();for(let ie=N?0:s;ie<=s;ie++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(let Be=0;Be<4;Be++)for(let ot=0;ot<(Be===3?2:6);ot++)if(!t.readBoolean())t.readUEG();else{const gt=Math.min(64,1<<4+(Be<<1));Be>1&&t.readEG();for(let Ys=0;Ys<gt;Ys++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const F=t.readUEG();let B=0;for(let ie=0;ie<F;ie++){let Be=!1;if(ie!==0&&(Be=t.readBoolean()),Be){ie===F&&t.readUEG(),t.readBoolean(),t.readUEG();let ot=0;for(let ys=0;ys<=B;ys++){const gt=t.readBoolean();let Ys=!1;gt||(Ys=t.readBoolean()),(gt||Ys)&&ot++}B=ot}else{const ot=t.readUEG(),ys=t.readUEG();B=ot+ys;for(let gt=0;gt<ot;gt++)t.readUEG(),t.readBoolean();for(let gt=0;gt<ys;gt++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const ie=t.readUEG();for(let Be=0;Be<ie;Be++){for(let ot=0;ot<V+4;ot++)t.readBits(1);t.readBits(1)}}let k=0,O=1,q=1,Z=!0,X=1,z=0;t.readBoolean(),t.readBoolean();let Se=!1;if(t.readBoolean()){if(t.readBoolean()){const vs=t.readUByte(),Eu=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],pr=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];vs>0&&vs<16?(O=Eu[vs-1],q=pr[vs-1]):vs===255&&(O=t.readBits(16),q=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),Se=t.readBoolean(),Se&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(X=t.readBits(32),z=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const pr=t.readBoolean(),Tu=t.readBoolean();let mi=!1;(pr||Tu)&&(mi=t.readBoolean(),mi&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),mi&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let Su=0;Su<=s;Su++){Z=t.readBoolean();const n0=Z||t.readBoolean();let xu=!1;n0?t.readEG():xu=t.readBoolean();const Au=xu?1:t.readUEG()+1;if(pr)for(let pi=0;pi<Au;pi++)t.readUEG(),t.readUEG(),mi&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(Tu)for(let pi=0;pi<Au;pi++)t.readUEG(),t.readUEG(),mi&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),k=t.readUEG())}let Ne=_,Me=D;if(I){let ie=1,Be=1;S===1?ie=Be=2:S==2&&(ie=2),Ne=_-ie*A-ie*b,Me=D-Be*C-Be*x}const $e=i?["A","B","C"][i]:"",mr=o<<24|c<<16|l<<8|u;let gi=0;for(let ie=0;ie<32;ie++)gi=(gi|(mr>>ie&1)<<31-ie)>>>0;let Ut=gi.toString(16);return a===1&&Ut==="2"&&(Ut="6"),{codecString:`hvc1.${$e}${a}.${Ut}.${n?"H":"L"}${v}.B0`,params:{general_tier_flag:n,general_profile_idc:a,general_profile_space:i,general_profile_compatibility_flags:[o,c,l,u],general_constraint_indicator_flags:[h,d,g,f,p,y],general_level_idc:v,bit_depth:M+8,bit_depth_luma_minus8:M,bit_depth_chroma_minus8:K,min_spatial_segmentation_idc:k,chroma_format_idc:S,frame_rate:{fixed:Z,fps:z/X}},width:Ne,height:Me,pixelRatio:[O,q]}}readPPS(e){const t=new li(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);const i=t.readBoolean(),n=t.readBoolean();let a=1;return n&&i?a=0:n?a=3:i&&(a=2),{parallelismType:a}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}const Ce=188;class ss{constructor(e,t,s,i){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.logger=i,this.videoParser=null}static probe(e,t){const s=ss.syncOffset(e);return s>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${s}`),s!==-1}static syncOffset(e){const t=e.length;let s=Math.min(Ce*5,t-Ce)+1,i=0;for(;i<s;){let n=!1,a=-1,o=0;for(let c=i;c<t;c+=Ce)if(e[c]===71&&(t-c===Ce||e[c+Ce]===71)){if(o++,a===-1&&(a=c,a!==0&&(s=Math.min(a+Ce*99,e.length-Ce)+1)),n||(n=vn(e,c)===0),n&&o>1&&(a===0&&o>2||c+Ce>s))return a}else{if(o)return-1;break}i++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:mo[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,s,i){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=ss.createTrack("video"),this._videoTrack.duration=i,this._audioTrack=ss.createTrack("audio",i),this._id3Track=ss.createTrack("id3"),this._txtTrack=ss.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=s}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:s}=this;e&&(e.pesData=null),t&&(t.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,s=!1,i=!1){s||(this.sampleAes=null);let n;const a=this._videoTrack,o=this._audioTrack,c=this._id3Track,l=this._txtTrack;let u=a.pid,h=a.pesData,d=o.pid,g=c.pid,f=o.pesData,p=c.pesData,y=null,v=this.pmtParsed,E=this._pmtId,T=e.length;if(this.remainderData&&(e=nt(this.remainderData,e),T=e.length,this.remainderData=null),T<Ce&&!i)return this.remainderData=e,{audioTrack:o,videoTrack:a,id3Track:c,textTrack:l};const S=Math.max(0,ss.syncOffset(e));T-=(T-S)%Ce,T<e.byteLength&&!i&&(this.remainderData=new Uint8Array(e.buffer,T,e.buffer.byteLength-T));let _=0;for(let I=S;I<T;I+=Ce)if(e[I]===71){const b=!!(e[I+1]&64),A=vn(e,I),x=(e[I+3]&48)>>4;let C;if(x>1){if(C=I+5+e[I+4],C===I+Ce)continue}else C=I+4;switch(A){case u:b&&(h&&(n=Us(h,this.logger))&&(this.readyVideoParser(a.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(a,l,n,!1)),h={data:[],size:0}),h&&(h.data.push(e.subarray(C,I+Ce)),h.size+=I+Ce-C);break;case d:if(b){if(f&&(n=Us(f,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,n);break;case"mp3":this.parseMPEGPES(o,n);break;case"ac3":this.parseAC3PES(o,n);break}f={data:[],size:0}}f&&(f.data.push(e.subarray(C,I+Ce)),f.size+=I+Ce-C);break;case g:b&&(p&&(n=Us(p,this.logger))&&this.parseID3PES(c,n),p={data:[],size:0}),p&&(p.data.push(e.subarray(C,I+Ce)),p.size+=I+Ce-C);break;case 0:b&&(C+=e[C]+1),E=this._pmtId=yg(e,C);break;case E:{b&&(C+=e[C]+1);const M=vg(e,C,this.typeSupported,s,this.observer,this.logger);u=M.videoPid,u>0&&(a.pid=u,a.segmentCodec=M.segmentVideoCodec),d=M.audioPid,d>0&&(o.pid=d,o.segmentCodec=M.segmentAudioCodec),g=M.id3Pid,g>0&&(c.pid=g),y!==null&&!v&&(this.logger.warn(`MPEG-TS PMT found at ${I} after unknown PID '${y}'. Backtracking to sync byte @${S} to parse all TS packets.`),y=null,I=S-188),v=this.pmtParsed=!0;break}case 17:case 8191:break;default:y=A;break}}else _++;_>0&&En(this.observer,new Error(`Found ${_} TS packet/s that do not start with 0x47`),void 0,this.logger),a.pesData=h,o.pesData=f,c.pesData=p;const D={audioTrack:o,videoTrack:a,id3Track:c,textTrack:l};return i&&this.extractRemainingSamples(D),D}flush(){const{remainderData:e}=this;this.remainderData=null;let t;return e?t=this.demux(e,-1,!1,!0):t={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:s,id3Track:i,textTrack:n}=e,a=s.pesData,o=t.pesData,c=i.pesData;let l;if(a&&(l=Us(a,this.logger))?(this.readyVideoParser(s.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(s,n,l,!0),s.pesData=null)):s.pesData=a,o&&(l=Us(o,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,l);break;case"mp3":this.parseMPEGPES(t,l);break;case"ac3":this.parseAC3PES(t,l);break}t.pesData=null}else o!=null&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=o;c&&(l=Us(c,this.logger))?(this.parseID3PES(i,l),i.pesData=null):i.pesData=c}demuxSampleAes(e,t,s){const i=this.demux(e,s,!0,!this.config.progressive),n=this.sampleAes=new gg(this.observer,this.config,t);return this.decrypt(i,n)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new mg:e==="hevc"&&(this.videoParser=new pg))}decrypt(e,t){return new Promise(s=>{const{audioTrack:i,videoTrack:n}=e;i.samples&&i.segmentCodec==="aac"?t.decryptAacSamples(i.samples,0,()=>{n.samples?t.decryptAvcSamples(n.samples,0,0,()=>{s(e)}):s(e)}):n.samples&&t.decryptAvcSamples(n.samples,0,0,()=>{s(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(e,t){let s=0;const i=this.aacOverFlow;let n=t.data;if(i){this.aacOverFlow=null;const h=i.missing,d=i.sample.unit.byteLength;if(h===-1)n=nt(i.sample.unit,n);else{const g=d-h;i.sample.unit.set(n.subarray(0,h),g),e.samples.push(i.sample),s=i.missing}}let a,o;for(a=s,o=n.length;a<o-1&&!zi(n,a);a++);if(a!==s){let h;const d=a<o-1;if(d?h=`AAC PES did not start with ADTS header,offset:${a}`:h="No ADTS header found in AAC PES",En(this.observer,new Error(h),d,this.logger),!d)return}Fl(e,this.observer,n,a,this.audioCodec);let c;if(t.pts!==void 0)c=t.pts;else if(i){const h=Nl(e.samplerate);c=i.sample.pts+h}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let l=0,u;for(;a<o;)if(u=$l(e,n,a,c,l),a+=u.length,u.missing){this.aacOverFlow=u;break}else for(l++;a<o-1&&!zi(n,a);a++);}parseMPEGPES(e,t){const s=t.data,i=s.length;let n=0,a=0;const o=t.pts;if(o===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;a<i;)if(Vl(s,a)){const c=Gl(e,s,a,o,n);if(c)a+=c.length,n++;else break}else a++}parseAC3PES(e,t){{const s=t.data,i=t.pts;if(i===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const n=s.length;let a=0,o=0,c;for(;o<n&&(c=Yl(e,s,o,i,a++))>0;)o+=c}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const s=le({},t,{type:this._videoTrack?ze.emsg:ze.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(s)}}function vn(r,e){return((r[e+1]&31)<<8)+r[e+2]}function yg(r,e){return(r[e+10]&31)<<8|r[e+11]}function vg(r,e,t,s,i,n){const a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=(r[e+1]&15)<<8|r[e+2],c=e+3+o-4,l=(r[e+10]&15)<<8|r[e+11];for(e+=12+l;e<c;){const u=vn(r,e),h=(r[e+3]&15)<<8|r[e+4];switch(r[e]){case 207:if(!s){Tn("ADTS AAC",n);break}case 15:a.audioPid===-1&&(a.audioPid=u);break;case 21:a.id3Pid===-1&&(a.id3Pid=u);break;case 219:if(!s){Tn("H.264",n);break}case 27:a.videoPid===-1&&(a.videoPid=u);break;case 3:case 4:!t.mpeg&&!t.mp3?n.log("MPEG audio found, not supported in this browser"):a.audioPid===-1&&(a.audioPid=u,a.segmentAudioCodec="mp3");break;case 193:if(!s){Tn("AC-3",n);break}case 129:t.ac3?a.audioPid===-1&&(a.audioPid=u,a.segmentAudioCodec="ac3"):n.log("AC-3 audio found, not supported in this browser");break;case 6:if(a.audioPid===-1&&h>0){let d=e+5,g=h;for(;g>2;){r[d]===106&&(t.ac3!==!0?n.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=u,a.segmentAudioCodec="ac3"));const p=r[d+1]+2;d+=p,g-=p}}break;case 194:case 135:return En(i,new Error("Unsupported EC-3 in M2TS found"),void 0,n),a;case 36:a.videoPid===-1&&(a.videoPid=u,a.segmentVideoCodec="hevc",n.log("HEVC in M2TS found"));break}e+=h+5}return a}function En(r,e,t,s){s.warn(`parsing error: ${e.message}`),r.emit(m.ERROR,m.ERROR,{type:H.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function Tn(r,e){e.log(`${r} with AES-128-CBC encryption found in unencrypted stream`)}function Us(r,e){let t=0,s,i,n,a,o;const c=r.data;if(!r||r.size===0)return null;for(;c[0].length<19&&c.length>1;)c[0]=nt(c[0],c[1]),c.splice(1,1);if(s=c[0],(s[0]<<16)+(s[1]<<8)+s[2]===1){if(i=(s[4]<<8)+s[5],i&&i>r.size-6)return null;const u=s[7];u&192&&(a=(s[9]&14)*536870912+(s[10]&255)*4194304+(s[11]&254)*16384+(s[12]&255)*128+(s[13]&254)/2,u&64?(o=(s[14]&14)*536870912+(s[15]&255)*4194304+(s[16]&254)*16384+(s[17]&255)*128+(s[18]&254)/2,a-o>60*9e4&&(e.warn(`${Math.round((a-o)/9e4)}s delta between PTS and DTS, align them`),a=o)):o=a),n=s[8];let h=n+9;if(r.size<=h)return null;r.size-=h;const d=new Uint8Array(r.size);for(let g=0,f=c.length;g<f;g++){s=c[g];let p=s.byteLength;if(h)if(h>p){h-=p;continue}else s=s.subarray(h),p-=h,h=0;d.set(s,t),t+=p}return i&&(i-=n+3),{data:d,pts:a,dts:o,len:i}}return null}class Eg{static getSilentFrame(e,t){switch(e){case"mp4a.40.2":if(t===1)return new Uint8Array([0,200,0,128,35,128]);if(t===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(t===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(t===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(t===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(t===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(t===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===2)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);break}}}const is=Math.pow(2,32)-1;class L{static init(){L.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let e;for(e in L.types)L.types.hasOwnProperty(e)&&(L.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),s=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);L.HDLR_TYPES={video:t,audio:s};const i=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),n=new Uint8Array([0,0,0,0,0,0,0,0]);L.STTS=L.STSC=L.STCO=n,L.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),L.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),L.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),L.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const a=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),c=new Uint8Array([0,0,0,1]);L.FTYP=L.box(L.types.ftyp,a,c,a,o),L.DINF=L.box(L.types.dinf,L.box(L.types.dref,i))}static box(e,...t){let s=8,i=t.length;const n=i;for(;i--;)s+=t[i].byteLength;const a=new Uint8Array(s);for(a[0]=s>>24&255,a[1]=s>>16&255,a[2]=s>>8&255,a[3]=s&255,a.set(e,4),i=0,s=8;i<n;i++)a.set(t[i],s),s+=t[i].byteLength;return a}static hdlr(e){return L.box(L.types.hdlr,L.HDLR_TYPES[e])}static mdat(e){return L.box(L.types.mdat,e)}static mdhd(e,t){t*=e;const s=Math.floor(t/(is+1)),i=Math.floor(t%(is+1));return L.box(L.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,s>>24,s>>16&255,s>>8&255,s&255,i>>24,i>>16&255,i>>8&255,i&255,85,196,0,0]))}static mdia(e){return L.box(L.types.mdia,L.mdhd(e.timescale||0,e.duration||0),L.hdlr(e.type),L.minf(e))}static mfhd(e){return L.box(L.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?L.box(L.types.minf,L.box(L.types.smhd,L.SMHD),L.DINF,L.stbl(e)):L.box(L.types.minf,L.box(L.types.vmhd,L.VMHD),L.DINF,L.stbl(e))}static moof(e,t,s){return L.box(L.types.moof,L.mfhd(e),L.traf(s,t))}static moov(e){let t=e.length;const s=[];for(;t--;)s[t]=L.trak(e[t]);return L.box.apply(null,[L.types.moov,L.mvhd(e[0].timescale||0,e[0].duration||0)].concat(s).concat(L.mvex(e)))}static mvex(e){let t=e.length;const s=[];for(;t--;)s[t]=L.trex(e[t]);return L.box.apply(null,[L.types.mvex,...s])}static mvhd(e,t){t*=e;const s=Math.floor(t/(is+1)),i=Math.floor(t%(is+1)),n=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,s>>24,s>>16&255,s>>8&255,s&255,i>>24,i>>16&255,i>>8&255,i&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return L.box(L.types.mvhd,n)}static sdtp(e){const t=e.samples||[],s=new Uint8Array(4+t.length);let i,n;for(i=0;i<t.length;i++)n=t[i].flags,s[i+4]=n.dependsOn<<4|n.isDependedOn<<2|n.hasRedundancy;return L.box(L.types.sdtp,s)}static stbl(e){return L.box(L.types.stbl,L.stsd(e),L.box(L.types.stts,L.STTS),L.box(L.types.stsc,L.STSC),L.box(L.types.stsz,L.STSZ),L.box(L.types.stco,L.STCO))}static avc1(e){let t=[],s=[],i,n,a;for(i=0;i<e.sps.length;i++)n=e.sps[i],a=n.byteLength,t.push(a>>>8&255),t.push(a&255),t=t.concat(Array.prototype.slice.call(n));for(i=0;i<e.pps.length;i++)n=e.pps[i],a=n.byteLength,s.push(a>>>8&255),s.push(a&255),s=s.concat(Array.prototype.slice.call(n));const o=L.box(L.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(s))),c=e.width,l=e.height,u=e.pixelRatio[0],h=e.pixelRatio[1];return L.box(L.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,c>>8&255,c&255,l>>8&255,l&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,L.box(L.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),L.box(L.types.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,u&255,h>>24,h>>16&255,h>>8&255,h&255])))}static esds(e){const t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...t,6,1,2])}static audioStsd(e){const t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,t&255,0,0])}static mp4a(e){return L.box(L.types.mp4a,L.audioStsd(e),L.box(L.types.esds,L.esds(e)))}static mp3(e){return L.box(L.types[".mp3"],L.audioStsd(e))}static ac3(e){return L.box(L.types["ac-3"],L.audioStsd(e),L.box(L.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return L.box(L.types.stsd,L.STSD,L.mp4a(e));if(t==="ac3"&&e.config)return L.box(L.types.stsd,L.STSD,L.ac3(e));if(t==="mp3"&&e.codec==="mp3")return L.box(L.types.stsd,L.STSD,L.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return L.box(L.types.stsd,L.STSD,L.avc1(e));if(t==="hevc"&&e.vps)return L.box(L.types.stsd,L.STSD,L.hvc1(e))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){const t=e.id,s=(e.duration||0)*(e.timescale||0),i=e.width||0,n=e.height||0,a=Math.floor(s/(is+1)),o=Math.floor(s%(is+1));return L.box(L.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,0,0,0,0,a>>24,a>>16&255,a>>8&255,a&255,o>>24,o>>16&255,o>>8&255,o&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,i>>8&255,i&255,0,0,n>>8&255,n&255,0,0]))}static traf(e,t){const s=L.sdtp(e),i=e.id,n=Math.floor(t/(is+1)),a=Math.floor(t%(is+1));return L.box(L.types.traf,L.box(L.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,i&255])),L.box(L.types.tfdt,new Uint8Array([1,0,0,0,n>>24,n>>16&255,n>>8&255,n&255,a>>24,a>>16&255,a>>8&255,a&255])),L.trun(e,s.length+16+20+8+16+8+8),s)}static trak(e){return e.duration=e.duration||4294967295,L.box(L.types.trak,L.tkhd(e),L.mdia(e))}static trex(e){const t=e.id;return L.box(L.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const s=e.samples||[],i=s.length,n=12+16*i,a=new Uint8Array(n);let o,c,l,u,h,d;for(t+=8+n,a.set([e.type==="video"?1:0,0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,i&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),o=0;o<i;o++)c=s[o],l=c.duration,u=c.size,h=c.flags,d=c.cts,a.set([l>>>24&255,l>>>16&255,l>>>8&255,l&255,u>>>24&255,u>>>16&255,u>>>8&255,u&255,h.isLeading<<2|h.dependsOn,h.isDependedOn<<6|h.hasRedundancy<<4|h.paddingValue<<1|h.isNonSync,h.degradPrio&61440,h.degradPrio&15,d>>>24&255,d>>>16&255,d>>>8&255,d&255],12+16*o);return L.box(L.types.trun,a)}static initSegment(e){L.types||L.init();const t=L.moov(e);return nt(L.FTYP,t)}static hvc1(e){const t=e.params,s=[e.vps,e.sps,e.pps],i=4,n=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),i-1|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),s.length]);let a=n.length;for(let f=0;f<s.length;f+=1){a+=3;for(let p=0;p<s[f].length;p+=1)a+=2+s[f][p].length}const o=new Uint8Array(a);o.set(n,0),a=n.length;const c=s.length-1;for(let f=0;f<s.length;f+=1){o.set(new Uint8Array([32+f|(f===c?128:0),0,s[f].length]),a),a+=3;for(let p=0;p<s[f].length;p+=1)o.set(new Uint8Array([s[f][p].length>>8,s[f][p].length&255]),a),a+=2,o.set(s[f][p],a),a+=s[f][p].length}const l=L.box(L.types.hvcC,o),u=e.width,h=e.height,d=e.pixelRatio[0],g=e.pixelRatio[1];return L.box(L.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,u>>8&255,u&255,h>>8&255,h&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),l,L.box(L.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),L.box(L.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,d&255,g>>24,g>>16&255,g>>8&255,g&255])))}}L.types=void 0,L.HDLR_TYPES=void 0,L.STTS=void 0,L.STSC=void 0,L.STCO=void 0,L.STSZ=void 0,L.VMHD=void 0,L.SMHD=void 0,L.STSD=void 0,L.FTYP=void 0,L.DINF=void 0;const Xl=9e4;function Sn(r,e,t=1,s=!1){const i=r*e*t;return s?Math.round(i):i}function Tg(r,e,t=1,s=!1){return Sn(r,e,1/t,s)}function ci(r,e=!1){return Sn(r,1e3,1/Xl,e)}function Sg(r,e=1){return Sn(r,Xl,1/e)}function zl(r){const{baseTime:e,timescale:t,trackId:s}=r;return`${e/t} (${e}/${t}) trackId: ${s}`}const xg=10*1e3,Ag=1024,_g=1152,Ig=1536;let Gs=null,xn=null;function Ql(r,e,t,s){return{duration:e,size:t,cts:s,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:r?2:1,isNonSync:r?0:1}}}class Zi extends rt{constructor(e,t,s,i){if(super("mp4-remuxer",i),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.ISGenerated=!1,Gs===null){const a=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Gs=a?parseInt(a[1]):0}if(xn===null){const n=navigator.userAgent.match(/Safari\/(\d+)/i);xn=n?parseInt(n[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){const t=this._initPTS;(!t||!e||e.trackId!==t.trackId||e.baseTime!==t.baseTime||e.timescale!==t.timescale)&&this.log(`Reset initPTS: ${t&&zl(t)} > ${e&&zl(e)}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const s=e[0].pts,i=e.reduce((n,a)=>{let o=a.pts,c=o-n;return c<-4294967296&&(t=!0,o=Qe(o,s),c=o-n),c>0?n:o},s);return t&&this.debug("PTS rollover detected"),i}remux(e,t,s,i,n,a,o,c){let l,u,h,d,g,f,p=n,y=n;const v=e.pid>-1,E=t.pid>-1,T=t.samples.length,S=e.samples.length>0,_=o&&T>0||T>1;if((!v||S)&&(!E||_)||this.ISGenerated||o){if(this.ISGenerated){var I,b,A,x;const V=this.videoTrackConfig;(V&&(t.width!==V.width||t.height!==V.height||((I=t.pixelRatio)==null?void 0:I[0])!==((b=V.pixelRatio)==null?void 0:b[0])||((A=t.pixelRatio)==null?void 0:A[1])!==((x=V.pixelRatio)==null?void 0:x[1]))||!V&&_||this.nextAudioTs===null&&S)&&this.resetInitSegment()}this.ISGenerated||(h=this.generateIS(e,t,n,a));const C=this.isVideoContiguous;let M=-1,K;if(_&&(M=Lg(t.samples),!C&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,M>0){this.warn(`Dropped ${M} out of ${T} video samples due to a missing keyframe`);const V=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(M),t.dropped+=M,y+=(t.samples[0].pts-V)/t.inputTimeScale,K=y}else M===-1&&(this.warn(`No keyframe found out of ${T} video samples`),f=!1);if(this.ISGenerated){if(S&&_){const V=this.getVideoStartPts(t.samples),w=(Qe(e.samples[0].pts,V)-V)/t.inputTimeScale;p+=Math.max(0,w),y+=Math.max(0,-w)}if(S){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),h=this.generateIS(e,t,n,a)),u=this.remuxAudio(e,p,this.isAudioContiguous,a,E||_||c===G.AUDIO?y:void 0),_){const V=u?u.endPTS-u.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),h=this.generateIS(e,t,n,a)),l=this.remuxVideo(t,y,C,V)}}else _&&(l=this.remuxVideo(t,y,C,0));l&&(l.firstKeyFrame=M,l.independent=M!==-1,l.firstKeyFramePTS=K)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(g=Jl(s,n,this._initPTS,this._initDTS)),i.samples.length&&(d=Zl(i,n,this._initPTS))),{audio:u,video:l,initSegment:h,independent:f,text:d,id3:g}}computeInitPts(e,t,s,i){const n=Math.round(s*t);let a=Qe(e,n);if(a<n+t)for(this.log(`Adjusting PTS for rollover in timeline near ${(n-a)/t} ${i}`);a<n+t;)a+=8589934592;return a-n}generateIS(e,t,s,i){const n=e.samples,a=t.samples,o=this.typeSupported,c={},l=this._initPTS;let u=!l||i,h="audio/mp4",d,g,f,p=-1;if(u&&(d=g=1/0),e.config&&n.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":o.mpeg?(h="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}c.audio={id:"audio",container:h,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):L.initSegment([e]),metadata:{channelCount:e.channelCount}},u&&(p=e.id,f=e.inputTimeScale,!l||f!==l.timescale?d=g=this.computeInitPts(n[0].pts,f,s,"audio"):u=!1)}if(t.sps&&t.pps&&a.length){if(t.timescale=t.inputTimeScale,c.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:L.initSegment([t]),metadata:{width:t.width,height:t.height}},u)if(p=t.id,f=t.inputTimeScale,!l||f!==l.timescale){const y=this.getVideoStartPts(a),v=Qe(a[0].dts,y),E=this.computeInitPts(v,f,s,"video"),T=this.computeInitPts(y,f,s,"video");g=Math.min(g,E),d=Math.min(d,T)}else u=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(c).length)return this.ISGenerated=!0,u?(l&&this.warn(`Timestamps at playlist time: ${i?"":"~"}${s} ${d/f} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${d/f} (${d}/${f}) trackId: ${p}`),this._initPTS={baseTime:d,timescale:f,trackId:p},this._initDTS={baseTime:g,timescale:f,trackId:p}):d=f=void 0,{tracks:c,initPTS:d,timescale:f,trackId:p}}remuxVideo(e,t,s,i){const n=e.inputTimeScale,a=e.samples,o=[],c=a.length,l=this._initPTS,u=l.baseTime*n/l.timescale;let h=this.nextVideoTs,d=8,g=this.videoSampleDuration,f,p,y=Number.POSITIVE_INFINITY,v=Number.NEGATIVE_INFINITY,E=!1;if(!s||h===null){const k=u+t*n,O=a[0].pts-Qe(a[0].dts,a[0].pts);Gs&&h!==null&&Math.abs(k-O-(h+u))<15e3?s=!0:h=k-O-u}const T=h+u;for(let k=0;k<c;k++){const O=a[k];O.pts=Qe(O.pts,T),O.dts=Qe(O.dts,T),O.dts<a[k>0?k-1:k].dts&&(E=!0)}E&&a.sort(function(k,O){const q=k.dts-O.dts,Z=k.pts-O.pts;return q||Z}),f=a[0].dts,p=a[a.length-1].dts;const S=p-f,_=S?Math.round(S/(c-1)):g||e.inputTimeScale/30;if(s){const k=f-T,O=k>_,q=k<-1;if((O||q)&&(O?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${ci(k,!0)} ms (${k}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${ci(-k,!0)} ms (${k}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!q||T>=a[0].pts||Gs)){f=T;const Z=a[0].pts-k;if(O)a[0].dts=f,a[0].pts=Z;else{let X=!0;for(let z=0;z<a.length&&!(a[z].dts>Z&&X);z++){const Se=a[z].pts;if(a[z].dts-=k,a[z].pts-=k,z<a.length-1){const ve=a[z+1].pts,Ne=a[z].pts,Me=ve<=Ne,$e=ve<=Se;X=Me==$e}}}this.log(`Video: Initial PTS/DTS adjusted: ${ci(Z,!0)}/${ci(f,!0)}, delta: ${ci(k,!0)} ms`)}}f=Math.max(0,f);let D=0,I=0,b=f;for(let k=0;k<c;k++){const O=a[k],q=O.units,Z=q.length;let X=0;for(let z=0;z<Z;z++)X+=q[z].data.length;I+=X,D+=Z,O.length=X,O.dts<b?(O.dts=b,b+=_/4|0||1):b=O.dts,y=Math.min(O.pts,y),v=Math.max(O.pts,v)}p=a[c-1].dts;const A=I+4*D+8;let x;try{x=new Uint8Array(A)}catch(k){this.observer.emit(m.ERROR,m.ERROR,{type:H.MUX_ERROR,details:R.REMUX_ALLOC_ERROR,fatal:!1,error:k,bytes:A,reason:`fail allocating video mdat ${A}`});return}const C=new DataView(x.buffer);C.setUint32(0,A),x.set(L.types.mdat,4);let M=!1,K=Number.POSITIVE_INFINITY,V=Number.POSITIVE_INFINITY,N=Number.NEGATIVE_INFINITY,w=Number.NEGATIVE_INFINITY;for(let k=0;k<c;k++){const O=a[k],q=O.units;let Z=0;for(let Se=0,ve=q.length;Se<ve;Se++){const Ne=q[Se],Me=Ne.data,$e=Ne.data.byteLength;C.setUint32(d,$e),d+=4,x.set(Me,d),d+=$e,Z+=4+$e}let X;if(k<c-1)g=a[k+1].dts-O.dts,X=a[k+1].pts-O.pts;else{const Se=this.config,ve=k>0?O.dts-a[k-1].dts:_;if(X=k>0?O.pts-a[k-1].pts:_,Se.stretchShortVideoTrack&&this.nextAudioTs!==null){const Ne=Math.floor(Se.maxBufferHole*n),Me=(i?y+i*n:this.nextAudioTs+u)-O.pts;Me>Ne?(g=Me-ve,g<0?g=ve:M=!0,this.log(`It is approximately ${Me/90} ms to the next segment; using duration ${g/90} ms for the last video frame.`)):g=ve}else g=ve}const z=Math.round(O.pts-O.dts);K=Math.min(K,g),N=Math.max(N,g),V=Math.min(V,X),w=Math.max(w,X),o.push(Ql(O.key,g,Z,z))}if(o.length){if(Gs){if(Gs<70){const k=o[0].flags;k.dependsOn=2,k.isNonSync=0}}else if(xn&&w-V<N-K&&_/N<.025&&o[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let k=f;for(let O=0,q=o.length;O<q;O++){const Z=k+o[O].duration,X=k+o[O].cts;if(O<q-1){const z=Z+o[O+1].cts;o[O].duration=z-X}else o[O].duration=O?o[O-1].duration:_;o[O].cts=0,k=Z}}}g=M||!g?_:g;const U=p+g;this.nextVideoTs=h=U-u,this.videoSampleDuration=g,this.isVideoContiguous=!0;const W={data1:L.moof(e.sequenceNumber++,f,le(e,{samples:o})),data2:x,startPTS:(y-u)/n,endPTS:(v+g-u)/n,startDTS:(f-u)/n,endDTS:h/n,type:"video",hasAudio:!1,hasVideo:!0,nb:o.length,dropped:e.dropped};return e.samples=[],e.dropped=0,W}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return _g;case"ac3":return Ig;default:return Ag}}remuxAudio(e,t,s,i,n){const a=e.inputTimeScale,o=e.samplerate?e.samplerate:a,c=a/o,l=this.getSamplesPerFrame(e),u=l*c,h=this._initPTS,d=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,g=[],f=n!==void 0;let p=e.samples,y=d?0:8,v=this.nextAudioTs||-1;const E=h.baseTime*a/h.timescale,T=E+t*a;if(this.isAudioContiguous=s=s||p.length&&v>0&&(i&&Math.abs(T-(v+E))<9e3||Math.abs(Qe(p[0].pts,T)-(v+E))<20*u),p.forEach(function(w){w.pts=Qe(w.pts,T)}),!s||v<0){const w=p.length;if(p=p.filter(U=>U.pts>=0),w!==p.length&&this.warn(`Removed ${p.length-w} of ${w} samples (initPTS ${E} / ${a})`),!p.length)return;n===0?v=0:i&&!f?v=Math.max(0,T-E):v=p[0].pts-E}if(e.segmentCodec==="aac"){const w=this.config.maxAudioFramesDrift;for(let U=0,F=v+E;U<p.length;U++){const B=p[U],W=B.pts,k=W-F,O=Math.abs(1e3*k/a);if(k<=-w*u&&f)U===0&&(this.warn(`Audio frame @ ${(W/a).toFixed(3)}s overlaps marker by ${Math.round(1e3*k/a)} ms.`),this.nextAudioTs=v=W-E,F=W);else if(k>=w*u&&O<xg&&f){let q=Math.round(k/u);for(F=W-q*u;F<0&&q&&u;)q--,F+=u;U===0&&(this.nextAudioTs=v=F-E),this.warn(`Injecting ${q} audio frames @ ${((F-E)/a).toFixed(3)}s due to ${Math.round(1e3*k/a)} ms gap.`);for(let Z=0;Z<q;Z++){let X=Eg.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);X||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),X=B.unit.subarray()),p.splice(U,0,{unit:X,pts:F}),F+=u,U++}}B.pts=F,F+=u}}let S=null,_=null,D,I=0,b=p.length;for(;b--;)I+=p[b].unit.byteLength;for(let w=0,U=p.length;w<U;w++){const F=p[w],B=F.unit;let W=F.pts;if(_!==null){const O=g[w-1];O.duration=Math.round((W-_)/c)}else if(s&&e.segmentCodec==="aac"&&(W=v+E),S=W,I>0){I+=y;try{D=new Uint8Array(I)}catch(O){this.observer.emit(m.ERROR,m.ERROR,{type:H.MUX_ERROR,details:R.REMUX_ALLOC_ERROR,fatal:!1,error:O,bytes:I,reason:`fail allocating audio mdat ${I}`});return}d||(new DataView(D.buffer).setUint32(0,I),D.set(L.types.mdat,4))}else return;D.set(B,y);const k=B.byteLength;y+=k,g.push(Ql(!0,l,k,0)),_=W}const A=g.length;if(!A)return;const x=g[g.length-1];v=_-E,this.nextAudioTs=v+c*x.duration;const C=d?new Uint8Array(0):L.moof(e.sequenceNumber++,S/c,le({},e,{samples:g}));e.samples=[];const M=(S-E)/a,K=this.nextAudioTs/a,N={data1:C,data2:D,startPTS:M,endPTS:K,startDTS:M,endDTS:K,type:"audio",hasAudio:!0,hasVideo:!1,nb:A};return this.isAudioContiguous=!0,N}}function Qe(r,e){let t;if(e===null)return r;for(e<r?t=-8589934592:t=8589934592;Math.abs(r-e)>4294967296;)r+=t;return r}function Lg(r){for(let e=0;e<r.length;e++)if(r[e].key)return e;return-1}function Jl(r,e,t,s){const i=r.samples.length;if(!i)return;const n=r.inputTimeScale;for(let o=0;o<i;o++){const c=r.samples[o];c.pts=Qe(c.pts-t.baseTime*n/t.timescale,e*n)/n,c.dts=Qe(c.dts-s.baseTime*n/s.timescale,e*n)/n}const a=r.samples;return r.samples=[],{samples:a}}function Zl(r,e,t){const s=r.samples.length;if(!s)return;const i=r.inputTimeScale;for(let a=0;a<s;a++){const o=r.samples[a];o.pts=Qe(o.pts-t.baseTime*i/t.timescale,e*i)/i}r.samples.sort((a,o)=>a.pts-o.pts);const n=r.samples;return r.samples=[],{samples:n}}class Rg extends rt{constructor(e,t,s,i){super("passthrough-remuxer",i),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(e){this.lastEndTime=null;const t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,s,i){this.audioCodec=t,this.videoCodec=s,this.generateInitSegment(e,i),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:s,videoCodec:i}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const{audio:n,video:a}=this.initData=Eo(e);if(t)fd(e,t);else{const c=n||a;c!=null&&c.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${c.codec}")!`)}n&&(s=ec(n,ce.AUDIO,this)),a&&(i=ec(a,ce.VIDEO,this));const o={};n&&a?o.audiovideo={container:"video/mp4",codec:s+","+i,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:n?o.audio={container:"audio/mp4",codec:s,encrypted:n.encrypted,initSegment:e,id:"audio"}:a?o.video={container:"video/mp4",codec:i,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=o}remux(e,t,s,i,n,a){var o,c;let{initPTS:l,lastEndTime:u}=this;const h={audio:void 0,video:void 0,text:i,id3:s,initSegment:void 0};$(u)||(u=this.lastEndTime=n||0);const d=t.samples;if(!d.length)return h;const g={initPTS:void 0,timescale:void 0,trackId:void 0};let f=this.initData;if((o=f)!=null&&o.length||(this.generateInitSegment(d),f=this.initData),!((c=f)!=null&&c.length))return this.warn("Failed to generate initSegment."),h;this.emitInitSegment&&(g.tracks=this.initTracks,this.emitInitSegment=!1);const p=md(d,f,this),y=f.audio?p[f.audio.id]:null,v=f.video?p[f.video.id]:null,E=er(v,1/0),T=er(y,1/0),S=er(v,0,!0),_=er(y,0,!0);let D=n,I=0;const b=y&&(!v||!l&&T<E||l&&l.trackId===f.audio.id),A=b?y:v;if(A){const F=A.timescale,B=A.start-n*F,W=b?f.audio.id:f.video.id;D=A.start/F,I=b?_-T:S-E,(a||!l)&&(bg(l,D,n,I)||F!==l.timescale)&&(l&&this.warn(`Timestamps at playlist time: ${a?"":"~"}${n} ${B/F} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${n} offset: ${D-n} (${B}/${F}) trackId: ${W}`),l=null,g.initPTS=B,g.timescale=F,g.trackId=W)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${n}`);l?(g.initPTS=l.baseTime,g.timescale=l.timescale,g.trackId=l.trackId):((!g.timescale||g.trackId===void 0||g.initPTS===void 0)&&(this.warn("Could not set initPTS"),g.initPTS=D,g.timescale=1,g.trackId=-1),this.initPTS=l={baseTime:g.initPTS,timescale:g.timescale,trackId:g.trackId});const x=D-l.baseTime/l.timescale,C=x+I;I>0?this.lastEndTime=C:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const M=!!f.audio,K=!!f.video;let V="";M&&(V+="audio"),K&&(V+="video");const N=(f.audio?f.audio.encrypted:!1)||(f.video?f.video.encrypted:!1),w={data1:d,startPTS:x,startDTS:x,endPTS:C,endDTS:C,type:V,hasAudio:M,hasVideo:K,nb:1,dropped:0,encrypted:N};h.audio=M&&!K?w:void 0,h.video=K?w:void 0;const U=v?.sampleCount;if(U){const F=v.keyFrameIndex,B=F!==-1;w.nb=U,w.dropped=F===0||this.isVideoContiguous?0:B?F:U,w.independent=B,w.firstKeyFrame=F,B&&v.keyFrameStart&&(w.firstKeyFramePTS=(v.keyFrameStart-l.baseTime)/l.timescale),this.isVideoContiguous||(h.independent=B),this.isVideoContiguous||(this.isVideoContiguous=B),w.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${F}/${U} dropped: ${w.dropped} start: ${w.firstKeyFramePTS||"NA"}`)}return h.initSegment=g,h.id3=Jl(s,n,l,l),i.samples.length&&(h.text=Zl(i,n,l)),h}}function er(r,e,t=!1){return r?.start!==void 0?(r.start+(t?r.duration:0))/r.timescale:e}function bg(r,e,t,s){if(r===null)return!0;const i=Math.max(s,1),n=e-r.baseTime/r.timescale;return Math.abs(n-t)>i}function ec(r,e,t){const s=r.codec;return s&&s.length>4?s:e===ce.AUDIO?s==="ec-3"||s==="ac-3"||s==="alac"?s:s==="fLaC"||s==="Opus"?Fi(s,!1):(t.warn(`Unhandled audio codec "${s}" in mp4 MAP`),s||"mp4a"):(t.warn(`Unhandled video codec "${s}" in mp4 MAP`),s||"avc1")}let $t;try{$t=self.performance.now.bind(self.performance)}catch{$t=Date.now}const tr=[{demux:fg,remux:Rg},{demux:ss,remux:Zi},{demux:cg,remux:Zi},{demux:hg,remux:Zi}];tr.splice(2,0,{demux:ug,remux:Zi});class tc{constructor(e,t,s,i,n,a){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=s,this.id=n,this.logger=a}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,s,i){const n=s.transmuxing;n.executeStart=$t();let a=new Uint8Array(e);const{currentTransmuxState:o,transmuxConfig:c}=this;i&&(this.currentTransmuxState=i);const{contiguous:l,discontinuity:u,trackSwitch:h,accurateTimeOffset:d,timeOffset:g,initSegmentChange:f}=i||o,{audioCodec:p,videoCodec:y,defaultInitPts:v,duration:E,initSegmentData:T}=c,S=Dg(a,t);if(S&&Ns(S.method)){const b=this.getDecrypter(),A=en(S.method);if(b.isSync()){let x=b.softwareDecrypt(a,S.key.buffer,S.iv.buffer,A);if(s.part>-1){const M=b.flush();x=M&&M.buffer}if(!x)return n.executeEnd=$t(),An(s);a=new Uint8Array(x)}else return this.asyncResult=!0,this.decryptionPromise=b.webCryptoDecrypt(a,S.key.buffer,S.iv.buffer,A).then(x=>{const C=this.push(x,null,s);return this.decryptionPromise=null,C}),this.decryptionPromise}const _=this.needsProbing(u,h);if(_){const b=this.configureTransmuxer(a);if(b)return this.logger.warn(`[transmuxer] ${b.message}`),this.observer.emit(m.ERROR,m.ERROR,{type:H.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,error:b,reason:b.message}),n.executeEnd=$t(),An(s)}(u||h||f||_)&&this.resetInitSegment(T,p,y,E,t),(u||f||_)&&this.resetInitialTimestamp(v),l||this.resetContiguity();const D=this.transmux(a,S,g,d,s);this.asyncResult=ui(D);const I=this.currentTransmuxState;return I.contiguous=!0,I.discontinuity=!1,I.trackSwitch=!1,n.executeEnd=$t(),D}flush(e){const t=e.transmuxing;t.executeStart=$t();const{decrypter:s,currentTransmuxState:i,decryptionPromise:n}=this;if(n)return this.asyncResult=!0,n.then(()=>this.flush(e));const a=[],{timeOffset:o}=i;if(s){const h=s.flush();h&&a.push(this.push(h.buffer,null,e))}const{demuxer:c,remuxer:l}=this;if(!c||!l){t.executeEnd=$t();const h=[An(e)];return this.asyncResult?Promise.resolve(h):h}const u=c.flush(o);return ui(u)?(this.asyncResult=!0,u.then(h=>(this.flushRemux(a,h,e),a))):(this.flushRemux(a,u,e),this.asyncResult?Promise.resolve(a):a)}flushRemux(e,t,s){const{audioTrack:i,videoTrack:n,id3Track:a,textTrack:o}=t,{accurateTimeOffset:c,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${s.sn}${s.part>-1?" part: "+s.part:""} of ${this.id===G.MAIN?"level":"track"} ${s.level}`);const u=this.remuxer.remux(i,n,a,o,l,c,!0,this.id);e.push({remuxResult:u,chunkMeta:s}),s.transmuxing.executeEnd=$t()}resetInitialTimestamp(e){const{demuxer:t,remuxer:s}=this;!t||!s||(t.resetTimeStamp(e),s.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,s,i,n){const{demuxer:a,remuxer:o}=this;!a||!o||(a.resetInitSegment(e,t,s,i),o.resetInitSegment(e,t,s,n))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,s,i,n){let a;return t&&t.method==="SAMPLE-AES"?a=this.transmuxSampleAes(e,t,s,i,n):a=this.transmuxUnencrypted(e,s,i,n),a}transmuxUnencrypted(e,t,s,i){const{audioTrack:n,videoTrack:a,id3Track:o,textTrack:c}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(n,a,o,c,t,s,!1,this.id),chunkMeta:i}}transmuxSampleAes(e,t,s,i,n){return this.demuxer.demuxSampleAes(e,t,s).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,s,i,!1,this.id),chunkMeta:n}))}configureTransmuxer(e){const{config:t,observer:s,typeSupported:i}=this;let n;for(let h=0,d=tr.length;h<d;h++){var a;if((a=tr[h].demux)!=null&&a.probe(e,this.logger)){n=tr[h];break}}if(!n)return new Error("Failed to find demuxer by probing fragment data");const o=this.demuxer,c=this.remuxer,l=n.remux,u=n.demux;(!c||!(c instanceof l))&&(this.remuxer=new l(s,t,i,this.logger)),(!o||!(o instanceof u))&&(this.demuxer=new u(s,t,i,this.logger),this.probe=u.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new Qr(this.config)),e}}function Dg(r,e){let t=null;return r.byteLength>0&&e?.key!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const An=r=>({remuxResult:{},chunkMeta:r});function ui(r){return"then"in r&&r.then instanceof Function}class Cg{constructor(e,t,s,i,n){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=s,this.duration=i,this.defaultInitPts=n||null}}class Pg{constructor(e,t,s,i,n,a){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=s,this.trackSwitch=i,this.timeOffset=n,this.initSegmentChange=a}}let sc=0;class ic{constructor(e,t,s,i){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=sc++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=c=>{const l=c.data,u=this.hls;if(!(!u||!(l!=null&&l.event)||l.instanceNo!==this.instanceNo))switch(l.event){case"init":{var h;const d=(h=this.workerContext)==null?void 0:h.objectURL;d&&self.URL.revokeObjectURL(d);break}case"transmuxComplete":{this.handleTransmuxComplete(l.data);break}case"flush":{this.onFlush(l.data);break}case"workerLog":{u.logger[l.data.logType]&&u.logger[l.data.logType](l.data.message);break}default:{l.data=l.data||{},l.data.frag=this.frag,l.data.part=this.part,l.data.id=this.id,u.trigger(l.event,l.data);break}}},this.onWorkerError=c=>{if(!this.hls)return;const l=new Error(`${c.message} (${c.filename}:${c.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(m.ERROR,{type:H.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:l})};const n=e.config;this.hls=e,this.id=t,this.useWorker=!!n.enableWorker,this.onTransmuxComplete=s,this.onFlush=i;const a=(c,l)=>{l=l||{},l.frag=this.frag||void 0,c===m.ERROR&&(l=l,l.parent=this.id,l.part=this.part,this.error=l.error),this.hls.trigger(c,l)};this.observer=new hn,this.observer.on(m.FRAG_DECRYPTED,a),this.observer.on(m.ERROR,a);const o=Ro(n.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const c=this.hls.logger;if(n.workerPath||Mf()){try{n.workerPath?(c.log(`loading Web Worker ${n.workerPath} for "${t}"`),this.workerContext=Nf(n.workerPath)):(c.log(`injecting Web Worker for "${t}"`),this.workerContext=Ff());const{worker:u}=this.workerContext;u.addEventListener("message",this.onWorkerMessage),u.addEventListener("error",this.onWorkerError),u.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:t,config:ue(n)})}catch(u){c.warn(`Error setting up "${t}" Web Worker, fallback to inline`,u),this.terminateWorker(),this.error=null,this.transmuxer=new tc(this.observer,o,n,"",t,e.logger)}return}}this.transmuxer=new tc(this.observer,o,n,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=sc++;const t=this.hls.config,s=Ro(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:s,id:this.id,config:ue(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),$f(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,s,i,n,a,o,c,l,u){var h,d;l.transmuxing.start=self.performance.now();const{instanceNo:g,transmuxer:f}=this,p=a?a.start:n.start,y=n.decryptdata,v=this.frag,E=!(v&&n.cc===v.cc),T=!(v&&l.level===v.level),S=v?l.sn-v.sn:-1,_=this.part?l.part-this.part.index:-1,D=S===0&&l.id>1&&l.id===v?.stats.chunkCount,I=!T&&(S===1||S===0&&(_===1||D&&_<=0)),b=self.performance.now();(T||S||n.stats.parsing.start===0)&&(n.stats.parsing.start=b),a&&(_||!I)&&(a.stats.parsing.start=b);const A=!(v&&((h=n.initSegment)==null?void 0:h.url)===((d=v.initSegment)==null?void 0:d.url)),x=new Pg(E,I,c,T,p,A);if(!I||E||A){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${n.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===G.MAIN?"level":"track"}: ${l.level} id: ${l.id}
18
- discontinuity: ${E}
19
- trackSwitch: ${T}
20
- contiguous: ${I}
21
- accurateTimeOffset: ${c}
22
- timeOffset: ${p}
23
- initSegmentChange: ${A}`);const C=new Cg(s,i,t,o,u);this.configureTransmuxer(C)}if(this.frag=n,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:g,cmd:"demux",data:e,decryptdata:y,chunkMeta:l,state:x},e instanceof ArrayBuffer?[e]:[]);else if(f){const C=f.push(e,y,l,x);ui(C)?C.then(M=>{this.handleTransmuxComplete(M)}).catch(M=>{this.transmuxerError(M,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(C)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:s}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(s){const i=s.flush(e);ui(i)?i.then(n=>{this.handleFlushResult(n,e)}).catch(n=>{this.transmuxerError(n,e,"transmuxer-interface flush error")}):this.handleFlushResult(i,e)}}transmuxerError(e,t,s){this.hls&&(this.error=e,this.hls.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:s}))}handleFlushResult(e,t){e.forEach(s=>{this.handleTransmuxComplete(s)}),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:s}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):s&&s.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}const rc=100;class wg extends cn{constructor(e,t,s){super(e,t,s,"audio-stream-controller",G.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(m.BUFFER_RESET,this.onBufferReset,this),e.on(m.BUFFER_CREATED,this.onBufferCreated,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(m.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(m.FRAG_LOADING,this.onFragLoading,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(m.BUFFER_RESET,this.onBufferReset,this),e.off(m.BUFFER_CREATED,this.onBufferCreated,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(m.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(m.FRAG_LOADING,this.onFragLoading,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:s,initPTS:i,timescale:n,trackId:a}){if(s===G.MAIN){const o=t.cc,c=this.fragCurrent;if(this.initPTS[o]={baseTime:i,timescale:n,trackId:a},this.log(`InitPTS for cc: ${o} found from main: ${i/n} (${i}/${n}) trackId: ${a}`),this.mainAnchor=t,this.state===P.WAITING_INIT_PTS){const l=this.waitingData;(!l&&!this.loadingParts||l&&l.frag.cc!==o)&&this.syncWithAnchor(t,l?.frag)}else!this.hls.hasEnoughToStart&&c&&c.cc!==o?(c.abortRequests(),this.syncWithAnchor(t,c)):this.state===P.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var s;const i=((s=this.mainFragLoading)==null?void 0:s.frag)||null;if(t&&i?.cc===t.cc)return;const n=(i||e).cc,a=this.getLevelDetails(),o=this.getLoadPosition(),c=Uo(a,n,o);c&&(this.log(`Syncing with main frag at ${c.start} cc ${c.cc}`),this.startFragRequested=!1,this.nextLoadPosition=c.start,this.resetLoadingState(),this.state===P.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=P.STOPPED;return}const s=this.lastCurrentTime;this.stopLoad(),this.setInterval(rc),s>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s,this.state=P.IDLE):this.state=P.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case P.IDLE:this.doTickIdle();break;case P.WAITING_TRACK:{const{levels:e,trackId:t}=this,s=e?.[t],i=s?.details;if(i&&!this.waitForLive(s)){if(this.waitForCdnTuneIn(i))break;this.state=P.WAITING_INIT_PTS}break}case P.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case P.WAITING_INIT_PTS:{const e=this.waitingData;if(e){const{frag:t,part:s,cache:i,complete:n}=e,a=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=P.FRAG_LOADING;const o=i.flush().buffer,c={frag:t,part:s,payload:o,networkDetails:null};this._handleFragmentLoadProgress(c),n&&super._handleFragmentLoadComplete(c)}else a&&a.cc!==e.frag.cc&&this.syncWithAnchor(a,e.frag)}else this.state=P.IDLE}}this.onTickEnd()}resetLoadingState(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;const{hls:t,levels:s,media:i,trackId:n}=this,a=t.config;if(!this.buffering||!i&&!this.primaryPrefetch&&(this.startFragRequested||!a.startFragPrefetch)||!(s!=null&&s[n]))return;const o=s[n],c=o.details;if(!c||this.waitForLive(o)||this.waitForCdnTuneIn(c)){this.state=P.WAITING_TRACK,this.startFragRequested=!1;return}const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,ce.AUDIO,G.AUDIO));const u=this.getFwdBufferInfo(l,G.AUDIO);if(u===null)return;if(!this.switchingTrack&&this._streamEnded(u,c)){t.trigger(m.BUFFER_EOS,{type:"audio"}),this.state=P.ENDED;return}const h=u.len,d=t.maxBufferLength,g=c.fragments,f=g[0].start,p=this.getLoadPosition(),y=this.flushing?p:u.end;if(this.switchingTrack&&i){const T=p;c.PTSKnown&&T<f&&(u.end>f||u.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=f+.05)}if(h>=d&&!this.switchingTrack&&y<g[g.length-1].start)return;let v=this.getNextFragment(y,c);if(v&&this.isLoopLoading(v,y)&&(v=this.getNextFragmentLoopLoading(v,c,u,G.MAIN,d)),!v){this.bufferFlushed=!0;return}let E=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&E&&xe(v)&&!v.endList&&(!c.live||!this.loadingParts&&y<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(E)===Re.OK&&(this.mainFragLoading=E=null),E&&xe(E))){if(v.start>E.end){const S=this.fragmentTracker.getFragAtPos(y,G.MAIN);S&&S.end>E.end&&(E=S,this.mainFragLoading={frag:S,targetBufferTime:null})}if(v.start>E.end)return}this.loadFragment(v,o,y)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(s=>new ii(s))}onAudioTrackSwitching(e,t){const s=!!t.url;this.trackId=t.id;const{fragCurrent:i}=this;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),s?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==P.STOPPED&&(this.setInterval(rc),this.state=P.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;const s=this.cachedTrackLoadedData;s&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(m.AUDIO_TRACK_LOADED,s))}onAudioTrackLoaded(e,t){var s;const{levels:i}=this,{details:n,id:a,groupId:o,track:c}=t;if(!i){this.warn(`Audio tracks reset while loading track ${a} "${c.name}" of "${o}"`);return}const l=this.mainDetails;if(!l||n.endCC>l.endCC||l.expired){this.cachedTrackLoadedData=t,this.state!==P.STOPPED&&(this.state=P.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${a} "${c.name}" of "${o}" loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`);const u=i[a];let h=0;if(n.live||(s=u.details)!=null&&s.live){if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;if(u.details){var d;h=this.alignPlaylists(n,u.details,(d=this.levelLastLoaded)==null?void 0:d.details)}n.alignedSliding||(Dl(n,l),n.alignedSliding||ji(n,l),h=n.fragmentStart)}u.details=n,this.levelLastLoaded=u,this.startFragRequested||this.setStartPosition(l,h),this.hls.trigger(m.AUDIO_TRACK_UPDATED,{details:n,id:a,groupId:t.groupId}),this.state===P.WAITING_TRACK&&!this.waitForCdnTuneIn(n)&&(this.state=P.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:i,payload:n}=e,{config:a,trackId:o,levels:c}=this;if(!c){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}const l=c[o];if(!l){this.warn("Audio track is undefined on fragment load progress");return}const u=l.details;if(!u){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(s.start);return}const h=a.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let d=this.transmuxer;d||(d=this.transmuxer=new ic(this.hls,G.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const g=this.initPTS[s.cc],f=(t=s.initSegment)==null?void 0:t.data;if(g!==void 0){const y=i?i.index:-1,v=y!==-1,E=new Jr(s.level,s.sn,s.stats.chunkCount,n.byteLength,y,v);d.push(n,f,h,"",s,i,u.totalduration,!1,E,g)}else{this.log(`Unknown video PTS for cc ${s.cc}, waiting for video PTS before demuxing audio frag ${s.sn} of [${u.startSN} ,${u.endSN}],track ${o}`);const{cache:p}=this.waitingData=this.waitingData||{frag:s,part:i,cache:new Pl,complete:!1};p.push(new Uint8Array(n)),this.state!==P.STOPPED&&(this.state=P.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;const s=t.tracks.audio;s&&(this.mediaBuffer=s.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===G.MAIN&&xe(t.frag)&&(this.mainFragLoading=t,this.state===P.IDLE&&this.tick())}onFragBuffered(e,t){const{frag:s,part:i}=t;if(s.type!==G.AUDIO){!this.audioOnly&&s.type===G.MAIN&&!s.elementaryStreams.video&&!s.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(xe(s)){this.fragPrevious=s;const n=this.switchingTrack;n&&(this.bufferedTrack=n,this.switchingTrack=null,this.hls.trigger(m.AUDIO_TRACK_SWITCHED,ae({},n)))}this.fragBufferedComplete(s,i),this.media&&this.tick()}onError(e,t){var s;if(t.fatal){this.state=P.ERROR;return}switch(t.details){case R.FRAG_GAP:case R.FRAG_PARSING_ERROR:case R.FRAG_DECRYPT_ERROR:case R.FRAG_LOAD_ERROR:case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_ERROR:case R.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(G.AUDIO,t);break;case R.AUDIO_TRACK_LOAD_ERROR:case R.AUDIO_TRACK_LOAD_TIMEOUT:case R.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===P.WAITING_TRACK&&((s=t.context)==null?void 0:s.type)===ee.AUDIO_TRACK&&(this.state=P.IDLE);break;case R.BUFFER_ADD_CODEC_ERROR:case R.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case R.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case R.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==ce.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==ce.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===P.ENDED&&(this.state=P.IDLE);const s=this.mediaBuffer||this.media;s&&(this.afterBufferFlushed(s,t,G.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;const s="audio",{hls:i}=this,{remuxResult:n,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}const{frag:c,part:l,level:u}=o,{details:h}=u,{audio:d,text:g,id3:f,initSegment:p}=n;if(this.fragContextChanged(c)||!h){this.fragmentTracker.removeFragment(c);return}if(this.state=P.PARSING,this.switchingTrack&&d&&this.completeAudioSwitch(this.switchingTrack),p!=null&&p.tracks){const y=c.initSegment||c;if(this.unhandledEncryptionError(p,c))return;this._bufferInitSegment(u,p.tracks,y,a),i.trigger(m.FRAG_PARSING_INIT_SEGMENT,{frag:y,id:s,tracks:p.tracks})}if(d){const{startPTS:y,endPTS:v,startDTS:E,endDTS:T}=d;l&&(l.elementaryStreams[ce.AUDIO]={startPTS:y,endPTS:v,startDTS:E,endDTS:T}),c.setElementaryStreamInfo(ce.AUDIO,y,v,E,T),this.bufferFragmentData(d,c,l,a)}if(f!=null&&(t=f.samples)!=null&&t.length){const y=le({id:s,frag:c,details:h},f);i.trigger(m.FRAG_PARSING_METADATA,y)}if(g){const y=le({id:s,frag:c,details:h},g);i.trigger(m.FRAG_PARSING_USERDATA,y)}}_bufferInitSegment(e,t,s,i){if(this.state!==P.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;const n=t.audio;n.id=G.AUDIO;const a=e.audioCodec;this.log(`Init audio buffer, container:${n.container}, codecs[level/parsed]=[${a}/${n.codec}]`),a&&a.split(",").length===1&&(n.levelCodec=a),this.hls.trigger(m.BUFFER_CODECS,t);const o=n.initSegment;if(o!=null&&o.byteLength){const c={type:"audio",frag:s,part:null,chunkMeta:i,parent:s.type,data:o};this.hls.trigger(m.BUFFER_APPENDING,c)}this.tickImmediate()}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);if(this.switchingTrack||i===Re.NOT_LOADED||i===Re.PARTIAL){var n;if(!xe(e))this._loadInitSegment(e,t);else if((n=t.details)!=null&&n.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=P.WAITING_INIT_PTS;const a=this.mainDetails;a&&a.fragmentStart!==t.details.fragmentStart&&ji(t.details,a)}else super.loadFragment(e,t,s)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){const{name:t,lang:s,assocLang:i,characteristics:n,audioCodec:a,channels:o}=this.bufferedTrack;ds({name:t,lang:s,assocLang:i,characteristics:n,audioCodec:a,channels:o},e,fs)||(Ui(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){const{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(m.AUDIO_TRACK_SWITCHED,ae({},e))}}class _n extends rt{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,s){const i=t?.renditionReports;if(i){let n=-1;for(let a=0;a<i.length;a++){const o=i[a];let c;try{c=new self.URL(o.URI,t.url).href}catch(l){this.warn(`Could not construct new URL for Rendition Report: ${l}`),c=o.URI||""}if(c===e){n=a;break}else c===e.substring(0,c.length)&&(n=a)}if(n!==-1){const a=i[n],o=parseInt(a["LAST-MSN"])||t.lastPartSn;let c=parseInt(a["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){const u=Math.min(t.age-t.partTarget,t.targetduration);c>=0&&u>t.partTarget&&(c+=1)}const l=s&&wo(s);return new ko(o,c>=0?c:void 0,l)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(s){this.warn(`Could not construct new URL with HLS Delivery Directives: ${s}`)}return e}playlistLoaded(e,t,s){const{details:i,stats:n}=t,a=self.performance.now(),o=n.loading.first?Math.max(0,a-n.loading.first):0;i.advancedDateTime=Date.now()-o;const c=this.hls.config.timelineOffset;if(c!==i.appliedTimelineOffset){const u=Math.max(c||0,0);i.appliedTimelineOffset=u,i.fragments.forEach(h=>{h.setStart(h.playlistOffset+u)})}if(i.live||s!=null&&s.live){const u="levelInfo"in t?t.levelInfo:t.track;if(i.reloaded(s),s&&i.fragments.length>0){_f(s,i,this);const E=i.playlistParsingError;if(E){this.warn(E);const T=this.hls;if(!T.config.ignorePlaylistParsingErrors){var l;const{networkDetails:S}=t;T.trigger(m.ERROR,{type:H.NETWORK_ERROR,details:R.LEVEL_PARSING_ERROR,fatal:!1,url:i.url,error:E,reason:E.message,level:t.level||void 0,parent:(l=i.fragments[0])==null?void 0:l.type,networkDetails:S,stats:n});return}i.playlistParsingError=null}}i.requestScheduled===-1&&(i.requestScheduled=n.loading.start);const h=this.hls.mainForwardBufferInfo,d=h?h.end-h.len:0,g=(i.edge-d)*1e3,f=Sl(i,g);if(i.requestScheduled+f<a?i.requestScheduled=a:i.requestScheduled+=f,this.log(`live playlist ${e} ${i.advanced?"REFRESHED "+i.lastPartSn+"-"+i.lastPartIndex:i.updated?"UPDATED":"MISSED"}`),!this.canLoad||!i.live)return;let p,y,v;if(i.canBlockReload&&i.endSN&&i.advanced){const E=this.hls.config.lowLatencyMode,T=i.lastPartSn,S=i.endSN,_=i.lastPartIndex,D=_!==-1,I=T===S;D?I?(y=S+1,v=E?0:_):(y=T,v=E?_+1:i.maxPartIndex):y=S+1;const b=i.age,A=b+i.ageHeader;let x=Math.min(A-i.partTarget,i.targetduration*1.5);if(x>0){if(A>i.targetduration*3)this.log(`Playlist last advanced ${b.toFixed(2)}s ago. Omitting segment and part directives.`),y=void 0,v=void 0;else if(s!=null&&s.tuneInGoal&&A-i.partTarget>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${x} with playlist age: ${i.age}`),x=0;else{const C=Math.floor(x/i.targetduration);if(y+=C,v!==void 0){const M=Math.round(x%i.targetduration/i.partTarget);v+=M}this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${b.toFixed(2)}s goal: ${x} skip sn ${C} to part ${v}`)}i.tuneInGoal=x}if(p=this.getDeliveryDirectives(i,t.deliveryDirectives,y,v),E||!I){i.requestScheduled=a,this.loadingPlaylist(u,p);return}}else(i.canBlockReload||i.canSkipUntil)&&(p=this.getDeliveryDirectives(i,t.deliveryDirectives,y,v));p&&y!==void 0&&i.canBlockReload&&(i.requestScheduled=n.loading.first+Math.max(f-o*2,f/2)),this.scheduleLoading(u,p,i)}else this.clearTimer()}scheduleLoading(e,t,s){const i=s||e.details;if(!i){this.loadingPlaylist(e,t);return}const n=self.performance.now(),a=i.requestScheduled;if(n>=a){this.loadingPlaylist(e,t);return}const o=a-n;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(o)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),o)}getDeliveryDirectives(e,t,s,i){let n=wo(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(s=t.msn,i=t.part,n=Bi.No),new ko(s,i,n)}checkRetry(e){const t=e.details,s=Gi(e),i=e.errorAction,{action:n,retryCount:a=0,retryConfig:o}=i||{},c=!!i&&!!o&&(n===ke.RetryRequest||!i.resolved&&n===ke.SendAlternateToPenaltyBox);if(c){var l;if(a>=o.maxNumRetry)return!1;if(s&&(l=e.context)!=null&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const u=Xr(o,a);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),u),this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" in ${u}ms`)}e.levelRetry=!0,i.resolved=!0}return c}}function nc(r,e){if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(!hi(r[t].attrs,e[t].attrs))return!1;return!0}function hi(r,e,t){const s=r["STABLE-RENDITION-ID"];return s&&!t?s===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(i=>r[i]!==e[i])}function In(r,e){return e.label.toLowerCase()===r.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(r.lang||"").toLowerCase())}class kg extends _n{constructor(e){super(e,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.LEVEL_LOADING,this.onLevelLoading,this),e.on(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.LEVEL_LOADING,this.onLevelLoading,this),e.off(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(m.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:s,groupId:i,details:n}=t,a=this.tracksInGroup[s];if(!a||a.groupId!==i){this.warn(`Audio track with id:${s} and group:${i} not found in active group ${a?.groupId}`);return}const o=a.details;a.details=t.details,this.log(`Audio track ${s} "${a.name}" lang:${a.lang} group:${i} loaded [${n.startSN}-${n.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const s=t.audioGroups||null,i=this.groupIds;let n=this.currentTrack;if(!s||i?.length!==s?.length||s!=null&&s.some(o=>i?.indexOf(o)===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(d=>!s||s.indexOf(d.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(d=>d.default)&&(this.selectDefaultTrack=!1),o.forEach((d,g)=>{d.id=g});else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const c=this.hls.config.audioPreference;if(!n&&c){const d=At(c,o,fs);if(d>-1)n=o[d];else{const g=At(c,this.tracks);n=this.tracks[g]}}let l=this.findTrackId(n);l===-1&&n&&(l=this.findTrackId(null));const u={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${s?.join(",")}`),this.hls.trigger(m.AUDIO_TRACKS_UPDATED,u);const h=this.trackId;if(l!==-1&&h===-1)this.setAudioTrack(l);else if(o.length&&h===-1){var a;const d=new Error(`No audio track selected for current audio group-ID(s): ${(a=this.groupIds)==null?void 0:a.join(",")} track count: ${o.length}`);this.warn(d.message),this.hls.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:R.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:d})}}}onError(e,t){t.fatal||!t.context||t.context.type===ee.AUDIO_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){const t=this.hls;if(t.config.audioPreference=e,e){const s=this.allAudioTracks;if(this.selectDefaultTrack=!1,s.length){const i=this.currentTrack;if(i&&ds(e,i,fs))return i;const n=At(e,this.tracksInGroup,fs);if(n>-1){const a=this.tracksInGroup[n];return this.setAudioTrack(n),a}else if(i){let a=t.loadLevel;a===-1&&(a=t.firstAutoLevel);const o=Hd(e,t.levels,s,a,fs);if(o===-1)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){const a=At(e,s);if(a>-1)return s[a]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;const s=this.currentTrack,i=t[e],n=i.details&&!i.details.live;if(e===this.trackId&&i===s&&n||(this.log(`Switching to audio-track ${e} "${i.name}" lang:${i.lang} group:${i.groupId} channels:${i.channels}`),this.trackId=e,this.currentTrack=i,this.hls.trigger(m.AUDIO_TRACK_SWITCHING,ae({},i)),n))return;const a=this.switchParams(i.url,s?.details,i.details);this.loadPlaylist(a)}findTrackId(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){const i=t[s];if(!(this.selectDefaultTrack&&!i.default)&&(!e||ds(e,i,fs)))return s}if(e){const{name:s,lang:i,assocLang:n,characteristics:a,audioCodec:o,channels:c}=e;for(let l=0;l<t.length;l++){const u=t[l];if(ds({name:s,lang:i,assocLang:n,characteristics:a,audioCodec:o,channels:c},u,fs))return l}for(let l=0;l<t.length;l++){const u=t[l];if(hi(e.attrs,u.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return l}for(let l=0;l<t.length;l++){const u=t[l];if(hi(e.attrs,u.attrs,["LANGUAGE"]))return l}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;this.shouldLoadPlaylist(t)&&Ui(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=e.id,i=e.groupId,n=this.getUrlWithDirectives(e.url,t),a=e.details,o=a?.age;this.log(`Loading audio-track ${s} "${e.name}" lang:${e.lang} group:${i}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${n}`),this.hls.trigger(m.AUDIO_TRACK_LOADING,{url:n,id:s,groupId:i,deliveryDirectives:t||null,track:e})}}class Og{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,s){if(this.queues===null||this.tracks===null)return;const i=this.queues[t];i.push(e),i.length===1&&!s&&this.executeNext(t)}appendBlocker(e){return new Promise(t=>{const s={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(s,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){const s={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(s)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;const s=(t=e[0])==null?void 0:t.label;(s==="async-blocker"||s==="async-blocker-prepend")&&(e[0].execute(),e.splice(0,1))})}unblockAudio(e){if(this.queues===null)return;this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(this.queues===null||this.tracks===null)return;const t=this.queues[e];if(t.length){const i=t[0];try{i.execute()}catch(n){var s;if(i.onError(n),this.queues===null||this.tracks===null)return;const a=(s=this.tracks[e])==null?void 0:s.buffer;a!=null&&a.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues!==null&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return((t=this.queues)==null?void 0:t[e][0])||null}toString(){const{queues:e,tracks:t}=this;return e===null||t===null?"<destroyed>":`
24
- ${this.list("video")}
25
- ${this.list("audio")}
26
- ${this.list("audiovideo")}}`}list(e){var t,s;return(t=this.queues)!=null&&t[e]||(s=this.tracks)!=null&&s[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const s=(t=this.tracks)==null?void 0:t[e],i=s?.buffer;return i?`SourceBuffer${i.updating?" updating":""}${s.ended?" ended":""}${s.ending?" ending":""}`:"none"}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map(s=>s.label).join(", "))||""}}const ac=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,oc="HlsJsTrackRemovedError";class Mg extends Error{constructor(e){super(e),this.name=oc}}class Fg extends rt{constructor(e,t){super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=s=>{var i;this.hls&&((i=this.mediaSource)==null?void 0:i.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=s=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=s=>{const{media:i,mediaSource:n}=this;s&&this.log("Media source opened"),!(!i||!n)&&(n.removeEventListener("sourceopen",this._onMediaSourceOpen),i.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(m.MEDIA_ATTACHED,{media:i,mediaSource:n}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:s,_objectUrl:i}=this;s!==i&&this.error(`Media element src was set while attaching MediaSource (${i} > ${s})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=id(Zt(e.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:e}=this;e.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.BUFFER_RESET,this.onBufferReset,this),e.on(m.BUFFER_APPENDING,this.onBufferAppending,this),e.on(m.BUFFER_CODECS,this.onBufferCodecs,this),e.on(m.BUFFER_EOS,this.onBufferEos,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(m.FRAG_PARSED,this.onFragParsed,this),e.on(m.FRAG_CHANGED,this.onFragChanged,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.BUFFER_RESET,this.onBufferReset,this),e.off(m.BUFFER_APPENDING,this.onBufferAppending,this),e.off(m.BUFFER_CODECS,this.onBufferCodecs,this),e.off(m.BUFFER_EOS,this.onBufferEos,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(m.FRAG_PARSED,this.onFragParsed,this),e.off(m.FRAG_CHANGED,this.onFragChanged,this),e.off(m.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:t}=this;if(!e)return null;const s={};if(this.operationQueue){const n=this.isUpdating();n||this.operationQueue.removeBlockers();const a=this.isQueued();(n||a)&&this.warn(`Transfering MediaSource with${a?" operations in queue":""}${n?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const i=this.transferData;return!this.sourceBufferCount&&i&&i.mediaSource===t?le(s,i.tracks):this.sourceBuffers.forEach(n=>{const[a]=n;a&&(s[a]=le({},this.tracks[a]),this.removeBuffer(a)),n[0]=n[1]=null}),{media:e,mediaSource:t,tracks:s}}initTracks(){const e={};this.sourceBuffers=[[null,null],[null,null]],this.tracks=e,this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){var s;let i=2;(t.audio&&!t.video||!t.altAudio)&&(i=1),this.bufferCodecEventsTotal=i,this.log(`${i} bufferCodec event(s) expected.`),(s=this.transferData)!=null&&s.mediaSource&&this.sourceBufferCount&&i&&this.bufferCreated()}onMediaAttaching(e,t){const s=this.media=t.media;this.transferData=this.overrides=void 0;const i=Zt(this.appendSource);if(i){const n=!!t.mediaSource;(n||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const a=this.mediaSource=t.mediaSource||new i;if(this.assignMediaSource(a),n)this._objectUrl=s.src,this.attachTransferred();else{const o=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{s.removeAttribute("src");const c=self.ManagedMediaSource;s.disableRemotePlayback=s.disableRemotePlayback||c&&a instanceof c,lc(s),Ng(s,o),s.load()}catch{s.src=o}else s.src=o}s.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,s;this.log(`${((t=this.transferData)==null?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${(s=e.constructor)==null?void 0:s.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const e=this.media,t=this.transferData;if(!t||!e)return;const s=this.tracks,i=t.tracks,n=i?Object.keys(i):null,a=n?n.length:0,o=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(i&&n&&a){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
27
- required tracks: ${ue(s,(c,l)=>c==="initSegment"?void 0:l)};
28
- transfer tracks: ${ue(i,(c,l)=>c==="initSegment"?void 0:l)}}`),!lo(i,s)){t.mediaSource=null,t.tracks=void 0;const c=e.currentTime,l=this.details,u=Math.max(c,l?.fragments[0].start||0);if(u-c>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${c} -> ${u}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(i)}"->"${Object.keys(s)}") start time: ${u} currentTime: ${c}`),this.onMediaDetaching(m.MEDIA_DETACHING,{}),this.onMediaAttaching(m.MEDIA_ATTACHING,t),e.currentTime=u;return}this.transferData=void 0,n.forEach(c=>{const l=c,u=i[l];if(u){const h=u.buffer;if(h){const d=this.fragmentTracker,g=u.id;if(d.hasFragments(g)||d.hasParts(g)){const y=j.getBuffered(h);d.detectEvictedFragments(l,y,g,null,!0)}const f=Ln(l),p=[l,h];this.sourceBuffers[f]=p,h.updating&&this.operationQueue&&this.operationQueue.prependBlocker(l),this.trackSourceBuffer(l,u)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}get mediaSourceOpenOrEnded(){var e;const t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){const s=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:i,mediaSource:n,_objectUrl:a}=this;if(n){if(this.log(`media source ${s?"transferring":"detaching"}`),s)this.sourceBuffers.forEach(([o])=>{o&&this.removeBuffer(o)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const o=n.readyState==="open";try{const c=n.sourceBuffers;for(let l=c.length;l--;)o&&c[l].abort(),n.removeSourceBuffer(c[l]);o&&n.endOfStream()}catch(c){this.warn(`onMediaDetaching: ${c.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}n.removeEventListener("sourceopen",this._onMediaSourceOpen),n.removeEventListener("sourceended",this._onMediaSourceEnded),n.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(n.removeEventListener("startstreaming",this._onStartStreaming),n.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}i&&(i.removeEventListener("emptied",this._onMediaEmptied),s||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a?(i.removeAttribute("src"),this.appendSource&&lc(i),i.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(m.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;const s=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),s)try{var i;(i=this.mediaSource)!=null&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(s)}catch(n){this.warn(`onBufferReset ${e}`,n)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[Ln(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new Og(this.tracks)}onBufferCodecs(e,t){var s;const i=this.tracks,n=Object.keys(t);this.log(`BUFFER_CODECS: "${n}" (current SB count ${this.sourceBufferCount})`);const a="audiovideo"in t&&(i.audio||i.video)||i.audiovideo&&("audio"in t||"video"in t),o=!a&&this.sourceBufferCount&&this.media&&n.some(c=>!i[c]);if(a||o){this.warn(`Unsupported transition between "${Object.keys(i)}" and "${n}" SourceBuffers`);return}n.forEach(c=>{var l,u;const h=t[c],{id:d,codec:g,levelCodec:f,container:p,metadata:y,supplemental:v}=h;let E=i[c];const T=(l=this.transferData)==null||(l=l.tracks)==null?void 0:l[c],S=T!=null&&T.buffer?T:E,_=S?.pendingCodec||S?.codec,D=S?.levelCodec;E||(E=i[c]={buffer:void 0,listeners:[],codec:g,supplemental:v,container:p,levelCodec:f,metadata:y,id:d});const I=Ni(_,D),b=I?.replace(ac,"$1");let A=Ni(g,f);const x=(u=A)==null?void 0:u.replace(ac,"$1");A&&I&&b!==x&&(c.slice(0,5)==="audio"&&(A=Fi(A,this.appendSource)),this.log(`switching codec ${_} to ${A}`),A!==(E.pendingCodec||E.codec)&&(E.pendingCodec=A),E.container=p,this.appendChangeType(c,p,A))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&((s=t.audio)==null?void 0:s.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{const s=this.tracks[t];return e[t]={id:s.id,container:s.container,codec:s.codec,levelCodec:s.levelCodec},e},{})}appendChangeType(e,t,s){const i=`${t};codecs=${s}`,n={label:`change-type=${i}`,execute:()=>{const a=this.tracks[e];if(a){const o=a.buffer;o!=null&&o.changeType&&(this.log(`changing ${e} sourceBuffer type to ${i}`),o.changeType(i),a.codec=s,a.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:a=>{this.warn(`Failed to change ${e} SourceBuffer type`,a)}};this.append(n,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const s=e.start,i=s+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(s,G.MAIN))==null?void 0:t.gap)===!0)return;const a={label:"block-audio",execute:()=>{var o;const c=this.tracks.video;(this.lastVideoAppendEnd>i||c!=null&&c.buffer&&j.isBuffered(c.buffer,i)||((o=this.fragmentTracker.getAppendedFrag(i,G.MAIN))==null?void 0:o.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn("Error executing block-audio operation",o)}};this.blockedAudioAppend={op:a,frag:e},this.append(a,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){const{tracks:s}=this,{data:i,type:n,parent:a,frag:o,part:c,chunkMeta:l,offset:u}=t,h=l.buffering[n],{sn:d,cc:g}=o,f=self.performance.now();h.start=f;const p=o.stats.buffering,y=c?c.stats.buffering:null;p.start===0&&(p.start=f),y&&y.start===0&&(y.start=f);const v=s.audio;let E=!1;n==="audio"&&v?.container==="audio/mpeg"&&(E=!this.lastMpegAudioChunk||l.id===1||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const T=s.video,S=T?.buffer;if(S&&d!=="initSegment"){const I=c||o,b=this.blockedAudioAppend;if(n==="audio"&&a!=="main"&&!this.blockedAudioAppend&&!(T.ending||T.ended)){const x=I.start+I.duration*.05,C=S.buffered,M=this.currentOp("video");!C.length&&!M?this.blockAudio(I):!M&&!j.isBuffered(S,x)&&this.lastVideoAppendEnd<x&&this.blockAudio(I)}else if(n==="video"){const A=I.end;if(b){const x=b.frag.start;(A>x||A<this.lastVideoAppendEnd||j.isBuffered(S,x))&&this.unblockAudio()}this.lastVideoAppendEnd=A}}const _=(c||o).start,D={label:`append-${n}`,execute:()=>{var I;h.executeStart=self.performance.now();const b=(I=this.tracks[n])==null?void 0:I.buffer;b&&(E?this.updateTimestampOffset(b,_,.1,n,d,g):u!==void 0&&$(u)&&this.updateTimestampOffset(b,u,1e-6,n,d,g)),this.appendExecutor(i,n)},onStart:()=>{},onComplete:()=>{const I=self.performance.now();h.executeEnd=h.end=I,p.first===0&&(p.first=I),y&&y.first===0&&(y.first=I);const b={};this.sourceBuffers.forEach(([A,x])=>{A&&(b[A]=j.getBuffered(x))}),this.appendErrors[n]=0,n==="audio"||n==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(m.BUFFER_APPENDED,{type:n,frag:o,part:c,chunkMeta:l,parent:o.type,timeRanges:b})},onError:I=>{var b;const A={type:H.MEDIA_ERROR,parent:o.type,details:R.BUFFER_APPEND_ERROR,sourceBufferName:n,frag:o,part:c,chunkMeta:l,error:I,err:I,fatal:!1},x=(b=this.media)==null?void 0:b.error;if(I.code===DOMException.QUOTA_EXCEEDED_ERR||I.name=="QuotaExceededError"||"quota"in I)A.details=R.BUFFER_FULL_ERROR;else if(I.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!x)A.errorAction=Ms(!0);else if(I.name===oc&&this.sourceBufferCount===0)A.errorAction=Ms(!0);else{const C=++this.appendErrors[n];this.warn(`Failed ${C}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${n}" sourceBuffer (${x||"no media error"})`),(C>=this.hls.config.appendErrorMaxRetry||x)&&(A.fatal=!0)}this.hls.trigger(m.ERROR,A)}};this.log(`queuing "${n}" append sn: ${d}${c?" p: "+c.index:""} of ${o.type===G.MAIN?"level":"track"} ${o.level} cc: ${g}`),this.append(D,n,this.isPending(this.tracks[n]))}getFlushOp(e,t,s){return this.log(`queuing "${e}" remove ${t}-${s}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,s)},onStart:()=>{},onComplete:()=>{this.hls.trigger(m.BUFFER_FLUSHED,{type:e})},onError:i=>{this.warn(`Failed to remove ${t}-${s} from "${e}" SourceBuffer`,i)}}}onBufferFlushing(e,t){const{type:s,startOffset:i,endOffset:n}=t;s?this.append(this.getFlushOp(s,i,n),s):this.sourceBuffers.forEach(([a])=>{a&&this.append(this.getFlushOp(a,i,n),a)})}onFragParsed(e,t){const{frag:s,part:i}=t,n=[],a=i?i.elementaryStreams:s.elementaryStreams;a[ce.AUDIOVIDEO]?n.push("audiovideo"):(a[ce.AUDIO]&&n.push("audio"),a[ce.VIDEO]&&n.push("video"));const o=()=>{const c=self.performance.now();s.stats.buffering.end=c,i&&(i.stats.buffering.end=c);const l=i?i.stats:s.stats;this.hls.trigger(m.FRAG_BUFFERED,{frag:s,part:i,stats:l,id:s.type})};n.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${s.type} level: ${s.level} sn: ${s.sn}`),this.blockBuffers(o,n).catch(c=>{this.warn(`Fragment buffered callback ${c}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){const t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var s;this.sourceBuffers.forEach(([a])=>{if(a){const o=this.tracks[a];(!t.type||t.type===a)&&(o.ending=!0,o.ended||(o.ended=!0,this.log(`${a} buffer reached EOS`)))}});const i=((s=this.overrides)==null?void 0:s.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([a])=>{var o;return a&&!((o=this.tracks[a])!=null&&o.ended)})?i?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:a}=this;if(!a||a.readyState!=="open"){a&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${a.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),a.endOfStream(),this.hls.trigger(m.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(m.BUFFERED_TO_END,void 0)):t.type==="video"&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){const t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===R.BUFFER_APPEND_ERROR&&t.frag){var s;const i=(s=t.errorAction)==null?void 0:s.nextAutoLevel;$(i)&&i!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:t,media:s}=this;if(!s||t===null||!this.sourceBufferCount)return;const i=e.config,n=s.currentTime,a=t.levelTargetDuration,o=t.live&&i.liveBackBufferLength!==null?i.liveBackBufferLength:i.backBufferLength;if($(o)&&o>=0){const l=Math.max(o,a),u=Math.floor(n/a)*a-l;this.flushBackBuffer(n,a,u)}const c=i.frontBufferFlushThreshold;if($(c)&&c>0){const l=Math.max(i.maxBufferLength,c),u=Math.max(l,a),h=Math.floor(n/a)*a+u;this.flushFrontBuffer(n,a,h)}}flushBackBuffer(e,t,s){this.sourceBuffers.forEach(([i,n])=>{if(n){const o=j.getBuffered(n);if(o.length>0&&s>o.start(0)){var a;this.hls.trigger(m.BACK_BUFFER_REACHED,{bufferEnd:s});const c=this.tracks[i];if((a=this.details)!=null&&a.live)this.hls.trigger(m.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(c!=null&&c.ended){this.log(`Cannot flush ${i} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:i})}}})}flushFrontBuffer(e,t,s){this.sourceBuffers.forEach(([i,n])=>{if(n){const a=j.getBuffered(n),o=a.length;if(o<2)return;const c=a.start(o-1),l=a.end(o-1);if(s>c||e>=c&&e<=l)return;this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:c,endOffset:1/0,type:i})}})}getDurationAndRange(){var e;const{details:t,mediaSource:s}=this;if(!t||!this.media||s?.readyState!=="open")return null;const i=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&s.setLiveSeekableRange){const l=Math.max(0,t.fragmentStart),u=Math.max(l,i);return{duration:1/0,start:l,end:u}}return{duration:1/0}}const n=(e=this.overrides)==null?void 0:e.duration;if(n)return $(n)?{duration:n}:null;const a=this.media.duration,o=$(s.duration)?s.duration:0;return i>o&&i>a||!$(a)?{duration:i}:null}updateMediaSource({duration:e,start:t,end:s}){const i=this.mediaSource;!this.media||!i||i.readyState!=="open"||(i.duration!==e&&($(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),i.duration=e),t!==void 0&&s!==void 0&&(this.log(`MediaSource duration is set to ${i.duration}. Setting seekable range to ${t}-${s}.`),i.setLiveSeekableRange(t,s)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:s}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${ue(s)}`),this.tracksReady){var i;const n=(i=this.transferData)==null?void 0:i.tracks;n&&Object.keys(n).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([t,s])=>{if(t){const i=this.tracks[t];e[t]={buffer:s,container:i.container,codec:i.codec,supplemental:i.supplemental,levelCodec:i.levelCodec,id:i.id,metadata:i.metadata}}}),this.hls.trigger(m.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:R.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:s}=this;if(!s)throw new Error("createSourceBuffers called when mediaSource was null");for(const n in e){const a=n,o=e[a];if(this.isPending(o)){const c=this.getTrackCodec(o,a),l=`${o.container};codecs=${c}`;o.codec=c,this.log(`creating sourceBuffer(${l})${this.currentOp(a)?" Queued":""} ${ue(o)}`);try{const u=s.addSourceBuffer(l),h=Ln(a),d=[a,u];t[h]=d,o.buffer=u}catch(u){var i;this.error(`error while trying to add sourceBuffer: ${u.message}`),this.shiftAndExecuteNext(a),(i=this.operationQueue)==null||i.removeBlockers(),delete this.tracks[a],this.hls.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:R.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:u,sourceBufferName:a,mimeType:l,parent:o.id});return}this.trackSourceBuffer(a,o)}}this.bufferCreated()}getTrackCodec(e,t){const s=e.supplemental;let i=e.codec;s&&(t==="video"||t==="audiovideo")&&ti(s,"video")&&(i=Id(i,s));const n=Ni(i,e.levelCodec);return n?t.slice(0,5)==="audio"?Fi(n,this.appendSource):n:""}trackSourceBuffer(e,t){const s=t.buffer;if(!s)return;const i=this.getTrackCodec(t,e);this.tracks[e]={buffer:s,codec:i,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(n,a)=>{const o=a.removedRanges;o!=null&&o.length&&this.hls.trigger(m.BUFFER_FLUSHED,{type:n})})}get mediaSrc(){var e,t;const s=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return s?.src}onSBUpdateStart(e){const t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}const s=this.currentOp(e);s&&(s.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var s;const i=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(s=this.mediaSource)==null?void 0:s.readyState}`);this.error(`${i}`,t),this.hls.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:R.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:i,fatal:!1});const n=this.currentOp(e);n&&n.onError(i)}updateTimestampOffset(e,t,s,i,n,a){const o=t-e.timestampOffset;Math.abs(o)>=s&&(this.log(`Updating ${i} SourceBuffer timestampOffset to ${t} (sn: ${n} cc: ${a})`),e.timestampOffset=t)}removeExecutor(e,t,s){const{media:i,mediaSource:n}=this,a=this.tracks[e],o=a?.buffer;if(!i||!n||!o){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}const c=$(i.duration)?i.duration:1/0,l=$(n.duration)?n.duration:1/0,u=Math.max(0,t),h=Math.min(s,c,l);h>u&&(!a.ending||a.ended)?(a.ended=!1,this.log(`Removing [${u},${h}] from the ${e} SourceBuffer`),o.remove(u,h)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const s=this.tracks[t],i=s?.buffer;if(!i)throw new Mg(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);s.ending=!1,s.ended=!1,i.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:s}=this,i=t.map(a=>this.appendBlocker(a));return t.length>1&&this.blockedAudioAppend&&this.unblockAudio(),Promise.all(i).then(a=>{s===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var s;const i=(s=this.tracks[t])==null?void 0:s.buffer;!i||i.updating||this.shiftAndExecuteNext(t)})}append(e,t,s){this.operationQueue&&this.operationQueue.append(e,t,s)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,s){const i=this.tracks[e];if(!i)return;const n=i.buffer;if(!n)return;const a=s.bind(this,e);i.listeners.push({event:t,listener:a}),n.addEventListener(t,a)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const s=t.buffer;s&&(t.listeners.forEach(i=>{s.removeEventListener(i.event,i.listener)}),t.listeners.length=0)}}function lc(r){const e=r.querySelectorAll("source");[].slice.call(e).forEach(t=>{r.removeChild(t)})}function Ng(r,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,r.appendChild(t)}function Ln(r){return r==="audio"?1:0}class Rn{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(m.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(m.BUFFER_CODECS,this.onBufferCodecs,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(m.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(m.BUFFER_CODECS,this.onBufferCodecs,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const s=this.hls.levels[t.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){const s=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,s.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&$(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}const e=this.hls.levels;if(e.length){const t=this.hls,s=this.getMaxLevel(e.length-1);s!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${s}: ${e[s].height}p@${e[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=s,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const s=t.filter((i,n)=>this.isLevelAllowed(i)&&n<=e);return this.clientRect=null,Rn.getMaxLevelByMediaSize(s,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const s=e.getBoundingClientRect();t.width=s.width,t.height=s.height,!t.width&&!t.height&&(t.width=s.right-s.left||e.width||0,t.height=s.bottom-s.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch{}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some(s=>e.bitrate===s.bitrate&&e.width===s.width&&e.height===s.height)}static getMaxLevelByMediaSize(e,t,s){if(!(e!=null&&e.length))return-1;const i=(o,c)=>c?o.width!==c.width||o.height!==c.height:!0;let n=e.length-1;const a=Math.max(t,s);for(let o=0;o<e.length;o+=1){const c=e[o];if((c.width>=a||c.height>=a)&&i(c,e[o+1])){n=o;break}}return n}}const We={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},$g={HLS:"h"};class Lt{constructor(e,t){Array.isArray(e)&&(e=e.map(s=>s instanceof Lt?s:new Lt(s))),this.value=e,this.params=t}}const Bg="Dict";function Ug(r){return Array.isArray(r)?JSON.stringify(r):r instanceof Map?"Map{}":r instanceof Set?"Set{}":typeof r=="object"?JSON.stringify(r):String(r)}function Gg(r,e,t,s){return new Error(`failed to ${r} "${Ug(e)}" as ${t}`,{cause:s})}function Rt(r,e,t){return Gg("serialize",r,e,t)}class cc{constructor(e){this.description=e}}const uc="Bare Item",Kg="Boolean";function Vg(r){if(typeof r!="boolean")throw Rt(r,Kg);return r?"?1":"?0"}function Hg(r){return btoa(String.fromCharCode(...r))}const Wg="Byte Sequence";function Yg(r){if(ArrayBuffer.isView(r)===!1)throw Rt(r,Wg);return`:${Hg(r)}:`}const qg="Integer";function jg(r){return r<-999999999999999||999999999999999<r}function hc(r){if(jg(r))throw Rt(r,qg);return r.toString()}function Xg(r){return`@${hc(r.getTime()/1e3)}`}function dc(r,e){if(r<0)return-dc(-r,e);const t=Math.pow(10,e);if(Math.abs(r*t%1-.5)<Number.EPSILON){const i=Math.floor(r*t);return(i%2===0?i:i+1)/t}else return Math.round(r*t)/t}const zg="Decimal";function Qg(r){const e=dc(r,3);if(Math.floor(Math.abs(e)).toString().length>12)throw Rt(r,zg);const t=e.toString();return t.includes(".")?t:`${t}.0`}const Jg="String",Zg=/[\x00-\x1f\x7f]+/;function em(r){if(Zg.test(r))throw Rt(r,Jg);return`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function tm(r){return r.description||r.toString().slice(7,-1)}const sm="Token";function fc(r){const e=tm(r);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw Rt(e,sm);return e}function bn(r){switch(typeof r){case"number":if(!$(r))throw Rt(r,uc);return Number.isInteger(r)?hc(r):Qg(r);case"string":return em(r);case"symbol":return fc(r);case"boolean":return Vg(r);case"object":if(r instanceof Date)return Xg(r);if(r instanceof Uint8Array)return Yg(r);if(r instanceof cc)return fc(r);default:throw Rt(r,uc)}}const im="Key";function Dn(r){if(/^[a-z*][a-z0-9\-_.*]*$/.test(r)===!1)throw Rt(r,im);return r}function Cn(r){return r==null?"":Object.entries(r).map(([e,t])=>t===!0?`;${Dn(e)}`:`;${Dn(e)}=${bn(t)}`).join("")}function gc(r){return r instanceof Lt?`${bn(r.value)}${Cn(r.params)}`:bn(r)}function rm(r){return`(${r.value.map(gc).join(" ")})${Cn(r.params)}`}function nm(r,e={whitespace:!0}){if(typeof r!="object"||r==null)throw Rt(r,Bg);const t=r instanceof Map?r.entries():Object.entries(r),s=e?.whitespace?" ":"";return Array.from(t).map(([i,n])=>{n instanceof Lt||(n=new Lt(n));let a=Dn(i);return n.value===!0?a+=Cn(n.params):(a+="=",Array.isArray(n.value)?a+=rm(n):a+=gc(n)),a}).join(`,${s}`)}function mc(r,e){return nm(r,e)}const bt="CMCD-Object",Te="CMCD-Request",ms="CMCD-Session",rs="CMCD-Status",am={br:bt,ab:bt,d:bt,ot:bt,tb:bt,tpb:bt,lb:bt,tab:bt,lab:bt,url:bt,pb:Te,bl:Te,tbl:Te,dl:Te,ltc:Te,mtp:Te,nor:Te,nrr:Te,rc:Te,sn:Te,sta:Te,su:Te,ttfb:Te,ttfbb:Te,ttlb:Te,cmsdd:Te,cmsds:Te,smrt:Te,df:Te,cs:Te,ts:Te,cid:ms,pr:ms,sf:ms,sid:ms,st:ms,v:ms,msd:ms,bs:rs,bsd:rs,cdn:rs,rtp:rs,bg:rs,pt:rs,ec:rs,e:rs},om={REQUEST:Te};function lm(r){return Object.keys(r).reduce((e,t)=>{var s;return(s=r[t])===null||s===void 0||s.forEach(i=>e[i]=t),e},{})}function cm(r,e){const t={};if(!r)return t;const s=Object.keys(r),i=e?lm(e):{};return s.reduce((n,a)=>{var o;const c=am[a]||i[a]||om.REQUEST,l=(o=n[c])!==null&&o!==void 0?o:n[c]={};return l[a]=r[a],n},t)}function um(r){return["ot","sf","st","e","sta"].includes(r)}function hm(r){return typeof r=="number"?$(r):r!=null&&r!==""&&r!==!1}const pc="event";function dm(r,e){const t=new URL(r),s=new URL(e);if(t.origin!==s.origin)return r;const i=t.pathname.split("/").slice(1),n=s.pathname.split("/").slice(1,-1);for(;i[0]===n[0];)i.shift(),n.shift();for(;n.length;)n.shift(),i.unshift("..");return i.join("/")+t.search+t.hash}const sr=r=>Math.round(r),Pn=(r,e)=>Array.isArray(r)?r.map(t=>Pn(t,e)):r instanceof Lt&&typeof r.value=="string"?new Lt(Pn(r.value,e),r.params):(e.baseUrl&&(r=dm(r,e.baseUrl)),e.version===1?encodeURIComponent(r):r),ir=r=>sr(r/100)*100,fm={br:sr,d:sr,bl:ir,dl:ir,mtp:ir,nor:(r,e)=>{let t=r;return e.version>=2&&(r instanceof Lt&&typeof r.value=="string"?t=new Lt([r]):typeof r=="string"&&(t=[r])),Pn(t,e)},rtp:ir,tb:sr},yc="request",vc="response",wn=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],gm=["e"],mm=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function rr(r){return mm.test(r)}function pm(r){return wn.includes(r)||gm.includes(r)||rr(r)}const Ec=["d","dl","nor","ot","rtp","su"];function ym(r){return wn.includes(r)||Ec.includes(r)||rr(r)}const vm=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function Em(r){return wn.includes(r)||Ec.includes(r)||vm.includes(r)||rr(r)}const Tm=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function Sm(r){return Tm.includes(r)||rr(r)}const xm={[vc]:Em,[pc]:pm,[yc]:ym};function Tc(r,e={}){const t={};if(r==null||typeof r!="object")return t;const s=e.version||r.v||1,i=e.reportingMode||yc,n=s===1?Sm:xm[i];let a=Object.keys(r).filter(n);const o=e.filter;typeof o=="function"&&(a=a.filter(o));const c=i===vc||i===pc;c&&!a.includes("ts")&&a.push("ts"),s>1&&!a.includes("v")&&a.push("v");const l=le({},fm,e.formatters),u={version:s,reportingMode:i,baseUrl:e.baseUrl};return a.sort().forEach(h=>{let d=r[h];const g=l[h];if(typeof g=="function"&&(d=g(d,u)),h==="v"){if(s===1)return;d=s}h=="pr"&&d===1||(c&&h==="ts"&&!$(d)&&(d=Date.now()),hm(d)&&(um(h)&&typeof d=="string"&&(d=new cc(d)),t[h]=d))}),t}function Am(r,e={}){const t={};if(!r)return t;const s=Tc(r,e),i=cm(s,e?.customHeaderMap);return Object.entries(i).reduce((n,[a,o])=>{const c=mc(o,{whitespace:!1});return c&&(n[a]=c),n},t)}function _m(r,e,t){return le(r,Am(e,t))}const Im="CMCD";function Lm(r,e={}){return r?mc(Tc(r,e),{whitespace:!1}):""}function Rm(r,e={}){if(!r)return"";const t=Lm(r,e);return encodeURIComponent(t)}function bm(r,e={}){if(!r)return"";const t=Rm(r,e);return`${Im}=${t}`}const Sc=/CMCD=[^&#]+/;function Dm(r,e,t){const s=bm(e,t);if(!s)return r;if(Sc.test(r))return r.replace(Sc,s);const i=r.includes("?")?"&":"?";return`${r}${i}${s}`}class Cm{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=i=>{try{this.apply(i,{ot:We.MANIFEST,su:!this.initialized})}catch(n){this.hls.logger.warn("Could not generate manifest CMCD data.",n)}},this.applyFragmentData=i=>{try{const{frag:n,part:a}=i,o=this.hls.levels[n.level],c=this.getObjectType(n),l={d:(a||n).duration*1e3,ot:c};(c===We.VIDEO||c===We.AUDIO||c==We.MUXED)&&(l.br=o.bitrate/1e3,l.tb=this.getTopBandwidth(c)/1e3,l.bl=this.getBufferLength(c));const u=a?this.getNextPart(a):this.getNextFrag(n);u!=null&&u.url&&u.url!==n.url&&(l.nor=u.url),this.apply(i,l)}catch(n){this.hls.logger.warn("Could not generate segment CMCD data.",n)}},this.hls=e;const t=this.config=e.config,{cmcd:s}=t;s!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=s.sessionId||e.sessionId,this.cid=s.contentId,this.useHeaders=s.useHeaders===!0,this.includeKeys=s.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHED,this.onMediaDetached,this),e.on(m.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHED,this.onMediaDetached,this),e.off(m.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var s,i;this.audioBuffer=(s=t.tracks.audio)==null?void 0:s.buffer,this.videoBuffer=(i=t.tracks.video)==null?void 0:i.buffer}createData(){var e;return{v:1,sf:$g.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){le(t,this.createData());const s=t.ot===We.INIT||t.ot===We.VIDEO||t.ot===We.MUXED;this.starved&&s&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);const{includeKeys:i}=this;i&&(t=Object.keys(t).reduce((a,o)=>(i.includes(o)&&(a[o]=t[o]),a),{}));const n={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),_m(e.headers,t,n)):e.url=Dm(e.url,t,n)}getNextFrag(e){var t;const s=(t=this.hls.levels[e.level])==null?void 0:t.details;if(s){const i=e.sn-s.startSN;return s.fragments[i+1]}}getNextPart(e){var t;const{index:s,fragment:i}=e,n=(t=this.hls.levels[i.level])==null||(t=t.details)==null?void 0:t.partList;if(n){const{sn:a}=i;for(let o=n.length-1;o>=0;o--){const c=n[o];if(c.index===s&&c.fragment.sn===a)return n[o+1]}}}getObjectType(e){const{type:t}=e;if(t==="subtitle")return We.TIMED_TEXT;if(e.sn==="initSegment")return We.INIT;if(t==="audio")return We.AUDIO;if(t==="main")return this.hls.audioTracks.length?We.VIDEO:We.MUXED}getTopBandwidth(e){let t=0,s;const i=this.hls;if(e===We.AUDIO)s=i.audioTracks;else{const n=i.maxAutoLevel,a=n>-1?n+1:i.levels.length;s=i.levels.slice(0,a)}return s.forEach(n=>{n.bitrate>t&&(t=n.bitrate)}),t>0?t:NaN}getBufferLength(e){const t=this.media,s=e===We.AUDIO?this.audioBuffer:this.videoBuffer;return!s||!t?NaN:j.bufferInfo(s,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,s=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new s(n)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(n,a,o){t(n),this.loader.load(n,a,o)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,s=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new s(n)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(n,a,o){t(n),this.loader.load(n,a,o)}}}}const Pm=3e5;class wm extends rt{constructor(e){super("content-steering",e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(e.indexOf(t.pathwayId)===-1&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter(s=>s!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:s}=t;s!==null&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:s}=t;if(s?.action===ke.SendAlternateToPenaltyBox&&s.flags===Xe.MoveAllAlternatesMatchingHost){const i=this.levels;let n=this._pathwayPriority,a=this.pathwayId;if(t.context){const{groupId:o,pathwayId:c,type:l}=t.context;o&&i?a=this.getPathwayForGroupId(o,l,a):c&&(a=c)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!n&&i&&(n=this.pathways()),n&&n.length>1&&(this.updatePathwayPriority(n),s.resolved=this.pathwayId!==a),t.details===R.BUFFER_APPEND_ERROR&&!t.fatal?s.resolved=!0:s.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${a} levels: ${i&&i.length} priorities: ${ue(n)} penalized: ${ue(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){const s=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),t=this.getLevelsForPathway(s),this.pathwayId=s}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let t;const s=this.penalizedPathways,i=performance.now();Object.keys(s).forEach(n=>{i-s[n]>Pm&&delete s[n]});for(let n=0;n<e.length;n++){const a=e[n];if(a in s)continue;if(a===this.pathwayId)return;const o=this.hls.nextLoadLevel,c=this.hls.levels[o];if(t=this.getLevelsForPathway(a),t.length>0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,Il(t),this.hls.trigger(m.LEVELS_UPDATED,{levels:t});const l=this.hls.levels[o];c&&l&&this.levels&&(l.attrs["STABLE-VARIANT-ID"]!==c.attrs["STABLE-VARIANT-ID"]&&l.bitrate!==c.bitrate&&this.log(`Unstable Pathways change from bitrate ${c.bitrate} to ${l.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,s){const i=this.getLevelsForPathway(s).concat(this.levels||[]);for(let n=0;n<i.length;n++)if(t===ee.AUDIO_TRACK&&i[n].hasAudioGroup(e)||t===ee.SUBTITLE_TRACK&&i[n].hasSubtitleGroup(e))return i[n].pathwayId;return s}clonePathways(e){const t=this.levels;if(!t)return;const s={},i={};e.forEach(n=>{const{ID:a,"BASE-ID":o,"URI-REPLACEMENT":c}=n;if(t.some(u=>u.pathwayId===a))return;const l=this.getLevelsForPathway(o).map(u=>{const h=new pe(u.attrs);h["PATHWAY-ID"]=a;const d=h.AUDIO&&`${h.AUDIO}_clone_${a}`,g=h.SUBTITLES&&`${h.SUBTITLES}_clone_${a}`;d&&(s[h.AUDIO]=d,h.AUDIO=d),g&&(i[h.SUBTITLES]=g,h.SUBTITLES=g);const f=Ac(u.uri,h["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",c),p=new ii({attrs:h,audioCodec:u.audioCodec,bitrate:u.bitrate,height:u.height,name:u.name,url:f,videoCodec:u.videoCodec,width:u.width});if(u.audioGroups)for(let y=1;y<u.audioGroups.length;y++)p.addGroupId("audio",`${u.audioGroups[y]}_clone_${a}`);if(u.subtitleGroups)for(let y=1;y<u.subtitleGroups.length;y++)p.addGroupId("text",`${u.subtitleGroups[y]}_clone_${a}`);return p});t.push(...l),xc(this.audioTracks,s,c,a),xc(this.subtitleTracks,i,c,a)})}loadSteeringManifest(e){const t=this.hls.config,s=t.loader;this.loader&&this.loader.destroy(),this.loader=new s(t);let i;try{i=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(i.protocol!=="data:"){const u=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;i.searchParams.set("_HLS_pathway",this.pathwayId),i.searchParams.set("_HLS_throughput",""+u)}const n={responseType:"json",url:i.href},a=t.steeringManifestLoadPolicy.default,o=a.errorRetry||a.timeoutRetry||{},c={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},l={onSuccess:(u,h,d,g)=>{this.log(`Loaded steering manifest: "${i}"`);const f=u.data;if(f?.VERSION!==1){this.log(`Steering VERSION ${f.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=f.TTL;const{"RELOAD-URI":p,"PATHWAY-CLONES":y,"PATHWAY-PRIORITY":v}=f;if(p)try{this.uri=new self.URL(p,i).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${p}`);return}this.scheduleRefresh(this.uri||d.url),y&&this.clonePathways(y);const E={steeringManifest:f,url:i.toString()};this.hls.trigger(m.STEERING_MANIFEST_LOADED,E),v&&this.updatePathwayPriority(v)},onError:(u,h,d,g)=>{if(this.log(`Error loading steering manifest: ${u.code} ${u.text} (${h.url})`),this.stopLoad(),u.code===410){this.enabled=!1,this.log(`Steering manifest ${h.url} no longer available`);return}let f=this.timeToLoad*1e3;if(u.code===429){const p=this.loader;if(typeof p?.getResponseHeader=="function"){const y=p.getResponseHeader("Retry-After");y&&(f=parseFloat(y)*1e3)}this.log(`Steering manifest ${h.url} rate limited`);return}this.scheduleRefresh(this.uri||h.url,f)},onTimeout:(u,h,d)=>{this.log(`Timeout loading steering manifest (${h.url})`),this.scheduleRefresh(this.uri||h.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(n,c,l)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var s;const i=(s=this.hls)==null?void 0:s.media;if(i&&!i.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}}function xc(r,e,t,s){r&&Object.keys(e).forEach(i=>{const n=r.filter(a=>a.groupId===i).map(a=>{const o=le({},a);return o.details=void 0,o.attrs=new pe(o.attrs),o.url=o.attrs.URI=Ac(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[i],o.attrs["PATHWAY-ID"]=s,o});r.push(...n)})}function Ac(r,e,t,s){const{HOST:i,PARAMS:n,[t]:a}=s;let o;e&&(o=a?.[e],o&&(r=o));const c=new self.URL(r);return i&&!o&&(c.host=i),n&&Object.keys(n).sort().forEach(l=>{l&&c.searchParams.set(l,n[l])}),c.href}class Ks extends rt{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=Ks.CDMCleanupPromise?[Ks.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=t=>{const{initDataType:s,initData:i}=t,n=`"${t.type}" event: init data type: "${s}"`;if(this.debug(n),i!==null){if(!this.keyFormatPromise){let a=Object.keys(this.keySystemAccessPromises);a.length||(a=ri(this.config));const o=a.map(rn).filter(c=>!!c);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(a=>{const o=qi(a);if(s!=="sinf"||o!==ye.FAIRPLAY){this.log(`Ignoring "${t.type}" event with init data type: "${s}" for selected key-system ${o}`);return}let c;try{const g=Le(new Uint8Array(i)),f=tn(JSON.parse(g).sinf),p=So(f);if(!p)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");c=new Uint8Array(p.subarray(8,24))}catch(g){this.warn(`${n} Failed to parse sinf: ${g}`);return}const l=we(c),{keyIdToKeySessionPromise:u,mediaKeySessions:h}=this;let d=u[l];for(let g=0;g<h.length;g++){const f=h[g],p=f.decryptdata;if(!p.keyId)continue;const y=we(p.keyId);if(Wi(c,p.keyId)||p.uri.replace(/-/g,"").indexOf(l)!==-1){if(d=u[y],!d)continue;if(p.pssh)break;delete u[y],p.pssh=new Uint8Array(i),p.keyId=c,d=u[l]=d.then(()=>this.generateRequestWithPreferredKeySession(f,s,i,"encrypted-event-key-match")),d.catch(v=>this.handleError(v));break}}d||this.handleError(new Error(`Key ID ${l} not encountered in playlist. Key-system sessions ${h.length}.`))}).catch(a=>this.handleError(a))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(m.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(m.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(m.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(m.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(m.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(m.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:s}=this.config,i=t?.[e];if(i)return i.licenseUrl;if(e===ye.WIDEVINE&&s)return s}getLicenseServerUrlOrThrow(e){const t=this.getLicenseServerUrl(e);if(t===void 0)throw new Error(`no license server URL configured for key-system "${e}"`);return t}getServerCertificateUrl(e){const{drmSystems:t}=this.config,s=t?.[e];if(s)return s.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,s=(a,o,c)=>!!a&&c.indexOf(a)===o,i=t.map(a=>a.audioCodec).filter(s),n=t.map(a=>a.videoCodec).filter(s);return i.length+n.length===0&&n.push("avc1.42e01e"),new Promise((a,o)=>{const c=l=>{const u=l.shift();this.getMediaKeysPromise(u,i,n).then(h=>a({keySystem:u,mediaKeys:h})).catch(h=>{l.length?c(l):h instanceof Je?o(h):o(new Je({type:H.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_ACCESS,error:h,fatal:!0},h.message))})};c(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:s}=this.config;if(typeof s!="function"){let i=`Configured requestMediaKeySystemAccess is not a function ${s}`;return nl===null&&self.location.protocol==="http:"&&(i=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(i))}return s(e,t)}getMediaKeysPromise(e,t,s){var i;const n=mf(e,t,s,this.config.drmSystemOptions||{});let a=this.keySystemAccessPromises[e],o=(i=a)==null?void 0:i.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${e}" key-system access with config: ${ue(n)}`),o=this.requestMediaKeySystemAccess(e,n);const c=a=this.keySystemAccessPromises[e]={keySystemAccess:o};return o.catch(l=>{this.log(`Failed to obtain access to key-system "${e}": ${l}`)}),o.then(l=>{this.log(`Access for key-system "${l.keySystem}" obtained`);const u=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);const h=c.mediaKeys=l.createMediaKeys().then(d=>(this.log(`Media-keys created for "${e}"`),c.hasMediaKeys=!0,u.then(g=>g?this.setMediaKeysServerCertificate(d,e,g):d)));return h.catch(d=>{this.error(`Failed to create media-keys for "${e}"}: ${d}`)}),h})}return o.then(()=>a.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:s}){this.log(`Creating key-system session "${t}" keyId: ${we(e.keyId||[])} keyUri: ${e.uri}`);const i=s.createSession(),n={decryptdata:e,keySystem:t,mediaKeys:s,mediaKeysSession:i,keyStatus:"status-pending"};return this.mediaKeySessions.push(n),n}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const s=this.createMediaKeySessionContext(e),i=nr(t),n="cenc";this.keyIdToKeySessionPromise[i]=this.generateRequestWithPreferredKeySession(s,n,t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}updateKeySession(e,t){const s=e.mediaKeysSession;return this.log(`Updating key-session "${s.sessionId}" for keyId ${we(e.decryptdata.keyId||[])}
29
- } (data length: ${t.byteLength})`),s.update(t)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>rn(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t,mediaKeys:s})=>this.attemptSetMediaKeys(t,s))}selectKeySystem(e){return new Promise((t,s)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:i})=>{const n=rn(i);n?t(n):s(new Error(`Unable to find format for key-system "${i}"`))}).catch(s)})}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){const t=ri(this.config),s=e.map(qi).filter(i=>!!i&&t.indexOf(i)!==-1);return this.selectKeySystem(s)}getKeyStatus(e){const{mediaKeySessions:t}=this;for(let s=0;s<t.length;s++){const i=km(e,t[s]);if(i)return i}}loadKey(e){const t=e.keyInfo.decryptdata,s=nr(t),i=this.bannedKeyIds[s];if(i||this.getKeyStatus(t)==="internal-error"){const o=_c(i||"internal-error",t);return this.handleError(o,e.frag),Promise.reject(o)}const n=`(keyId: ${s} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${n}`);const a=this.keyIdToKeySessionPromise[s];if(!a){const o=this.getKeySystemForKeyPromise(t).then(({keySystem:c,mediaKeys:l})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${n}`),this.attemptSetMediaKeys(c,l).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:c,mediaKeys:l,decryptdata:t}))))).then(c=>{const l="cenc",u=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(c,l,u,"playlist-key")});return o.catch(c=>this.handleError(c,e.frag)),this.keyIdToKeySessionPromise[s]=o,o}return a.catch(o=>{if(o instanceof Je){const c=ae({},o.data);this.getKeyStatus(t)==="internal-error"&&(c.decryptdata=t);const l=new Je(c,o.message);this.handleError(l,e.frag)}}),a}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof Je){t&&(e.data.frag=t);const s=e.data.decryptdata;this.error(`${e.message}${s?` (${we(s.keyId||[])})`:""}`),this.hls.trigger(m.ERROR,e.data)}else this.error(e.message),this.hls.trigger(m.ERROR,{type:H.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){const t=nr(e),s=this.keyIdToKeySessionPromise[t];if(!s){const i=qi(e.keyFormat),n=i?[i]:ri(this.config);return this.attemptKeySystemAccess(n)}return s}getKeySystemSelectionPromise(e){if(e.length||(e=ri(this.config)),e.length===0)throw new Je({type:H.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${ue({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const i=Promise.all(s).then(()=>this.media?this.media.setMediaKeys(t):new Promise((n,a)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return a(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(n).catch(a)}}));return this.mediaKeys=t,this.setMediaKeysQueue.push(i),i.then(()=>{this.log(`Media-keys set for "${e}"`),s.push(i),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(n=>s.indexOf(n)===-1)})}generateRequestWithPreferredKeySession(e,t,s,i){var n;const a=(n=this.config.drmSystems)==null||(n=n[e.keySystem])==null?void 0:n.generateRequest;if(a)try{const f=a.call(this.hls,t,s,e);if(!f)throw new Error("Invalid response from configured generateRequest filter");t=f.initDataType,s=f.initData?f.initData:null,e.decryptdata.pssh=s?new Uint8Array(s):null}catch(f){if(this.warn(f.message),this.hls&&this.hls.config.debug)throw f}if(s===null)return this.log(`Skipping key-session request for "${i}" (no initData)`),Promise.resolve(e);const o=nr(e.decryptdata),c=e.decryptdata.uri;this.log(`Generating key-session request for "${i}" keyId: ${o} URI: ${c} (init data type: ${t} length: ${s.byteLength})`);const l=new hn,u=e._onmessage=f=>{const p=e.mediaKeysSession;if(!p){l.emit("error",new Error("invalid state"));return}const{messageType:y,message:v}=f;this.log(`"${y}" message event for session "${p.sessionId}" message size: ${v.byteLength}`),y==="license-request"||y==="license-renewal"?this.renewLicense(e,v).catch(E=>{l.eventNames().length?l.emit("error",E):this.handleError(E)}):y==="license-release"?e.keySystem===ye.FAIRPLAY&&this.updateKeySession(e,sn("acknowledged")).then(()=>this.removeSession(e)).catch(E=>this.handleError(E)):this.warn(`unhandled media key message type "${y}"`)},h=(f,p)=>{p.keyStatus=f;let y;f.startsWith("usable")?l.emit("resolved"):f==="internal-error"||f==="output-restricted"||f==="output-downscaled"?y=_c(f,p.decryptdata):f==="expired"?y=new Error(`key expired (keyId: ${o})`):f==="released"?y=new Error("key released"):f==="status-pending"||this.warn(`unhandled key status change "${f}" (keyId: ${o})`),y&&(l.eventNames().length?l.emit("error",y):this.handleError(y))},d=e._onkeystatuseschange=f=>{if(!e.mediaKeysSession){l.emit("error",new Error("invalid state"));return}const y=this.getKeyStatuses(e);if(!Object.keys(y).some(S=>y[S]!=="status-pending"))return;if(y[o]==="expired"){this.log(`Expired key ${ue(y)} in key-session "${e.mediaKeysSession.sessionId}"`),this.renewKeySession(e);return}let E=y[o];if(E)h(E,e);else{var T;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(T=e.keyStatusTimeouts)[o]||(T[o]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;const _=this.getKeyStatus(e.decryptdata);if(_&&_!=="status-pending")return this.log(`No status for keyId ${o} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${_} from other session.`),h(_,e);this.log(`key status for ${o} in key-session "${e.mediaKeysSession.sessionId}" timed out after 1000ms`),E="internal-error",h(E,e)},1e3)),this.log(`No status for keyId ${o} (${ue(y)}).`)}};Ue(e.mediaKeysSession,"message",u),Ue(e.mediaKeysSession,"keystatuseschange",d);const g=new Promise((f,p)=>{l.on("error",p),l.on("resolved",f)});return e.mediaKeysSession.generateRequest(t,s).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${o} URI: ${c}`)}).catch(f=>{throw new Je({type:H.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_SESSION,error:f,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${f}`)}).then(()=>g).catch(f=>(l.removeAllListeners(),this.removeSession(e).then(()=>{throw f}))).then(()=>(l.removeAllListeners(),e))}getKeyStatuses(e){const t={};return e.mediaKeysSession.keyStatuses.forEach((s,i)=>{if(typeof i=="string"&&typeof s=="object"){const o=i;i=s,s=o}const n="buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i);if(e.keySystem===ye.PLAYREADY&&n.length===16){const o=we(n);t[o]=s,il(n)}const a=we(n);s==="internal-error"&&(this.bannedKeyIds[a]=s),this.log(`key status change "${s}" for keyStatuses keyId: ${a} key-session "${e.mediaKeysSession.sessionId}"`),t[a]=s}),t}fetchServerCertificate(e){const t=this.config,s=t.loader,i=new s(t),n=this.getServerCertificateUrl(e);return n?(this.log(`Fetching server certificate for "${e}"`),new Promise((a,o)=>{const c={responseType:"arraybuffer",url:n},l=t.certLoadPolicy.default,u={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(d,g,f,p)=>{a(d.data)},onError:(d,g,f,p)=>{o(new Je({type:H.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:f,response:ae({url:c.url,data:void 0},d)},`"${e}" certificate request failed (${n}). Status: ${d.code} (${d.text})`))},onTimeout:(d,g,f)=>{o(new Je({type:H.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:f,response:{url:c.url,data:void 0}},`"${e}" certificate request timed out (${n})`))},onAbort:(d,g,f)=>{o(new Error("aborted"))}};i.load(c,u,h)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,s){return new Promise((i,n)=>{e.setServerCertificate(s).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${s.byteLength}) on "${t}"`),i(e)}).catch(a=>{n(new Je({type:H.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(s=>this.updateKeySession(e,new Uint8Array(s)).catch(i=>{throw new Je({type:H.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:i,fatal:!1},i.message)}))}unpackPlayReadyKeyMessage(e,t){const s=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!s.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const i=new DOMParser().parseFromString(s,"application/xml"),n=i.querySelectorAll("HttpHeader");if(n.length>0){let u;for(let h=0,d=n.length;h<d;h++){var a,o;u=n[h];const g=(a=u.querySelector("name"))==null?void 0:a.textContent,f=(o=u.querySelector("value"))==null?void 0:o.textContent;g&&f&&e.setRequestHeader(g,f)}}const c=i.querySelector("Challenge"),l=c?.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return sn(atob(l))}setupLicenseXHR(e,t,s,i){const n=this.config.licenseXhrSetup;return n?Promise.resolve().then(()=>{if(!s.decryptdata)throw new Error("Key removed");return n.call(this.hls,e,t,s,i)}).catch(a=>{if(!s.decryptdata)throw a;return e.open("POST",t,!0),n.call(this.hls,e,t,s,i)}).then(a=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:a||i})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:i}))}requestLicense(e,t){const s=this.config.keyLoadPolicy.default;return new Promise((i,n)=>{const a=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${a}`);const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return n(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let c=o.response;this.log(`License received ${c instanceof ArrayBuffer?c.byteLength:c}`);const l=this.config.licenseResponseCallback;if(l)try{c=l.call(this.hls,o,a,e)}catch(u){this.error(u)}i(c)}else{const c=s.errorRetry,l=c?c.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||o.status>=400&&o.status<500)n(new Je({type:H.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:o,response:{url:a,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${a}). Status: ${o.status} (${o.statusText})`));else{const u=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${u} attempts left`),this.requestLicense(e,t).then(i,n)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,a,e,t).then(({xhr:c,licenseChallenge:l})=>{e.keySystem==ye.PLAYREADY&&(l=this.unpackPlayReadyKeyMessage(c,l)),c.send(l)}).catch(n)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const s=t.media;this.media=s,Ue(s,"encrypted",this.onMediaEncrypted),Ue(s,"waitingforkey",this.onWaitingForKey);const i=this.mediaResolved;i?i():this.mediaKeys=s.mediaKeys}onMediaDetached(){const e=this.media;e&&(He(e,"encrypted",this.onMediaEncrypted),He(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};const t=this.mediaResolved;if(t&&t(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const s=this.media,i=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,ts.clearKeyUriToKeyIdMap();const n=i.length;Ks.CDMCleanupPromise=Promise.all(i.map(a=>this.removeSession(a)).concat((s==null||(e=s.setMediaKeys(null))==null?void 0:e.catch(a=>{this.log(`Could not clear media keys: ${a}`),this.hls&&this.hls.trigger(m.ERROR,{type:H.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${a}`)})}))||Promise.resolve())).catch(a=>{this.log(`Could not close sessions and clear media keys: ${a}`),this.hls&&this.hls.trigger(m.ERROR,{type:H.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${a}`)})}).then(()=>{n&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){const s=t.reduce((i,n)=>(i.indexOf(n.keyFormat)===-1&&i.push(n.keyFormat),i),[]);this.log(`Selecting key-system from session-keys ${s.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(s)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:s,decryptdata:i}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${we(i?.keyId||[])}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),s&&s.readyState!==XMLHttpRequest.DONE&&s.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const n=this.mediaKeySessions.indexOf(e);n>-1&&this.mediaKeySessions.splice(n,1);const{keyStatusTimeouts:a}=e;a&&Object.keys(a).forEach(l=>self.clearTimeout(a[l]));const{drmSystemOptions:o}=this.config;return(yf(o)?new Promise((l,u)=>{self.setTimeout(()=>u(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(l).catch(u)}):Promise.resolve()).catch(l=>{this.log(`Could not remove session: ${l}`),this.hls&&this.hls.trigger(m.ERROR,{type:H.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${l}`)})}).then(()=>t.close()).catch(l=>{this.log(`Could not close session: ${l}`),this.hls&&this.hls.trigger(m.ERROR,{type:H.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${l}`)})})}return Promise.resolve()}}Ks.CDMCleanupPromise=void 0;function nr(r){if(!r)throw new Error("Could not read keyId of undefined decryptdata");if(r.keyId===null)throw new Error("keyId is null");return we(r.keyId)}function km(r,e){if(r.keyId&&e.mediaKeysSession.keyStatuses.has(r.keyId))return e.mediaKeysSession.keyStatuses.get(r.keyId);if(r.matches(e.decryptdata))return e.keyStatus}class Je extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}function _c(r,e){const t=r==="output-restricted",s=t?R.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:R.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Je({type:H.KEY_SYSTEM_ERROR,details:s,fatal:!1,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${r}"`)}class Om{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(m.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(m.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const s=this.hls.config;if(s.capLevelOnFPSDrop){const i=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=i,i&&typeof i.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),s.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,s){const i=performance.now();if(t){if(this.lastTime){const n=i-this.lastTime,a=s-this.lastDroppedFrames,o=t-this.lastDecodedFrames,c=1e3*a/n,l=this.hls;if(l.trigger(m.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:s}),c>0&&a>l.config.fpsDroppedMonitoringThreshold*o){let u=l.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+u),u>0&&(l.autoLevelCapping===-1||l.autoLevelCapping>=u)&&(u=u-1,l.trigger(m.FPS_DROP_LEVEL_CAPPING,{level:u,droppedLevel:l.currentLevel}),l.autoLevelCapping=u,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=s,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}function Ic(r,e){let t;try{t=new Event("addtrack")}catch{t=document.createEvent("Event"),t.initEvent("addtrack",!1,!1)}t.track=r,e.dispatchEvent(t)}function Lc(r,e){const t=r.mode;if(t==="disabled"&&(r.mode="hidden"),r.cues&&!r.cues.getCueById(e.id))try{if(r.addCue(e),!r.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(s){oe.debug(`[texttrack-utils]: ${s}`);try{const i=new self.TextTrackCue(e.startTime,e.endTime,e.text);i.id=e.id,r.addCue(i)}catch(i){oe.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${i}`)}}t==="disabled"&&(r.mode=t)}function Vs(r,e){const t=r.mode;if(t==="disabled"&&(r.mode="hidden"),r.cues)for(let s=r.cues.length;s--;)e&&r.cues[s].removeEventListener("enter",e),r.removeCue(r.cues[s]);t==="disabled"&&(r.mode=t)}function kn(r,e,t,s){const i=r.mode;if(i==="disabled"&&(r.mode="hidden"),r.cues&&r.cues.length>0){const n=Fm(r.cues,e,t);for(let a=0;a<n.length;a++)(!s||s(n[a]))&&r.removeCue(n[a])}i==="disabled"&&(r.mode=i)}function Mm(r,e){if(e<=r[0].startTime)return 0;const t=r.length-1;if(e>r[t].endTime)return-1;let s=0,i=t,n;for(;s<=i;)if(n=Math.floor((i+s)/2),e<r[n].startTime)i=n-1;else if(e>r[n].startTime&&s<t)s=n+1;else return n;return r[s].startTime-e<e-r[i].startTime?s:i}function Fm(r,e,t){const s=[],i=Mm(r,e);if(i>-1)for(let n=i,a=r.length;n<a;n++){const o=r[n];if(o.startTime>=e&&o.endTime<=t)s.push(o);else if(o.startTime>t)return s}return s}function ar(r){const e=[];for(let t=0;t<r.length;t++){const s=r[t];(s.kind==="subtitles"||s.kind==="captions")&&s.label&&e.push(r[t])}return e}class Nm extends _n{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const s=ar(this.media.textTracks);for(let n=0;n<s.length;n++)if(s[n].mode==="hidden")t=s[n];else if(s[n].mode==="showing"){t=s[n];break}const i=this.findTrackForTextTrack(t);this.subtitleTrack!==i&&this.setSubtitleTrack(i)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.LEVEL_LOADING,this.onLevelLoading,this),e.on(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.LEVEL_LOADING,this.onLevelLoading,this),e.off(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(m.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){const s=this.media;if(!s)return;const i=!!t.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||s.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,i)return;ar(s.textTracks).forEach(a=>{Vs(a)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:s,groupId:i,details:n}=t,a=this.tracksInGroup[s];if(!a||a.groupId!==i){this.warn(`Subtitle track with id:${s} and group:${i} not found in active group ${a?.groupId}`);return}const o=a.details;a.details=t.details,this.log(`Subtitle track ${s} "${a.name}" lang:${a.lang} group:${i} loaded [${n.startSN}-${n.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const s=t.subtitleGroups||null,i=this.groupIds;let n=this.currentTrack;if(!s||i?.length!==s?.length||s!=null&&s.some(a=>i?.indexOf(a)===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const a=this.tracks.filter(u=>!s||s.indexOf(u.groupId)!==-1);if(a.length)this.selectDefaultTrack&&!a.some(u=>u.default)&&(this.selectDefaultTrack=!1),a.forEach((u,h)=>{u.id=h});else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=a;const o=this.hls.config.subtitlePreference;if(!n&&o){this.selectDefaultTrack=!1;const u=At(o,a);if(u>-1)n=a[u];else{const h=At(o,this.tracks);n=this.tracks[h]}}let c=this.findTrackId(n);c===-1&&n&&(c=this.findTrackId(null));const l={subtitleTracks:a};this.log(`Updating subtitle tracks, ${a.length} track(s) found in "${s?.join(",")}" group-id`),this.hls.trigger(m.SUBTITLE_TRACKS_UPDATED,l),c!==-1&&this.trackId===-1&&this.setSubtitleTrack(c)}}findTrackId(e){const t=this.tracksInGroup,s=this.selectDefaultTrack;for(let i=0;i<t.length;i++){const n=t[i];if(!(s&&!n.default||!s&&!e)&&(!e||ds(n,e)))return i}if(e){for(let i=0;i<t.length;i++){const n=t[i];if(hi(e.attrs,n.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<t.length;i++){const n=t[i];if(hi(e.attrs,n.attrs,["LANGUAGE"]))return i}}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){const i=t[s];if(In(i,e))return s}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===ee.SUBTITLE_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(e.id===-1)return this.setSubtitleTrack(-1),null;const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const s=this.currentTrack;if(s&&ds(e,s))return s;const i=At(e,this.tracksInGroup);if(i>-1){const n=this.tracksInGroup[i];return this.setSubtitleTrack(i),n}else{if(s)return null;{const n=At(e,t);if(n>-1)return t[n]}}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=e.id,i=e.groupId,n=this.getUrlWithDirectives(e.url,t),a=e.details,o=a?.age;this.log(`Loading subtitle ${s} "${e.name}" lang:${e.lang} group:${i}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${n}`),this.hls.trigger(m.SUBTITLE_TRACK_LOADING,{url:n,id:s,groupId:i,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=ar(e.textTracks),s=this.currentTrack;let i;if(s&&(i=t.filter(n=>In(s,n))[0],i||this.warn(`Unable to find subtitle TextTrack with name "${s.name}" and language "${s.lang}"`)),[].slice.call(t).forEach(n=>{n.mode!=="disabled"&&n!==i&&(n.mode="disabled")}),i){const n=this.subtitleDisplay?"showing":"hidden";i.mode!==n&&(i.mode=n)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!$(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.selectDefaultTrack=!1;const s=this.currentTrack,i=t[e]||null;if(this.trackId=e,this.currentTrack=i,this.toggleTrackModes(),!i){this.hls.trigger(m.SUBTITLE_TRACK_SWITCH,{id:e});return}const n=!!i.details&&!i.details.live;if(e===this.trackId&&i===s&&n)return;this.log(`Switching to subtitle-track ${e}`+(i?` "${i.name}" lang:${i.lang} group:${i.groupId}`:""));const{id:a,groupId:o="",name:c,type:l,url:u}=i;this.hls.trigger(m.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:c,type:l,url:u});const h=this.switchParams(i.url,s?.details,i.details);this.loadPlaylist(h)}}function $m(){try{return crypto.randomUUID()}catch{try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch{let t=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{const n=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(i=="x"?n:n&3|8).toString(16)})}}}function di(r){let e=5381,t=r.length;for(;t;)e=e*33^r.charCodeAt(--t);return(e>>>0).toString()}const Hs=.025;let or=(function(r){return r[r.Point=0]="Point",r[r.Range=1]="Range",r})({});function Bm(r,e,t){return`${r.identifier}-${t+1}-${di(e)}`}class Um{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,(e=this.assetListLoader)==null||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return!0;const s=this.playoutLimit;return e<=0||isNaN(s)?!1:s===0?!0:(((t=this.assetList[e])==null?void 0:t.startOffset)||0)>s}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const e=this.dateRange.startTime;if(this.snapOptions.out){const t=this.dateRange.tagAnchor;if(t)return On(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;const e=this.dateRange.tagAnchor;if(e){const t=this.dateRange.startTime,s=On(t,e);return t-s<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=$(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){const e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const t=this.resumeAnchor;if(t)return On(e,t)}return e}get appendInPlace(){return this.appendInPlaceStarted?!0:this.appendInPlaceDisabled?!1:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<Hs))}set appendInPlace(e){if(this.appendInPlaceStarted){this.resetOnResume=!e;return}this.appendInPlaceDisabled=!e}get timelineStart(){return this._timelineStart!==null?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){const e=this.playoutLimit;let t;return this._duration!==null?t=this._duration:this.dateRange.duration?t=this.dateRange.duration:t=this.dateRange.plannedDuration||0,!isNaN(e)&&e<t&&(t=e),t}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return this.dateRange.attr["X-TIMELINE-OCCUPIES"]==="RANGE"?or.Range:or.Point}get supplementsPrimary(){return this.dateRange.attr["X-TIMELINE-STYLE"]==="PRIMARY"}get contentMayVary(){return this.dateRange.attr["X-CONTENT-MAY-VARY"]!=="NO"}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||this.assetListResponse!==null}toString(){return Gm(this)}}function On(r,e){return r-e.start<e.duration/2&&!(Math.abs(r-(e.start+e.duration))<Hs)?e.start:e.start+e.duration}function Rc(r,e,t){const s=new self.URL(r,t);return s.protocol!=="data:"&&s.searchParams.set("_HLS_primary_id",e),s}function Mn(r,e){for(;(t=r.assetList[++e])!=null&&t.error;)var t;return e}function Gm(r){return`["${r.identifier}" ${r.cue.pre?"<pre>":r.cue.post?"<post>":""}${r.timelineStart.toFixed(2)}-${r.resumeTime.toFixed(2)}]`}function Ws(r){const e=r.timelineStart,t=r.duration||0;return`["${r.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}class Km{constructor(e,t,s,i){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(m.PLAYOUT_LIMIT_REACHED,{})};const n=this.hls=new e(t);this.interstitial=s,this.assetItem=i;const a=()=>{this.hasDetails=!0};n.once(m.LEVEL_LOADED,a),n.once(m.AUDIO_TRACK_LOADED,a),n.once(m.SUBTITLE_TRACK_LOADED,a),n.on(m.MEDIA_ATTACHING,(o,{media:c})=>{this.removeMediaListeners(),this.mediaAttached=c,this.interstitial.playoutLimit&&(c.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&n.on(m.BUFFER_APPENDED,()=>{const u=this.bufferedEnd;this.reachedPlayout(u)&&(this._bufferedEosTime=u,n.trigger(m.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let t=this.assetItem.uri;try{t=Rc(t,e.config.primarySessionId||"").href}catch{}e.loadSource(t)}}bufferedInPlaceToEnd(e){var t;if(!this.appendInPlace)return!1;if((t=this.hls)!=null&&t.bufferedToEnd)return!0;if(!e)return!1;const s=Math.min(this._bufferedEosTime||1/0,this.duration),i=this.timelineOffset,n=j.bufferInfo(e,i,0);return this.getAssetTime(n.end)>=s-.02}reachedPlayout(e){const s=this.interstitial.playoutLimit;return this.startOffset+e>=s}get destroyed(){var e;return!((e=this.hls)!=null&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return((e=this.hls)==null?void 0:e.media)||null}get bufferedEnd(){const e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const t=j.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){const e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){const e=this.assetItem.duration;if(!e)return 0;const t=this.interstitial.playoutLimit;if(t){const s=t-this.startOffset;if(s>0&&s<e)return s}return e}get remaining(){const e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return((e=this.hls)==null?void 0:e.config.timelineOffset)||0}set timelineOffset(e){const t=this.timelineOffset;if(e!==t){const s=e-t;if(Math.abs(s)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){const t=this.timelineOffset,s=this.duration;return Math.min(Math.max(0,e-t),s)}removeMediaListeners(){const e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var e;(e=this.hls)!=null&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),(t=this.hls)==null||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,(e=this.hls)==null||e.detachMedia()}resumeBuffering(){var e;(e=this.hls)==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.hls)==null||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),((e=this.hls)==null?void 0:e.transferMedia())||null}resetDetails(){const e=this.hls;if(e&&this.hasDetails){e.stopLoad();const t=s=>delete s.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,s){var i;(i=this.hls)==null||i.on(e,t)}once(e,t,s){var i;(i=this.hls)==null||i.once(e,t)}off(e,t,s){var i;(i=this.hls)==null||i.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${Ws(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const bc=.033;class Vm extends rt{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((s,i)=>e<=i.startOffset&&t>i.startOffset?(delete i.error,s+1):s,0):0}get duration(){const e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let s=-1;e.nextEvent?s=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(s=this.findEventIndex(e.previousEvent.identifier)+1);const i=this.items;if(i)for(i[s]||(t===void 0&&(t=e.start),s=this.findItemIndexAtTime(t));s>=0&&(n=i[s])!=null&&n.event;){var n;s--}return s}findItemIndexAtTime(e,t){const s=this.items;if(s)for(let i=0;i<s.length;i++){let n=s[i];if(t&&t!=="primary"&&(n=n[t]),e===n.start||e>n.start&&e<n.end)return i}return-1}findJumpRestrictedIndex(e,t){const s=this.items;if(s)for(let i=e;i<=t&&s[i];i++){const n=s[i].event;if(n!=null&&n.restrictions.jump&&!n.appendInPlace)return i}return-1}findEventIndex(e){const t=this.items;if(t)for(let i=t.length;i--;){var s;if(((s=t[i].event)==null?void 0:s.identifier)===e)return i}return-1}findAssetIndex(e,t){const s=e.assetList,i=s.length;if(i>1)for(let n=0;n<i;n++){const a=s[n];if(!a.error){const o=a.timelineStart;if(t===o||t>o&&(t<o+(a.duration||0)||n===i-1))return n}}return 0}get assetIdAtEnd(){var e;const t=(e=this.items)==null||(e=e[this.length-1])==null?void 0:e.event;if(t){const s=t.assetList,i=s[s.length-1];if(i)return i.identifier}return null}parseInterstitialDateRanges(e,t){const s=e.main.details,{dateRanges:i}=s,n=this.events,a=this.parseDateRanges(i,{url:s.url},t),o=Object.keys(i),c=n?n.filter(l=>!o.includes(l.identifier)):[];a.length&&a.sort((l,u)=>{const h=l.cue.pre,d=l.cue.post,g=u.cue.pre,f=u.cue.post;if(h&&!g)return-1;if(g&&!h||d&&!f)return 1;if(f&&!d)return-1;if(!h&&!g&&!d&&!f){const p=l.startTime,y=u.startTime;if(p!==y)return p-y}return l.dateRange.tagOrder-u.dateRange.tagOrder}),this.events=a,c.forEach(l=>{this.removeEvent(l)}),this.updateSchedule(e,c)}updateSchedule(e,t=[],s=!1){const i=this.events||[];if(i.length||t.length||this.length<2){const n=this.items,a=this.parseSchedule(i,e);(s||t.length||n?.length!==a.length||a.some((c,l)=>Math.abs(c.playout.start-n[l].playout.start)>.005||Math.abs(c.playout.end-n[l].playout.end)>.005))&&(this.items=a,this.onScheduleUpdate(t,n))}}parseDateRanges(e,t,s){const i=[],n=Object.keys(e);for(let a=0;a<n.length;a++){const o=n[a],c=e[o];if(c.isInterstitial){let l=this.eventMap[o];l?l.setDateRange(c):(l=new Um(c,t),this.eventMap[o]=l,s===!1&&(l.appendInPlace=s)),i.push(l)}}return i}parseSchedule(e,t){const s=[],i=t.main.details,n=i.live?1/0:i.edge;let a=0;if(e=e.filter(c=>!c.error&&!(c.cue.once&&c.hasPlayed)),e.length){this.resolveOffsets(e,t);let c=0,l=0;if(e.forEach((u,h)=>{const d=u.cue.pre,g=u.cue.post,f=e[h-1]||null,p=u.appendInPlace,y=g?n:u.startOffset,v=u.duration,E=u.timelineOccupancy===or.Range?v:0,T=u.resumptionOffset,S=f?.startTime===y,_=y+u.cumulativeDuration;let D=p?_+v:y+T;if(d||!g&&y<=0){const b=l;l+=E,u.timelineStart=_;const A=a;a+=v,s.push({event:u,start:_,end:D,playout:{start:A,end:a},integrated:{start:b,end:l}})}else if(y<=n){if(!S){const x=y-c;if(x>bc){const C=c,M=l;l+=x;const K=a;a+=x;const V={previousEvent:e[h-1]||null,nextEvent:u,start:C,end:C+x,playout:{start:K,end:a},integrated:{start:M,end:l}};s.push(V)}else x>0&&f&&(f.cumulativeDuration+=x,s[s.length-1].end=y)}g&&(D=_),u.timelineStart=_;const b=l;l+=E;const A=a;a+=v,s.push({event:u,start:_,end:D,playout:{start:A,end:a},integrated:{start:b,end:l}})}else return;const I=u.resumeTime;g||I>n?c=n:c=I}),c<n){var o;const u=c,h=l,d=n-c;l+=d;const g=a;a+=d,s.push({previousEvent:((o=s[s.length-1])==null?void 0:o.event)||null,nextEvent:null,start:c,end:u+d,playout:{start:g,end:a},integrated:{start:h,end:l}})}this.setDurations(n,a,l)}else s.push({previousEvent:null,nextEvent:null,start:0,end:n,playout:{start:0,end:n},integrated:{start:0,end:n}}),this.setDurations(n,n,n);return s}setDurations(e,t,s){this.durations={primary:e,playout:t,integrated:s}}resolveOffsets(e,t){const s=t.main.details,i=s.live?1/0:s.edge;let n=0,a=-1;e.forEach((o,c)=>{const l=o.cue.pre,u=o.cue.post,h=l?0:u?i:o.startTime;this.updateAssetDurations(o),a===h?o.cumulativeDuration=n:(n=0,a=h),!u&&o.snapOptions.in&&(o.resumeAnchor=gs(null,s.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1)),!o.appendInPlace&&c+1<e.length&&e[c+1].startTime-e[c].resumeTime<bc&&(e[c+1].appendInPlace=!1,e[c+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`));const g=$(o.resumeOffset)?o.resumeOffset:o.duration;n+=g})}primaryCanResumeInPlaceAt(e,t){const s=e.resumeTime,i=e.startTime+e.resumptionOffset;return Math.abs(s-i)>Hs?(this.log(`"${e.identifier}" resumption ${s} not aligned with estimated timeline end ${i}`),!1):!Object.keys(t).some(a=>{const o=t[a].details,c=o.edge;if(s>=c)return this.log(`"${e.identifier}" resumption ${s} past ${a} playlist end ${c}`),!1;const l=gs(null,o.fragments,s);if(!l)return this.log(`"${e.identifier}" resumption ${s} does not align with any fragments in ${a} playlist (${o.fragStart}-${o.fragmentEnd})`),!0;const u=a==="audio"?.175:0;return Math.abs(l.start-s)<Hs+u||Math.abs(l.end-s)<Hs+u?!1:(this.log(`"${e.identifier}" resumption ${s} not aligned with ${a} fragment bounds (${l.start}-${l.end} sn: ${l.sn} cc: ${l.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;const t=e.timelineStart;let s=0,i=!1,n=!1;for(let a=0;a<e.assetList.length;a++){const o=e.assetList[a],c=t+s;o.startOffset=s,o.timelineStart=c,i||(i=o.duration===null),n||(n=!!o.error);const l=o.error?0:o.duration||0;s+=l}i&&!n?e.duration=Math.max(s,e.duration):e.duration=s}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function dt(r){return`[${r.event?'"'+r.event.identifier+'"':"primary"}: ${r.start.toFixed(2)}-${r.end.toFixed(2)}]`}class Hm{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const s=e.assetListUrl;let i;try{i=Rc(s,this.hls.sessionId,e.baseUrl)}catch(d){const g=this.assignAssetListError(e,R.ASSET_LIST_LOAD_ERROR,d,s);this.hls.trigger(m.ERROR,g);return}t&&i.protocol!=="data:"&&i.searchParams.set("_HLS_start_offset",""+t);const n=this.hls.config,a=n.loader,o=new a(n),c={responseType:"json",url:i.href},l=n.interstitialAssetListLoadPolicy.default,u={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(d,g,f,p)=>{const y=d.data,v=y?.ASSETS;if(!Array.isArray(v)){const E=this.assignAssetListError(e,R.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),f.url,g,p);this.hls.trigger(m.ERROR,E);return}e.assetListResponse=y,this.hls.trigger(m.ASSET_LIST_LOADED,{event:e,assetListResponse:y,networkDetails:p})},onError:(d,g,f,p)=>{const y=this.assignAssetListError(e,R.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${d.code} ${d.text} (${g.url})`),g.url,p,f);this.hls.trigger(m.ERROR,y)},onTimeout:(d,g,f)=>{const p=this.assignAssetListError(e,R.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${g.url})`),g.url,d,f);this.hls.trigger(m.ERROR,p)}};return o.load(c,u,h),this.hls.trigger(m.ASSET_LIST_LOADING,{event:e}),o}assignAssetListError(e,t,s,i,n,a){return e.error=s,{type:H.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:i,error:s,networkDetails:a,stats:n}}}function Dc(r){var e;r==null||(e=r.play())==null||e.catch(()=>{})}function lr(r,e){return`[${r}] Advancing timeline position to ${e}`}class Wm extends rt{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const s=this.currentTime;if(s===void 0||this.playbackDisabled||!this.schedule)return;const i=s-this.timelinePos;if(Math.abs(i)<1/7056e5)return;const a=i<=-.01;this.timelinePos=s,this.bufferedPos=s;const o=this.playingItem;if(!o){this.checkBuffer();return}if(a&&this.schedule.resetErrorsInRange(s,s-i)&&this.updateSchedule(!0),this.checkBuffer(),a&&s<o.start||s>=o.end){var c;const g=this.findItemIndex(o);let f=this.schedule.findItemIndexAtTime(s);if(f===-1&&(f=g+(a?-1:1),this.log(`seeked ${a?"back ":""}to position not covered by schedule ${s} (resolving from ${g} to ${f})`)),!this.isInterstitial(o)&&(c=this.media)!=null&&c.paused&&(this.shouldPlay=!1),!a&&f>g){const p=this.schedule.findJumpRestrictedIndex(g+1,f);if(p>g){this.setSchedulePosition(p);return}}this.setSchedulePosition(f);return}const l=this.playingAsset;if(!l){if(this.playingLastItem&&this.isInterstitial(o)){const g=o.event.assetList[0];g&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(s,g))}return}const u=l.timelineStart,h=l.duration||0;if(a&&s<u||s>=u+h){var d;(d=o.event)!=null&&d.appendInPlace&&(this.clearAssetPlayers(o.event,o),this.flushFrontBuffer(s)),this.setScheduleToAssetAtTime(s,l)}},this.onTimeupdate=()=>{const s=this.currentTime;if(s===void 0||this.playbackDisabled)return;if(s>this.timelinePos)this.timelinePos=s,s>this.bufferedPos&&this.checkBuffer();else return;const i=this.playingItem;if(!i||this.playingLastItem)return;if(s>=i.end){this.timelinePos=i.end;const o=this.findItemIndex(i);this.setSchedulePosition(o+1)}const n=this.playingAsset;if(!n)return;const a=n.timelineStart+(n.duration||0);s>=a&&this.setScheduleToAssetAtTime(s,n)},this.onScheduleUpdate=(s,i)=>{const n=this.schedule;if(!n)return;const a=this.playingItem,o=n.events||[],c=n.items||[],l=n.durations,u=s.map(p=>p.identifier),h=!!(o.length||u.length);(h||i)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o}
30
- Schedule: ${c.map(p=>dt(p))} pos: ${this.timelinePos}`),u.length&&this.log(`Removed events ${u}`);let d=null,g=null;a&&(d=this.updateItem(a,this.timelinePos),this.itemsMatch(a,d)?this.playingItem=d:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const f=this.bufferingItem;if(f&&(g=this.updateItem(f,this.bufferedPos),this.itemsMatch(f,g)?this.bufferingItem=g:f.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(f.event,null))),s.forEach(p=>{p.assetList.forEach(y=>{this.clearAssetPlayer(y.identifier,null)})}),this.playerQueue.forEach(p=>{if(p.interstitial.appendInPlace){const y=p.assetItem.timelineStart,v=p.timelineOffset-y;if(v)try{p.timelineOffset=y}catch(E){Math.abs(v)>Hs&&this.warn(`${E} ("${p.assetId}" ${p.timelineOffset}->${y})`)}}}),h||i){if(this.hls.trigger(m.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:c.slice(0),durations:l,removedIds:u}),this.isInterstitial(a)&&u.includes(a.event.identifier)){this.warn(`Interstitial "${a.event.identifier}" removed while playing`),this.primaryFallback(a.event);return}a&&this.trimInPlace(d,a),f&&g!==d&&this.trimInPlace(g,f),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new Hm(e),this.schedule=new Vm(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(m.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(m.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(m.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(m.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(m.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(m.BUFFER_APPENDED,this.onBufferAppended,this),e.on(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(m.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(m.MEDIA_ENDED,this.onMediaEnded,this),e.on(m.ERROR,this.onError,this),e.on(m.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(m.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(m.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(m.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(m.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(m.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(m.BUFFER_CODECS,this.onBufferCodecs,this),e.off(m.BUFFER_APPENDED,this.onBufferAppended,this),e.off(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(m.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(m.MEDIA_ENDED,this.onMediaEnded,this),e.off(m.ERROR,this.onError,this),e.off(m.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;(e=this.getBufferingPlayer())==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.getBufferingPlayer())==null||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){He(e,"play",this.onPlay),He(e,"pause",this.onPause),He(e,"seeking",this.onSeeking),He(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const s=this.media=t.media;Ue(s,"seeking",this.onSeeking),Ue(s,"timeupdate",this.onTimeupdate),Ue(s,"play",this.onPlay),Ue(s,"pause",this.onPause)}onMediaAttached(e,t){const s=this.effectivePlayingItem,i=this.detachedData;if(this.detachedData=null,s===null)this.checkStart();else if(!i){this.clearScheduleState();const n=this.findItemIndex(s);this.setSchedulePosition(n)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){const s=!!t.transferMedia,i=this.media;if(this.media=null,!s&&(i&&this.removeMediaListeners(i),this.detachedData)){const n=this.getBufferingPlayer();n&&(this.log(`Removing schedule state for detachedData and ${n}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,n.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const e=this,t=()=>e.bufferingItem||e.waitingItem,s=h=>h&&e.getAssetPlayer(h.identifier),i=(h,d,g,f,p)=>{if(h){let y=h[d].start;const v=h.event;if(v){if(d==="playout"||v.timelineOccupancy!==or.Point){const E=s(g);E?.interstitial===v&&(y+=E.assetItem.startOffset+E[p])}}else{const E=f==="bufferedPos"?a():e[f];y+=E-h.start}return y}return 0},n=(h,d)=>{var g;if(h!==0&&d!=="primary"&&(g=e.schedule)!=null&&g.length){var f;const p=e.schedule.findItemIndexAtTime(h),y=(f=e.schedule.items)==null?void 0:f[p];if(y){const v=y[d].start-y.start;return h+v}}return h},a=()=>{const h=e.bufferedPos;return h===Number.MAX_VALUE?o("primary"):Math.max(h,0)},o=h=>{var d,g;return(d=e.primaryDetails)!=null&&d.live?e.primaryDetails.edge:((g=e.schedule)==null?void 0:g.durations[h])||0},c=(h,d)=>{var g,f;const p=e.effectivePlayingItem;if(p!=null&&(g=p.event)!=null&&g.restrictions.skip||!e.schedule)return;e.log(`seek to ${h} "${d}"`);const y=e.effectivePlayingItem,v=e.schedule.findItemIndexAtTime(h,d),E=(f=e.schedule.items)==null?void 0:f[v],T=e.getBufferingPlayer(),S=T?.interstitial,_=S?.appendInPlace,D=y&&e.itemsMatch(y,E);if(y&&(_||D)){const I=s(e.playingAsset),b=I?.media||e.primaryMedia;if(b){const A=d==="primary"?b.currentTime:i(y,d,e.playingAsset,"timelinePos","currentTime"),x=h-A,C=(_?A:b.currentTime)+x;if(C>=0&&(!I||_||C<=I.duration)){b.currentTime=C;return}}}if(E){let I=h;if(d!=="primary"){const A=E[d].start,x=h-A;I=E.start+x}const b=!e.isInterstitial(E);if((!e.isInterstitial(y)||y.event.appendInPlace)&&(b||E.event.appendInPlace)){const A=e.media||(_?T?.media:null);A&&(A.currentTime=I)}else if(y){const A=e.findItemIndex(y);if(v>A){const C=e.schedule.findJumpRestrictedIndex(A+1,v);if(C>A){e.setSchedulePosition(C);return}}let x=0;if(b)e.timelinePos=I,e.checkBuffer();else{const C=E.event.assetList,M=h-(E[d]||E).start;for(let K=C.length;K--;){const V=C[K];if(V.duration&&M>=V.startOffset&&M<V.startOffset+V.duration){x=K;break}}}e.setSchedulePosition(v,x)}}},l=()=>{const h=e.effectivePlayingItem;if(e.isInterstitial(h))return h;const d=t();return e.isInterstitial(d)?d:null},u={get bufferedEnd(){const h=t(),d=e.bufferingItem;if(d&&d===h){var g;return i(d,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-d.playout.start||((g=e.bufferingAsset)==null?void 0:g.startOffset)||0}return 0},get currentTime(){const h=l(),d=e.effectivePlayingItem;return d&&d===h?i(d,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-d.playout.start:0},set currentTime(h){const d=l(),g=e.effectivePlayingItem;g&&g===d&&c(h+g.playout.start,"playout")},get duration(){const h=l();return h?h.playout.end-h.playout.start:0},get assetPlayers(){var h;const d=(h=l())==null?void 0:h.event.assetList;return d?d.map(g=>e.getAssetPlayer(g.identifier)):[]},get playingIndex(){var h;const d=(h=l())==null?void 0:h.event;return d&&e.effectivePlayingAsset?d.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return l()}};return this.manager={get events(){var h;return((h=e.schedule)==null||(h=h.events)==null?void 0:h.slice(0))||[]},get schedule(){var h;return((h=e.schedule)==null||(h=h.items)==null?void 0:h.slice(0))||[]},get interstitialPlayer(){return l()?u:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const h=t();return e.findItemIndex(h)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const h=e.effectivePlayingItem;return e.findItemIndex(h)},primary:{get bufferedEnd(){return a()},get currentTime(){const h=e.timelinePos;return h>0?h:0},set currentTime(h){c(h,"primary")},get duration(){return o("primary")},get seekableStart(){var h;return((h=e.primaryDetails)==null?void 0:h.fragmentStart)||0}},integrated:{get bufferedEnd(){return i(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return i(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(h){c(h,"integrated")},get duration(){return o("integrated")},get seekableStart(){var h;return n(((h=e.primaryDetails)==null?void 0:h.fragmentStart)||0,"integrated")}},skip:()=>{const h=e.effectivePlayingItem,d=h?.event;if(d&&!d.restrictions.skip){const g=e.findItemIndex(h);if(d.appendInPlace){const f=h.playout.start+h.event.duration;c(f+.001,"playout")}else e.advanceAfterAssetEnded(d,g,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;const t=this.playingItem,s=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!s?!1:this.findItemIndex(t)===s.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t;if(this.mediaSelection===null)return;const s=this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&!s.event.appendInPlace)return;let i=this.media;!i&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(i=this.primaryMedia);const n=(t=i)==null?void 0:t.currentTime;if(!(n===void 0||!$(n)))return n}get primaryMedia(){var e;return this.media||((e=this.detachedData)==null?void 0:e.media)||null}isInterstitial(e){return!!(e!=null&&e.event)}retreiveMediaSource(e,t){const s=this.getAssetPlayer(e);s&&this.transferMediaFromPlayer(s,t)}transferMediaFromPlayer(e,t){const s=e.interstitial.appendInPlace,i=e.media;if(s&&i===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&i){this.detachedData={media:i};return}const n=e.transferMedia();this.log(`transfer MediaSource from ${e} ${ue(n)}`),this.detachedData=n}else t&&i&&(this.shouldPlay||(this.shouldPlay=!i.paused))}transferMediaTo(e,t){var s,i;if(e.media===t)return;let n=null;const a=this.hls,o=e!==a,c=o&&e.interstitial.appendInPlace,l=(s=this.detachedData)==null?void 0:s.mediaSource;let u;if(a.media)c&&(n=a.transferMedia(),this.detachedData=n),u="Primary";else if(l){const f=this.getBufferingPlayer();f?(n=f.transferMedia(),u=`${f}`):u="detached MediaSource"}else u="detached media";if(!n){if(l)n=this.detachedData,this.log(`using detachedData: MediaSource ${ue(n)}`);else if(!this.detachedData||a.media===t){const f=this.playerQueue;f.length>1&&f.forEach(p=>{if(o&&p.interstitial.appendInPlace!==c){const y=p.interstitial;this.clearInterstitial(p.interstitial,null),y.appendInPlace=!1,y.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${y}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}const h=n&&"mediaSource"in n&&((i=n.mediaSource)==null?void 0:i.readyState)!=="closed",d=h&&n?n:t;this.log(`${h?"transfering MediaSource":"attaching media"} to ${o?e:"Primary"} from ${u} (media.currentTime: ${t.currentTime})`);const g=this.schedule;if(d===n&&g){const f=o&&e.assetId===g.assetIdAtEnd;d.overrides={duration:g.duration,endOfStream:!o||f,cueRemoval:!o}}e.attachMedia(d)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,t=e?.events;if(!t||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);const s=this.timelinePos,i=this.effectivePlayingItem;if(s===-1){const n=this.hls.startPosition;if(this.log(lr("checkStart",n)),this.timelinePos=n,t.length&&t[0].cue.pre){const a=e.findEventIndex(t[0].identifier);this.setSchedulePosition(a)}else if(n>=0||!this.primaryLive){const a=this.timelinePos=n>0?n:0,o=e.findItemIndexAtTime(a);this.setSchedulePosition(o)}}else if(i&&!this.playingItem){const n=e.findItemIndex(i);this.setSchedulePosition(n)}}advanceAssetBuffering(e,t){const s=e.event,i=s.findAssetIndex(t),n=Mn(s,i);if(!s.isAssetPastPlayoutLimit(n))this.bufferedToEvent(e,n);else if(this.schedule){var a;const o=(a=this.schedule.items)==null?void 0:a[this.findItemIndex(e)+1];o&&this.bufferedToItem(o)}}advanceAfterAssetEnded(e,t,s){const i=Mn(e,s);if(e.isAssetPastPlayoutLimit(i)){if(this.schedule){const n=this.schedule.items;if(n){const a=t+1,o=n.length;if(a>=o){this.setSchedulePosition(-1);return}const c=e.resumeTime;this.timelinePos<c&&(this.log(lr("advanceAfterAssetEnded",c)),this.timelinePos=c,e.appendInPlace&&this.advanceInPlace(c),this.checkBuffer(this.bufferedPos<c)),this.setSchedulePosition(a)}}}else{if(e.appendInPlace){const n=e.assetList[i];n&&this.advanceInPlace(n.timelineStart)}this.setSchedulePosition(t,i)}}setScheduleToAssetAtTime(e,t){const s=this.schedule;if(!s)return;const i=t.parentIdentifier,n=s.getEvent(i);if(n){const a=s.findEventIndex(i),o=s.findAssetIndex(n,e);this.advanceAfterAssetEnded(n,a,o-1)}}setSchedulePosition(e,t){var s;const i=(s=this.schedule)==null?void 0:s.items;if(!i||this.playbackDisabled)return;const n=e>=0?i[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${n&&dt(n)}) pos: ${this.timelinePos}`);const a=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(a)){const u=a.event,h=this.playingAsset,d=h?.identifier,g=d?this.getAssetPlayer(d):null;if(g&&d&&(!this.eventItemsMatch(a,n)||t!==void 0&&d!==u.assetList[t].identifier)){var c;const f=u.findAssetIndex(h);if(this.log(`INTERSTITIAL_ASSET_ENDED ${f+1}/${u.assetList.length} ${Ws(h)}`),this.endedAsset=h,this.playingAsset=null,this.hls.trigger(m.INTERSTITIAL_ASSET_ENDED,{asset:h,assetListIndex:f,event:u,schedule:i.slice(0),scheduleIndex:e,player:g}),a!==this.playingItem){this.itemsMatch(a,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(u,this.findItemIndex(this.playingItem),f);return}this.retreiveMediaSource(d,n),g.media&&!((c=this.detachedData)!=null&&c.mediaSource)&&g.detachMedia()}if(!this.eventItemsMatch(a,n)&&(this.endedItem=a,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${u} ${dt(a)}`),u.hasPlayed=!0,this.hls.trigger(m.INTERSTITIAL_ENDED,{event:u,schedule:i.slice(0),scheduleIndex:e}),u.cue.once)){var l;this.updateSchedule();const f=(l=this.schedule)==null?void 0:l.items;if(n&&f){const p=this.findItemIndex(n);this.advanceSchedule(p,f,t,a,o)}return}}this.advanceSchedule(e,i,t,a,o)}advanceSchedule(e,t,s,i,n){const a=this.schedule;if(!a)return;const o=t[e]||null,c=this.primaryMedia,l=this.playerQueue;if(l.length&&l.forEach(u=>{const h=u.interstitial,d=a.findEventIndex(h.identifier);(d<e||d>e+1)&&this.clearInterstitial(h,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);const u=o.event;if(s===void 0){s=a.findAssetIndex(u,this.timelinePos);const f=Mn(u,s-1);if(u.isAssetPastPlayoutLimit(f)||u.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(u,e,s);return}s=f}const h=this.waitingItem;this.assetsBuffered(o,c)||this.setBufferingItem(o);let d=this.preloadAssets(u,s);if(this.eventItemsMatch(o,h||i)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${dt(o)} ${u.appendInPlace?"append in place":""}`),this.hls.trigger(m.INTERSTITIAL_STARTED,{event:u,schedule:t.slice(0),scheduleIndex:e})),!u.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${u}`);return}if(u.assetListLoader&&(u.assetListLoader.destroy(),u.assetListLoader=void 0),!c){this.log(`Waiting for attachMedia to start Interstitial ${u}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;const g=u.assetList[s];if(!g){this.advanceAfterAssetEnded(u,e,s||0);return}if(d||(d=this.getAssetPlayer(g.identifier)),d===null||d.destroyed){const f=u.assetList.length;this.warn(`asset ${s+1}/${f} player destroyed ${u}`),d=this.createAssetPlayer(u,g,s),d.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&u.appendInPlace&&this.isAssetBuffered(g))return;this.startAssetPlayer(d,s,t,e,c),this.shouldPlay&&Dc(d.media)}else o?(this.resumePrimary(o,e,i),this.shouldPlay&&Dc(this.hls.media)):n&&this.isInterstitial(i)&&(this.endedItem=null,this.playingItem=i,i.event.appendInPlace||this.attachPrimary(a.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var e;return(e=this.mediaSelection)==null?void 0:e.main.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,s){var i,n;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${dt(e)}`),!((i=this.detachedData)!=null&&i.mediaSource)){let o=this.timelinePos;(o<e.start||o>=e.end)&&(o=this.getPrimaryResumption(e,t),this.log(lr("resumePrimary",o)),this.timelinePos=o),this.attachPrimary(o,e)}if(!s)return;const a=(n=this.schedule)==null?void 0:n.items;a&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${dt(e)}`),this.hls.trigger(m.INTERSTITIALS_PRIMARY_RESUMED,{schedule:a.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){const s=e.start;if(this.primaryLive){const i=this.primaryDetails;if(t===0)return this.hls.startPosition;if(i&&(s<i.fragmentStart||s>i.edge))return this.hls.liveSyncPosition||-1}return s}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:j.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,s){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const i=this.primaryMedia;if(!i)return;const n=this.hls;n.media?this.checkBuffer():(this.transferMediaTo(n,i),s&&this.startLoadingPrimaryAt(e,s)),s||(this.log(lr("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,s))}startLoadingPrimaryAt(e,t){var s;const i=this.hls;!i.loadingEnabled||!i.media||Math.abs((((s=i.mainForwardBufferInfo)==null?void 0:s.start)||i.media.currentTime)-e)>.5?i.startLoad(e,t):i.bufferingEnabled||i.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),(e=this.schedule)==null||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(m.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(m.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1||!this.schedule)return;const s=this.hls.levels[t.level];if(!s.details)return;const i=ae(ae({},this.mediaSelection||this.altSelection),{},{main:s});this.mediaSelection=i,this.schedule.parseInterstitialDateRanges(i,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){const s=this.hls.audioTracks[t.id],i=this.mediaSelection;if(!i){this.altSelection=ae(ae({},this.altSelection),{},{audio:s});return}const n=ae(ae({},i),{},{audio:s});this.mediaSelection=n}onSubtitleTrackUpdated(e,t){const s=this.hls.subtitleTracks[t.id],i=this.mediaSelection;if(!i){this.altSelection=ae(ae({},this.altSelection),{},{subtitles:s});return}const n=ae(ae({},i),{},{subtitles:s});this.mediaSelection=n}onAudioTrackSwitching(e,t){const s=Fo(t);this.playerQueue.forEach(({hls:i})=>i&&(i.setAudioOption(t)||i.setAudioOption(s)))}onSubtitleTrackSwitch(e,t){const s=Fo(t);this.playerQueue.forEach(({hls:i})=>i&&(i.setSubtitleOption(t)||t.id!==-1&&i.setSubtitleOption(s)))}onBufferCodecs(e,t){const s=t.tracks;s&&(this.requiredTracks=s)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){const s=this.playingItem;if(s&&!this.itemsMatch(s,this.bufferingItem)&&!this.isInterstitial(s)){const i=this.timelinePos;this.bufferedPos=i,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;const t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let i=0;i<t.length;i++){const n=t[i];if(n.cue.post){var s;const a=this.schedule.findEventIndex(n.identifier),o=(s=this.schedule.items)==null?void 0:s[a];this.isInterstitial(o)&&this.eventItemsMatch(o,this.bufferingItem)&&this.bufferedToItem(o,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){const t=this.playingItem;if(!this.playingLastItem&&t){const s=this.findItemIndex(t);this.setSchedulePosition(s+1)}else this.shouldPlay=!1}updateItem(e,t){var s;const i=(s=this.schedule)==null?void 0:s.items;if(e&&i){const n=this.findItemIndex(e,t);return i[n]||null}return null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((n,a)=>{e.event.isAssetPastPlayoutLimit(a)&&this.clearAssetPlayer(n.identifier,null)});const s=e.end+.25,i=j.bufferInfo(this.primaryMedia,s,0);(i.end>s||(i.nextStart||0)>s)&&(this.log(`trim buffered interstitial ${dt(e)} (was ${dt(t)})`),this.attachPrimary(s,null,!0),this.flushFrontBuffer(s))}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var s;return!!t&&(e===t||e.event.identifier===((s=t.event)==null?void 0:s.identifier))}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;const s=this.mediaSelection;s&&((t=this.schedule)==null||t.updateSchedule(s,[],e))}checkBuffer(e){var t;const s=(t=this.schedule)==null?void 0:t.items;if(!s)return;const i=j.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=i.len<1),this.updateBufferedPos(i.end,s,e)}updateBufferedPos(e,t,s){const i=this.schedule,n=this.bufferingItem;if(this.bufferedPos>e||!i)return;if(t.length===1&&this.itemsMatch(t[0],n)){this.bufferedPos=e;return}const a=this.playingItem,o=this.findItemIndex(a);let c=i.findItemIndexAtTime(e);if(this.bufferedPos<e){var l;const u=this.findItemIndex(n),h=Math.min(u+1,t.length-1),d=t[h];if((c===-1&&n&&e>=n.end||(l=d.event)!=null&&l.appendInPlace&&e+.01>=d.start)&&(c=h),this.isInterstitial(n)){const g=n.event;if(h-o>1&&g.appendInPlace===!1||g.assetList.length===0&&g.assetListLoader)return}if(this.bufferedPos=e,c>u&&c>o)this.bufferedToItem(d);else{const g=this.primaryDetails;this.primaryLive&&g&&e>g.edge-g.targetduration&&d.start<g.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(d)&&this.preloadAssets(d.event,0)}}else s&&a&&!this.itemsMatch(a,n)&&(c===o?this.bufferedToItem(a):c===o+1&&this.bufferedToItem(t[c]))}assetsBuffered(e,t){return e.event.assetList.length===0?!1:!e.event.assetList.some(i=>{const n=this.getAssetPlayer(i.identifier);return!(n!=null&&n.bufferedInPlaceToEnd(t))})}setBufferingItem(e){const t=this.bufferingItem,s=this.schedule;if(!this.itemsMatch(e,t)&&s){const{items:i,events:n}=s;if(!i||!n)return t;const a=this.isInterstitial(e),o=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));const c=o?o.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${dt(e)}`+(t?` (${c.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(a){const l=s.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((u,h)=>{const d=this.getAssetPlayer(u.identifier);d&&(h===l&&d.loadSource(),d.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(l=>l.pauseBuffering());this.hls.trigger(m.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:n.slice(0),schedule:i.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){const s=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(s!==null){this.bufferingAsset=null;const i=this.detachedData;i?i.mediaSource?this.attachPrimary(e.start,e,!0):this.preloadPrimary(e):this.preloadPrimary(e)}}}preloadPrimary(e){const t=this.findItemIndex(e),s=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(s)}bufferedToEvent(e,t){const s=e.event,i=s.assetList.length===0&&!s.assetListLoader,n=s.cue.once;if(i||!n){const a=this.preloadAssets(s,t);if(a!=null&&a.interstitial.appendInPlace){const o=this.primaryMedia;o&&this.bufferAssetPlayer(a,o)}}}preloadAssets(e,t){const s=e.assetUrl,i=e.assetList.length,n=i===0&&!e.assetListLoader,a=e.cue.once;if(n){const c=e.timelineStart;if(e.appendInPlace){var o;const d=this.playingItem;!this.isInterstitial(d)&&(d==null||(o=d.nextEvent)==null?void 0:o.identifier)===e.identifier&&this.flushFrontBuffer(c+.25)}let l,u=0;if(!this.playingItem&&this.primaryLive&&(u=this.hls.startPosition,u===-1&&(u=this.hls.liveSyncPosition||0)),u&&!(e.cue.pre||e.cue.post)){const d=u-c;d>0&&(l=Math.round(d*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${s?1:i} ${e}${l?` live-start: ${u} start-offset: ${l}`:""}`),s)return this.createAsset(e,0,0,c,e.duration,s);const h=this.assetListLoader.loadAssetList(e,l);h&&(e.assetListLoader=h)}else if(!a&&i){for(let l=t;l<i;l++){const u=e.assetList[l],h=this.getAssetPlayerQueueIndex(u.identifier);(h===-1||this.playerQueue[h].destroyed)&&!u.error&&this.createAssetPlayer(e,u,l)}const c=e.assetList[t];if(c){const l=this.getAssetPlayer(c.identifier);return l&&l.loadSource(),l}}return null}flushFrontBuffer(e){const t=this.requiredTracks;if(!t)return;this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(i=>{this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:i})})}getAssetPlayerQueueIndex(e){const t=this.playerQueue;for(let s=0;s<t.length;s++)if(e===t[s].assetId)return s;return-1}getAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){const{playerQueue:e,primaryMedia:t}=this;if(t){for(let s=0;s<e.length;s++)if(e[s].media===t)return e[s]}return null}createAsset(e,t,s,i,n,a){const o={parentIdentifier:e.identifier,identifier:Bm(e,a,t),duration:n,startOffset:s,timelineStart:i,uri:a};return this.createAssetPlayer(e,o,t)}createAssetPlayer(e,t,s){const i=this.hls,n=i.userConfig;let a=n.videoPreference;const o=i.loadLevelObj||i.levels[i.currentLevel];(a||o)&&(a=le({},a),o.videoCodec&&(a.videoCodec=o.videoCodec),o.videoRange&&(a.allowedVideoRanges=[o.videoRange]));const c=i.audioTracks[i.audioTrack],l=i.subtitleTracks[i.subtitleTrack];let u=0;if(this.primaryLive||e.appendInPlace){const S=this.timelinePos-t.timelineStart;if(S>1){const _=t.duration;_&&S<_&&(u=S)}}const h=t.identifier,d=ae(ae({},n),{},{maxMaxBufferLength:Math.min(180,i.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:i.sessionId,assetPlayerId:h,abrEwmaDefaultEstimate:i.bandwidthEstimate,interstitialsController:void 0,startPosition:u,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:a,audioPreference:c||n.audioPreference,subtitlePreference:l||n.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(d.timelineOffset=t.timelineStart));const g=d.cmcd;g!=null&&g.sessionId&&g.contentId&&(d.cmcd=le({},g,{contentId:di(t.uri)})),this.getAssetPlayer(h)&&this.warn(`Duplicate date range identifier ${e} and asset ${h}`);const f=new Km(this.HlsPlayerClass,d,e,t);this.playerQueue.push(f),e.assetList[s]=t;let p=!0;const y=S=>{if(S.live){var _;const b=new Error(`Interstitials MUST be VOD assets ${e}`),A={fatal:!0,type:H.OTHER_ERROR,details:R.INTERSTITIAL_ASSET_ITEM_ERROR,error:b},x=((_=this.schedule)==null?void 0:_.findEventIndex(e.identifier))||-1;this.handleAssetItemError(A,e,x,s,b.message);return}const D=S.edge-S.fragmentStart,I=t.duration;(p||I===null||D>I)&&(p=!1,this.log(`Interstitial asset "${h}" duration change ${I} > ${D}`),t.duration=D,this.updateSchedule())};f.on(m.LEVEL_UPDATED,(S,{details:_})=>y(_)),f.on(m.LEVEL_PTS_UPDATED,(S,{details:_})=>y(_)),f.on(m.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const v=(S,_)=>{const D=this.getAssetPlayer(h);if(D&&_.tracks){D.off(m.BUFFER_CODECS,v),D.tracks=_.tracks;const I=this.primaryMedia;this.bufferingAsset===D.assetItem&&I&&!D.media&&this.bufferAssetPlayer(D,I)}};f.on(m.BUFFER_CODECS,v);const E=()=>{var S;const _=this.getAssetPlayer(h);if(this.log(`buffered to end of asset ${_}`),!_||!this.schedule)return;const D=this.schedule.findEventIndex(e.identifier),I=(S=this.schedule.items)==null?void 0:S[D];this.isInterstitial(I)&&this.advanceAssetBuffering(I,t)};f.on(m.BUFFERED_TO_END,E);const T=S=>()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;this.shouldPlay=!0;const D=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,D,S)};return f.once(m.MEDIA_ENDED,T(s)),f.once(m.PLAYOUT_LIMIT_REACHED,T(1/0)),f.on(m.ERROR,(S,_)=>{if(!this.schedule)return;const D=this.getAssetPlayer(h);if(_.details===R.BUFFER_STALLED_ERROR){if(D!=null&&D.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(_,e,this.schedule.findEventIndex(e.identifier),s,`Asset player error ${_.error} ${e}`)}),f.on(m.DESTROYING,()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;const _=new Error(`Asset player destroyed unexpectedly ${h}`),D={fatal:!0,type:H.OTHER_ERROR,details:R.INTERSTITIAL_ASSET_ITEM_ERROR,error:_};this.handleAssetItemError(D,e,this.schedule.findEventIndex(e.identifier),s,_.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${Ws(t)}`),this.hls.trigger(m.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:s,event:e,player:f}),f}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(s=>{this.clearAssetPlayer(s.identifier,t)})}resetAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);const s=this.playerQueue[t];this.transferMediaFromPlayer(s,null),s.resetDetails()}}clearAssetPlayer(e,t){const s=this.getAssetPlayerQueueIndex(e);if(s!==-1){const i=this.playerQueue[s];this.log(`clear ${i} toSegment: ${t&&dt(t)}`),this.transferMediaFromPlayer(i,t),this.playerQueue.splice(s,1),i.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,s,i,n){const{interstitial:a,assetItem:o,assetId:c}=e,l=a.assetList.length,u=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(!u||u.identifier!==c)&&(u&&(this.clearAssetPlayer(u.identifier,s[i]),delete u.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${l} ${Ws(o)}`),this.hls.trigger(m.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:t,event:a,schedule:s.slice(0),scheduleIndex:i,player:e})),this.bufferAssetPlayer(e,n)}bufferAssetPlayer(e,t){var s,i;if(!this.schedule)return;const{interstitial:n,assetItem:a}=e,o=this.schedule.findEventIndex(n.identifier),c=(s=this.schedule.items)==null?void 0:s[o];if(!c)return;e.loadSource(),this.setBufferingItem(c),this.bufferingAsset=a;const l=this.getBufferingPlayer();if(l===e)return;const u=n.appendInPlace;if(u&&l?.interstitial.appendInPlace===!1)return;const h=l?.tracks||((i=this.detachedData)==null?void 0:i.tracks)||this.requiredTracks;if(u&&a!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(h&&!lo(h,e.tracks)){const d=new Error(`Asset ${Ws(a)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(h)}')`),g={fatal:!0,type:H.OTHER_ERROR,details:R.INTERSTITIAL_ASSET_ITEM_ERROR,error:d},f=n.findAssetIndex(a);this.handleAssetItemError(g,n,o,f,d.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){const t=this.schedule,s=this.primaryMedia;if(!t||!s)return;const i=s.currentTime,n=t.findAssetIndex(e,i),a=e.assetList[n];if(a){const o=this.getAssetPlayer(a.identifier);if(o){const c=o.currentTime||i-a.timelineStart,l=o.duration-c;if(this.warn(`Stalled at ${c} of ${c+l} in ${o} ${e} (media.currentTime: ${i})`),c&&(l/s.playbackRate<.5||o.bufferedInPlaceToEnd(s))&&o.hls){const u=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,u,n)}}}}advanceInPlace(e){const t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e)}handleAssetItemError(e,t,s,i,n){if(e.details===R.BUFFER_STALLED_ERROR)return;const a=t.assetList[i]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${a&&Ws(a)} ${e.error}`),!this.schedule)return;const o=a?.identifier||"",c=this.getAssetPlayerQueueIndex(o),l=this.playerQueue[c]||null,u=this.schedule.items,h=le({},e,{fatal:!1,errorAction:Ms(!0),asset:a,assetListIndex:i,event:t,schedule:u,scheduleIndex:s,player:l});if(this.hls.trigger(m.INTERSTITIAL_ASSET_ERROR,h),!e.fatal)return;const d=this.playingAsset,g=this.bufferingAsset,f=new Error(n);if(a&&(this.clearAssetPlayer(o,null),a.error=f),!t.assetList.some(p=>!p.error))t.error=f;else for(let p=i;p<t.assetList.length;p++)this.resetAssetPlayer(t.assetList[p].identifier);this.updateSchedule(!0),t.error?this.primaryFallback(t):d&&d.identifier===o?this.advanceAfterAssetEnded(t,s,i):g&&g.identifier===o&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,g)}primaryFallback(e){const t=e.timelineStart,s=this.effectivePlayingItem;let i=this.timelinePos;if(s){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${i} playing: ${dt(s)} error: ${e.error}`),i===-1&&(i=this.hls.startPosition);const a=this.updateItem(s,i);this.itemsMatch(s,a)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(i===-1){this.checkStart();return}if(!this.schedule)return;const n=this.schedule.findItemIndexAtTime(i);this.setSchedulePosition(n)}onAssetListLoaded(e,t){var s,i;const n=t.event,a=n.identifier,o=t.assetListResponse.ASSETS;if(!((s=this.schedule)!=null&&s.hasEvent(a)))return;const c=n.timelineStart,l=n.duration;let u=0;o.forEach((p,y)=>{const v=parseFloat(p.DURATION);this.createAsset(n,y,u,c+u,v,p.URI),u+=v}),n.duration=u,this.log(`Loaded asset-list with duration: ${u} (was: ${l}) ${n}`);const h=this.waitingItem,d=h?.event.identifier===a;this.updateSchedule();const g=(i=this.bufferingItem)==null?void 0:i.event;if(d){var f;const p=this.schedule.findEventIndex(a),y=(f=this.schedule.items)==null?void 0:f[p];if(y){if(!this.playingItem&&this.timelinePos>y.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==p){n.error=new Error(`Interstitial ${o.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${n}`),this.log(n.error.message),this.updateSchedule(!0),this.primaryFallback(n);return}this.setBufferingItem(y)}this.setSchedulePosition(p)}else if(g?.identifier===a){const p=n.assetList[0];if(p){const y=this.getAssetPlayer(p.identifier);if(g.appendInPlace){const v=this.primaryMedia;y&&v&&this.bufferAssetPlayer(y,v)}else y&&y.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case R.ASSET_LIST_PARSING_ERROR:case R.ASSET_LIST_LOAD_ERROR:case R.ASSET_LIST_LOAD_TIMEOUT:{const s=t.interstitial;s&&(this.updateSchedule(!0),this.primaryFallback(s));break}case R.BUFFER_STALLED_ERROR:{const s=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&s.event.appendInPlace){this.handleInPlaceStall(s.event);return}this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}const Cc=500;class Ym extends cn{constructor(e,t,s){super(e,t,s,"subtitle-stream-controller",G.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(m.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(m.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(m.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(m.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=P.IDLE,this.setInterval(Cc),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:s,success:i}=t;if(this.fragContextChanged(s)||(xe(s)&&(this.fragPrevious=s),this.state=P.IDLE),!i)return;const n=this.tracksBuffered[this.currentTrackId];if(!n)return;let a;const o=s.start;for(let l=0;l<n.length;l++)if(o>=n[l].start&&o<=n[l].end){a=n[l];break}const c=s.start+s.duration;a?a.end=c:(a={start:o,end:c},n.push(a)),this.fragmentTracker.fragBuffered(s),this.fragBufferedComplete(s,null),this.media&&this.tick()}onBufferFlushing(e,t){const{startOffset:s,endOffset:i}=t;if(s===0&&i!==Number.POSITIVE_INFINITY){const n=i-1;if(n<=0)return;t.endOffsetSubtitles=Math.max(0,n),this.tracksBuffered.forEach(a=>{for(let o=0;o<a.length;){if(a[o].end<=n){a.shift();continue}else if(a[o].start<n)a[o].start=n;else break;o++}}),this.fragmentTracker.removeFragmentsInRange(s,n,G.SUBTITLE)}}onError(e,t){const s=t.frag;s?.type===G.SUBTITLE&&(t.details===R.FRAG_GAP&&this.fragmentTracker.fragBuffered(s,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==P.STOPPED&&(this.state=P.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&nc(this.levels,t)){this.levels=t.map(s=>new ii(s));return}this.tracksBuffered=[],this.levels=t.map(s=>{const i=new ii(s);return this.tracksBuffered[i.id]=[],i}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,G.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var s;if(this.currentTrackId=t.id,!((s=this.levels)!=null&&s.length)||this.currentTrackId===-1){this.clearInterval();return}const i=this.levels[this.currentTrackId];i!=null&&i.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,i&&this.state!==P.STOPPED&&this.setInterval(Cc)}onSubtitleTrackLoaded(e,t){var s;const{currentTrackId:i,levels:n}=this,{details:a,id:o}=t;if(!n){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}const c=n[o];if(o>=n.length||!c)return;this.log(`Subtitle track ${o} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""},duration:${a.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(a.live||(s=c.details)!=null&&s.live){if(a.deltaUpdateFailed)return;const h=this.mainDetails;if(!h){this.startFragRequested=!1;return}const d=h.fragments[0];if(!c.details)a.hasProgramDateTime&&h.hasProgramDateTime?(ji(a,h),l=a.fragmentStart):d&&(l=d.start,ln(a,l));else{var u;l=this.alignPlaylists(a,c.details,(u=this.levelLastLoaded)==null?void 0:u.details),l===0&&d&&(l=d.start,ln(a,l))}h&&!this.startFragRequested&&this.setStartPosition(h,l)}c.details=a,this.levelLastLoaded=c,o===i&&(this.hls.trigger(m.SUBTITLE_TRACK_UPDATED,{details:a,id:o,groupId:t.groupId}),this.tick(),a.live&&!this.fragCurrent&&this.media&&this.state===P.IDLE&&(gs(null,a.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),c.details=void 0)))}_handleFragmentLoadComplete(e){const{frag:t,payload:s}=e,i=t.decryptdata,n=this.hls;if(!this.fragContextChanged(t)&&s&&s.byteLength>0&&i!=null&&i.key&&i.iv&&Ns(i.method)){const a=performance.now();this.decrypter.decrypt(new Uint8Array(s),i.key.buffer,i.iv.buffer,en(i.method)).catch(o=>{throw n.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:R.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:t}),o}).then(o=>{const c=performance.now();n.trigger(m.FRAG_DECRYPTED,{frag:t,payload:o,stats:{tstart:a,tdecrypt:c}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=P.IDLE})}}doTick(){if(!this.media){this.state=P.IDLE;return}if(this.state===P.IDLE){const{currentTrackId:e,levels:t}=this,s=t?.[e];if(!s||!t.length||!s.details||this.waitForLive(s))return;const{config:i}=this,n=this.getLoadPosition(),a=j.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],n,i.maxBufferHole),{end:o,len:c}=a,l=s.details,u=this.hls.maxBufferLength+l.levelTargetDuration;if(c>u)return;const h=l.fragments,d=h.length,g=l.edge;let f=null;const p=this.fragPrevious;if(o<g){const E=i.maxFragLookUpTolerance,T=o>g-E?0:E;f=gs(p,h,Math.max(h[0].start,o),T),!f&&p&&p.start<h[0].start&&(f=h[0])}else f=h[d-1];if(f=this.filterReplacedPrimary(f,s.details),!f)return;const y=f.sn-l.startSN,v=h[y-1];if(v&&v.cc===f.cc&&this.fragmentTracker.getState(v)===Re.NOT_LOADED&&(f=v),this.fragmentTracker.getState(f)===Re.NOT_LOADED){const E=this.mapToInitFragWhenRequired(f);E&&this.loadFragment(E,s,o)}}}loadFragment(e,t,s){xe(e)?super.loadFragment(e,t,s):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new qm(this.tracksBuffered[this.currentTrackId]||[])}}class qm{constructor(e){this.buffered=void 0;const t=(s,i,n)=>{if(i=i>>>0,i>n-1)throw new DOMException(`Failed to execute '${s}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${n})`);return e[i][s]};this.buffered={get length(){return e.length},end(s){return t("end",s,e.length)},start(s){return t("start",s,e.length)}}}}const jm={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},Pc=r=>String.fromCharCode(jm[r]||r),ft=15,Bt=100,Xm={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},zm={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Qm={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Jm={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Zm=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class ep{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const s=typeof t=="function"?t():t;oe.log(`${this.time} [${e}] ${s}`)}}}const ps=function(e){const t=[];for(let s=0;s<e.length;s++)t.push(e[s].toString(16));return t};class wc{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){const t=["foreground","underline","italics","background","flash"];for(let s=0;s<t.length;s++){const i=t[s];e.hasOwnProperty(i)&&(this[i]=e[i])}}isDefault(){return this.foreground==="white"&&!this.underline&&!this.italics&&this.background==="black"&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class tp{constructor(){this.uchar=" ",this.penState=new wc}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return this.uchar===" "&&this.penState.isDefault()}}class sp{constructor(e){this.chars=[],this.pos=0,this.currPenState=new wc,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Bt;t++)this.chars.push(new tp);this.logger=e}equals(e){for(let t=0;t<Bt;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<Bt;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<Bt;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>Bt&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Bt)}moveCursor(e){const t=this.pos+e;if(e>1)for(let s=this.pos+1;s<t+1;s++)this.chars[s].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();const t=Pc(e);if(this.pos>=Bt){this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1)}clearFromPos(e){let t;for(t=e;t<Bt;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let t=!0;for(let s=0;s<Bt;s++){const i=this.chars[s].uchar;i!==" "&&(t=!1),e.push(i)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}class Fn{constructor(e){this.rows=[],this.currRow=ft-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<ft;t++)this.rows.push(new sp(e));this.logger=e}reset(){for(let e=0;e<ft;e++)this.rows[e].clear();this.currRow=ft-1}equals(e){let t=!0;for(let s=0;s<ft;s++)if(!this.rows[s].equals(e.rows[s])){t=!1;break}return t}copy(e){for(let t=0;t<ft;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<ft;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,()=>"pacData = "+ue(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let o=0;o<ft;o++)this.rows[o].clear();const n=this.currRow+1-this.nrRollUpRows,a=this.lastOutputScreen;if(a){const o=a.rows[n].cueStartTime,c=this.logger.time;if(o!==null&&c!==null&&o<c)for(let l=0;l<this.nrRollUpRows;l++)this.rows[t-this.nrRollUpRows+l+1].copy(a.rows[n+l])}}this.currRow=t;const s=this.rows[this.currRow];if(e.indent!==null){const n=e.indent,a=Math.max(n-1,0);s.setCursor(e.indent),e.color=s.chars[a].penState.foreground}const i={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(i)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+ue(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());const e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const t=[];let s="",i=-1;for(let n=0;n<ft;n++){const a=this.rows[n].getTextString();a&&(i=n+1,e?t.push("Row "+i+": '"+a+"'"):t.push(a.trim()))}return t.length>0&&(e?s="["+t.join(" | ")+"]":s=t.join(`
31
- `)),s}getTextAndFormat(){return this.rows}}class kc{constructor(e,t,s){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new Fn(s),this.nonDisplayedMemory=new Fn(s),this.lastOutputScreen=new Fn(s),this.currRollUpRow=this.displayedMemory.rows[ft-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=s}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[ft-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),this.mode==="MODE_POP-ON"?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!=="MODE_ROLL-UP"&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let s=0;s<e.length;s++)this.writeScreen.insertChar(e[s]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+this.writeScreen.getDisplayText(!0)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),this.mode!=="MODE_TEXT"&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),this.mode==="MODE_POP-ON"){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const t={flash:!1};if(t.underline=e%2===1,t.italics=e>=46,t.italics)t.foreground="white";else{const s=Math.floor(e/2)-16,i=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=i[s]}this.logger.log(2,"MIDROW: "+ue(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const t=this.logger.time;t!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=t:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}class Oc{constructor(e,t,s){this.channels=void 0,this.currentChannel=0,this.cmdHistory=rp(),this.logger=void 0;const i=this.logger=new ep;this.channels=[null,new kc(e,t,i),new kc(e+1,s,i)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let s=0;s<t.length;s+=2){const i=t[s]&127,n=t[s+1]&127;let a=!1,o=null;if(i===0&&n===0)continue;this.logger.log(3,()=>"["+ps([t[s],t[s+1]])+"] -> ("+ps([i,n])+")");const c=this.cmdHistory;if(i>=16&&i<=31){if(ip(i,n,c)){cr(null,null,c),this.logger.log(3,()=>"Repeated command ("+ps([i,n])+") is dropped");continue}cr(i,n,this.cmdHistory),a=this.parseCmd(i,n),a||(a=this.parseMidrow(i,n)),a||(a=this.parsePAC(i,n)),a||(a=this.parseBackgroundAttributes(i,n))}else cr(null,null,c);if(!a&&(o=this.parseChars(i,n),o)){const u=this.currentChannel;u&&u>0?this.channels[u].insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!a&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+ps([i,n])+" orig: "+ps([t[s],t[s+1]]))}}parseCmd(e,t){const s=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,i=(e===23||e===31)&&t>=33&&t<=35;if(!(s||i))return!1;const n=e===20||e===21||e===23?1:2,a=this.channels[n];return e===20||e===21||e===28||e===29?t===32?a.ccRCL():t===33?a.ccBS():t===34?a.ccAOF():t===35?a.ccAON():t===36?a.ccDER():t===37?a.ccRU(2):t===38?a.ccRU(3):t===39?a.ccRU(4):t===40?a.ccFON():t===41?a.ccRDC():t===42?a.ccTR():t===43?a.ccRTD():t===44?a.ccEDM():t===45?a.ccCR():t===46?a.ccENM():t===47&&a.ccEOC():a.ccTO(t-32),this.currentChannel=n,!0}parseMidrow(e,t){let s=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?s=1:s=2,s!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const i=this.channels[s];return i?(i.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+ps([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let s;const i=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,n=(e===16||e===24)&&t>=64&&t<=95;if(!(i||n))return!1;const a=e<=23?1:2;t>=64&&t<=95?s=a===1?Xm[e]:Qm[e]:s=a===1?zm[e]:Jm[e];const o=this.channels[a];return o?(o.setPAC(this.interpretPAC(s,t)),this.currentChannel=a,!0):!1}interpretPAC(e,t){let s;const i={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?s=t-96:s=t-64,i.underline=(s&1)===1,s<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(s/2)]:s<=15?(i.italics=!0,i.color="white"):i.indent=Math.floor((s-16)/2)*4,i}parseChars(e,t){let s,i=null,n=null;if(e>=25?(s=2,n=e-8):(s=1,n=e),n>=17&&n<=19){let a;n===17?a=t+80:n===18?a=t+112:a=t+144,this.logger.log(2,()=>"Special char '"+Pc(a)+"' in channel "+s),i=[a]}else e>=32&&e<=127&&(i=t===0?[e]:[e,t]);return i&&this.logger.log(3,()=>"Char codes = "+ps(i).join(",")),i}parseBackgroundAttributes(e,t){const s=(e===16||e===24)&&t>=32&&t<=47,i=(e===23||e===31)&&t>=45&&t<=47;if(!(s||i))return!1;let n;const a={};e===16||e===24?(n=Math.floor((t-32)/2),a.background=Zm[n],t%2===1&&(a.background=a.background+"_semi")):t===45?a.background="transparent":(a.foreground="black",t===47&&(a.underline=!0));const o=e<=23?1:2;return this.channels[o].setBkgData(a),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}cr(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const s=this.channels[t];s&&s.cueSplitAtTime(e)}}}function cr(r,e,t){t.a=r,t.b=e}function ip(r,e,t){return t.a===r&&t.b===e}function rp(){return{a:null,b:null}}var Nn=(function(){if(Yi!=null&&Yi.VTTCue)return self.VTTCue;const r=["","lr","rl"],e=["start","middle","end","left","right"];function t(o,c){if(typeof c!="string"||!Array.isArray(o))return!1;const l=c.toLowerCase();return~o.indexOf(l)?l:!1}function s(o){return t(r,o)}function i(o){return t(e,o)}function n(o,...c){let l=1;for(;l<arguments.length;l++){const u=arguments[l];for(const h in u)o[h]=u[h]}return o}function a(o,c,l){const u=this,h={enumerable:!0};u.hasBeenReset=!1;let d="",g=!1,f=o,p=c,y=l,v=null,E="",T=!0,S="auto",_="start",D=50,I="middle",b=50,A="middle";Object.defineProperty(u,"id",n({},h,{get:function(){return d},set:function(x){d=""+x}})),Object.defineProperty(u,"pauseOnExit",n({},h,{get:function(){return g},set:function(x){g=!!x}})),Object.defineProperty(u,"startTime",n({},h,{get:function(){return f},set:function(x){if(typeof x!="number")throw new TypeError("Start time must be set to a number.");f=x,this.hasBeenReset=!0}})),Object.defineProperty(u,"endTime",n({},h,{get:function(){return p},set:function(x){if(typeof x!="number")throw new TypeError("End time must be set to a number.");p=x,this.hasBeenReset=!0}})),Object.defineProperty(u,"text",n({},h,{get:function(){return y},set:function(x){y=""+x,this.hasBeenReset=!0}})),Object.defineProperty(u,"region",n({},h,{get:function(){return v},set:function(x){v=x,this.hasBeenReset=!0}})),Object.defineProperty(u,"vertical",n({},h,{get:function(){return E},set:function(x){const C=s(x);if(C===!1)throw new SyntaxError("An invalid or illegal string was specified.");E=C,this.hasBeenReset=!0}})),Object.defineProperty(u,"snapToLines",n({},h,{get:function(){return T},set:function(x){T=!!x,this.hasBeenReset=!0}})),Object.defineProperty(u,"line",n({},h,{get:function(){return S},set:function(x){if(typeof x!="number"&&x!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");S=x,this.hasBeenReset=!0}})),Object.defineProperty(u,"lineAlign",n({},h,{get:function(){return _},set:function(x){const C=i(x);if(!C)throw new SyntaxError("An invalid or illegal string was specified.");_=C,this.hasBeenReset=!0}})),Object.defineProperty(u,"position",n({},h,{get:function(){return D},set:function(x){if(x<0||x>100)throw new Error("Position must be between 0 and 100.");D=x,this.hasBeenReset=!0}})),Object.defineProperty(u,"positionAlign",n({},h,{get:function(){return I},set:function(x){const C=i(x);if(!C)throw new SyntaxError("An invalid or illegal string was specified.");I=C,this.hasBeenReset=!0}})),Object.defineProperty(u,"size",n({},h,{get:function(){return b},set:function(x){if(x<0||x>100)throw new Error("Size must be between 0 and 100.");b=x,this.hasBeenReset=!0}})),Object.defineProperty(u,"align",n({},h,{get:function(){return A},set:function(x){const C=i(x);if(!C)throw new SyntaxError("An invalid or illegal string was specified.");A=C,this.hasBeenReset=!0}})),u.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a})();class np{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function Mc(r){function e(s,i,n,a){return(s|0)*3600+(i|0)*60+(n|0)+parseFloat(a||0)}const t=r.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return t?parseFloat(t[2])>59?e(t[2],t[3],0,t[4]):e(t[1],t[2],t[3],t[4]):null}class ap{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t)}get(e,t,s){return s?this.has(e)?this.values[e]:t[s]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,s){for(let i=0;i<s.length;++i)if(t===s[i]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){const s=parseFloat(t);if(s>=0&&s<=100)return this.set(e,s),!0}return!1}}function Fc(r,e,t,s){const i=s?r.split(s):[r];for(const n in i){if(typeof i[n]!="string")continue;const a=i[n].split(t);if(a.length!==2)continue;const o=a[0],c=a[1];e(o,c)}}const $n=new Nn(0,0,""),ur=$n.align==="middle"?"middle":"center";function op(r,e,t){const s=r;function i(){const o=Mc(r);if(o===null)throw new Error("Malformed timestamp: "+s);return r=r.replace(/^[^\sa-zA-Z-]+/,""),o}function n(o,c){const l=new ap;Fc(o,function(d,g){let f;switch(d){case"region":for(let p=t.length-1;p>=0;p--)if(t[p].id===g){l.set(d,t[p].region);break}break;case"vertical":l.alt(d,g,["rl","lr"]);break;case"line":f=g.split(","),l.integer(d,f[0]),l.percent(d,f[0])&&l.set("snapToLines",!1),l.alt(d,f[0],["auto"]),f.length===2&&l.alt("lineAlign",f[1],["start",ur,"end"]);break;case"position":f=g.split(","),l.percent(d,f[0]),f.length===2&&l.alt("positionAlign",f[1],["start",ur,"end","line-left","line-right","auto"]);break;case"size":l.percent(d,g);break;case"align":l.alt(d,g,["start",ur,"end","left","right"]);break}},/:/,/\s/),c.region=l.get("region",null),c.vertical=l.get("vertical","");let u=l.get("line","auto");u==="auto"&&$n.line===-1&&(u=-1),c.line=u,c.lineAlign=l.get("lineAlign","start"),c.snapToLines=l.get("snapToLines",!0),c.size=l.get("size",100),c.align=l.get("align",ur);let h=l.get("position","auto");h==="auto"&&$n.position===50&&(h=c.align==="start"||c.align==="left"?0:c.align==="end"||c.align==="right"?100:50),c.position=h}function a(){r=r.replace(/^\s+/,"")}if(a(),e.startTime=i(),a(),r.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+s);r=r.slice(3),a(),e.endTime=i(),a(),n(r,e)}function Nc(r){return r.replace(/<br(?: \/)?>/gi,`
32
- `)}class lp{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new np,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));function s(){let n=t.buffer,a=0;for(n=Nc(n);a<n.length&&n[a]!=="\r"&&n[a]!==`
33
- `;)++a;const o=n.slice(0,a);return n[a]==="\r"&&++a,n[a]===`
34
- `&&++a,t.buffer=n.slice(a),o}function i(n){Fc(n,function(a,o){},/:/)}try{let n="";if(t.state==="INITIAL"){if(!/\r\n|\n/.test(t.buffer))return this;n=s();const o=n.match(/^()?WEBVTT([ \t].*)?$/);if(!(o!=null&&o[0]))throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let a=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(a?a=!1:n=s(),t.state){case"HEADER":/:/.test(n)?i(n):n||(t.state="ID");continue;case"NOTE":n||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(n)){t.state="NOTE";break}if(!n)continue;if(t.cue=new Nn(0,0,""),t.state="CUE",n.indexOf("-->")===-1){t.cue.id=n;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{op(n,t.cue,t.regionList)}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const o=n.indexOf("-->")!==-1;if(!n||o&&(a=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(t.cue===null)continue;t.cue.text&&(t.cue.text+=`
35
- `),t.cue.text+=n}continue;case"BADCUE":n||(t.state="ID")}}}catch{t.state==="CUETEXT"&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state=t.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||e.state==="HEADER")&&(e.buffer+=`
14
+ ${t.m3u8}
15
+
16
+ Playlist starting @${n.startSN}
17
+ ${n.m3u8}`)}function ic(e,t,n=!0){let r=t.startSN+t.skippedSegments-e.startSN,i=e.fragments,a=r>=0,o=0;if(a&&r<i.length)o=i[r].start;else if(a&&t.startSN===e.endSN+1)o=e.fragmentEnd;else if(a&&n)o=e.fragmentStart+r*t.levelTargetDuration;else if(!t.skippedSegments&&t.fragmentStart===0)o=e.fragmentStart;else return;ac(t,o)}function ac(e,t){if(t){let n=e.fragments;for(let r=e.skippedSegments;r<n.length;r++)n[r].addStart(t);e.fragmentHint&&e.fragmentHint.addStart(t)}}function oc(e,t=1/0){let n=1e3*e.targetduration;if(e.updated){let r=e.fragments;if(r.length&&n*4>t){let e=r[r.length-1].duration*1e3;e<n&&(n=e)}}else n/=2;return Math.round(n)}function sc(e,t,n){if(!e)return null;let r=e.fragments[t-e.startSN];return r||(r=e.fragmentHint,r&&r.sn===t)?r:t<e.startSN&&n&&n.sn===t?n:null}function cc(e,t,n){return e?lc(e.partList,t,n):null}function lc(e,t,n){if(e)for(let r=e.length;r--;){let i=e[r];if(i.index===n&&i.fragment.sn===t)return i}return null}function uc(e){e.forEach((e,t)=>{var n;(n=e.details)==null||n.fragments.forEach(e=>{e.level=t,e.initSegment&&(e.initSegment.level=t)})})}function dc(e,t){return e!==t&&t?fc(e)!==fc(t):!1}function fc(e){return e.replace(/\?[^?]*$/,``)}function pc(e,t){for(let n=0,r=e.length;n<r;n++)if(e[n]?.cc===t)return e[n];return null}function mc(e,t){return!!(e&&t.startCC<e.endCC&&t.endCC>e.startCC)}function hc(e,t){let n=e.start+t;e.startPTS=n,e.setStart(n),e.endPTS=n+e.duration}function gc(e,t){let n=t.fragments;for(let t=0,r=n.length;t<r;t++)hc(n[t],e);t.fragmentHint&&hc(t.fragmentHint,e),t.alignedSliding=!0}function _c(e,t){e&&(vc(t,e),t.alignedSliding||yc(t,e),!t.alignedSliding&&!t.skippedSegments&&ic(e,t,!1))}function vc(e,t){if(!mc(t,e))return;let n=Math.min(t.endCC,e.endCC),r=pc(t.fragments,n),i=pc(e.fragments,n);!r||!i||(G.log(`Aligning playlist at start of dicontinuity sequence ${n}`),gc(r.start-i.start,e))}function yc(e,t){if(!e.hasProgramDateTime||!t.hasProgramDateTime)return;let n=e.fragments,r=t.fragments;if(!n.length||!r.length)return;let i,a,o=Math.min(t.endCC,e.endCC);t.startCC<o&&e.startCC<o&&(i=pc(r,o),a=pc(n,o)),(!i||!a)&&(i=r[Math.floor(r.length/2)],a=pc(n,i.cc)||n[Math.floor(n.length/2)]);let s=i.programDateTime,c=a.programDateTime;!s||!c||gc((c-s)/1e3-(a.start-i.start),e)}function bc(e,t,n){xc(e,t,n),e.addEventListener(t,n)}function xc(e,t,n){e.removeEventListener(t,n)}var Sc={toString:function(e){let t=``,n=e.length;for(let r=0;r<n;r++)t+=`[${e.start(r).toFixed(3)}-${e.end(r).toFixed(3)}]`;return t}},Z={STOPPED:`STOPPED`,IDLE:`IDLE`,KEY_LOADING:`KEY_LOADING`,FRAG_LOADING:`FRAG_LOADING`,FRAG_LOADING_WAITING_RETRY:`FRAG_LOADING_WAITING_RETRY`,WAITING_TRACK:`WAITING_TRACK`,PARSING:`PARSING`,PARSED:`PARSED`,ENDED:`ENDED`,ERROR:`ERROR`,WAITING_INIT_PTS:`WAITING_INIT_PTS`,WAITING_LEVEL:`WAITING_LEVEL`},Cc=class extends Wo{constructor(e,t,n,r,i){super(r,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=Z.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{let{config:e,fragCurrent:t,media:n,mediaBuffer:r,state:i}=this,a=n?n.currentTime:0,o=X.bufferInfo(r||n,a,e.maxBufferHole),s=!o.len;if(this.log(`Media seeking to ${L(a)?a.toFixed(3):a}, state: ${i}, ${s?`out of`:`in`} buffer`),this.state===Z.ENDED)this.resetLoadingState();else if(t){let n=e.maxFragLookUpTolerance,r=t.start-n,i=t.start+t.duration+n;if(s||i<o.start||r>o.end){let e=a>i;(a<r||e)&&(e&&t.loader&&(this.log(`Cancelling fragment load for seek (sn: ${t.sn})`),t.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(n&&(this.fragmentTracker.removeFragmentsInRange(a,1/0,this.playlistType,!0),a>this.lastCurrentTime&&(this.lastCurrentTime=a),!this.loadingParts)){let e=Math.max(o.end,a),t=this.shouldLoadParts(this.getLevelDetails(),e);t&&(this.log(`LL-Part loading ON after seeking to ${a.toFixed(2)} with buffer @${e.toFixed(2)}`),this.loadingParts=t)}this.hls.hasEnoughToStart||(this.log(`Setting ${s?`startPosition`:`nextLoadPosition`} to ${a} for seek without enough to start`),this.nextLoadPosition=a,s&&(this.startPosition=a)),s&&this.state===Z.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log(`setting startPosition to 0 because media ended`),this.startPosition=this.lastCurrentTime=0},this.playlistType=i,this.hls=e,this.fragmentLoader=new zo(e.config),this.keyLoader=n,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Lo(e.config)}registerListeners(){let{hls:e}=this;e.on(B.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(B.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(B.MANIFEST_LOADING,this.onManifestLoading,this),e.on(B.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(B.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(B.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(B.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(B.MANIFEST_LOADING,this.onManifestLoading,this),e.off(B.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(B.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===Z.STOPPED)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);let e=this.fragCurrent;e!=null&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=Z.STOPPED}get startPositionValue(){let{nextLoadPosition:e,startPosition:t}=this;return t===-1&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;let n=e.end||0,r=this.config.timelineOffset||0;if(n<=r)return!1;let i=e.buffered;this.config.maxBufferHole&&i&&i.length>1&&(e=X.bufferedInfo(i,e.start,0));let a=e.nextStart;if(a&&a>r&&a<t.edge||this.media.currentTime<e.start)return!1;let o=t.partList;if(o!=null&&o.length){let e=o[o.length-1];return X.isBuffered(this.media,e.start+e.duration/2)}let s=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(s)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){let e=this.config.timelineOffset;return e?this.getLevelDetails()?.appliedTimelineOffset||e:0}onMediaAttached(e,t){let n=this.media=this.mediaBuffer=t.media;bc(n,`seeking`,this.onMediaSeeking),bc(n,`ended`,this.onMediaEnded);let r=this.config;this.levels&&r.autoStartLoad&&this.state===Z.STOPPED&&this.startLoad(r.startPosition)}onMediaDetaching(e,t){let n=!!t.transferMedia,r=this.media;if(r!==null){if(r.ended&&(this.log(`MSE detaching and video ended, reset startPosition`),this.startPosition=this.lastCurrentTime=0),xc(r,`seeking`,this.onMediaSeeking),xc(r,`ended`,this.onMediaEnded),this.keyLoader&&!n&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,n){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&=(this.transmuxer.destroy(),null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=Z.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,n){this.startFragRequested=!0,this._loadFragForPlayback(e,t,n)}_loadFragForPlayback(e,t,n){this._doFragLoad(e,t,n,e=>{let t=e.frag;if(this.fragContextChanged(t)){this.warn(`${t.type} sn: ${t.sn}${e.part?` part: `+e.part.index:``} of ${this.fragInfo(t,!1,e.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(t);return}t.stats.chunkCount++,this._handleFragmentLoadProgress(e)}).then(e=>{if(!e)return;let t=this.state,n=e.frag;if(this.fragContextChanged(n)){(t===Z.FRAG_LOADING||!this.fragCurrent&&t===Z.PARSING)&&(this.fragmentTracker.removeFragment(n),this.state=Z.IDLE);return}`payload`in e&&(this.log(`Loaded ${n.type} sn: ${n.sn} of ${this.playlistLabel()} ${n.level}`),this.hls.trigger(B.FRAG_LOADED,e)),this._handleFragmentLoadComplete(e)}).catch(t=>{this.state===Z.STOPPED||this.state===Z.ERROR||(this.warn(`Frag error: ${t?.message||t}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){let{fragmentTracker:t}=this;if(t.getState(e)===To.APPENDING){let n=e.type,r=this.getFwdBufferInfo(this.mediaBuffer,n),i=Math.max(e.duration,r?r.len:this.config.maxBufferLength),a=this.backtrackFragment;((a?e.sn-a.sn:0)===1||this.reduceMaxBufferLength(i,e.duration))&&t.removeFragment(e)}else this.mediaBuffer?.buffered.length===0?t.removeAllFragments():t.hasParts(e.type)&&(t.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),t.getState(e)===To.PARTIAL&&t.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){let t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){let t=e.details;return t?.live&&t.type!==`EVENT`&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,n=null){if(!(e-t))return;let r={startOffset:e,endOffset:t,type:n};this.hls.trigger(B.BUFFER_FLUSHING,r)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(e=>{let t=e?.frag;if(!t||this.fragContextChanged(t)||!this.levels)throw Error(`init load aborted`);return e}).then(e=>{let{hls:t}=this,{frag:n,payload:r}=e,i=n.decryptdata;if(r&&r.byteLength>0&&i!=null&&i.key&&i.iv&&us(i.method)){let a=self.performance.now();return this.decrypter.decrypt(new Uint8Array(r),i.key.buffer,i.iv.buffer,ds(i.method)).catch(e=>{throw t.trigger(B.ERROR,{type:R.MEDIA_ERROR,details:z.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:n}),e}).then(r=>{let i=self.performance.now();return t.trigger(B.FRAG_DECRYPTED,{frag:n,payload:r,stats:{tstart:a,tdecrypt:i}}),e.payload=r,this.completeInitSegmentLoad(e)})}return this.completeInitSegmentLoad(e)}).catch(t=>{this.state===Z.STOPPED||this.state===Z.ERROR||(this.warn(t),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){let{levels:t}=this;if(!t)throw Error(`init load aborted, missing levels`);let n=e.frag.stats;this.state!==Z.STOPPED&&(this.state=Z.IDLE),e.frag.data=new Uint8Array(e.payload),n.parsing.start=n.buffering.start=self.performance.now(),n.parsing.end=n.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var n,r;let i=e.tracks;if(i&&!t.encrypted&&((n=i.audio)!=null&&n.encrypted||(r=i.video)!=null&&r.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){let e=this.media,n=Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${e?`attached mediaKeys: `+e.mediaKeys:`detached`})`);return this.warn(n.message),!e||e.mediaKeys?!1:(this.hls.trigger(B.ERROR,{type:R.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_NO_KEYS,fatal:!1,error:n,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){let{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){let n=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?` part: `+t.index:``} of ${this.fragInfo(e,!1,t)} > buffer:${n?Sc.toString(X.getBuffered(n)):`(detached)`})`),vi(e)){if(e.type!==H.SUBTITLE){let t=e.elementaryStreams;if(!Object.keys(t).some(e=>!!t[e])){this.state=Z.IDLE;return}}let t=this.levels?.[e.level];t!=null&&t.fragmentError&&(this.log(`Resetting level fragment error count of ${t.fragmentError} on frag buffered`),t.fragmentError=0)}this.state=Z.IDLE}_handleFragmentLoadComplete(e){let{transmuxer:t}=this;if(!t)return;let{frag:n,part:r,partsLoaded:i}=e,a=!i||i.length===0||i.some(e=>!e),o=new Go(n.level,n.sn,n.stats.chunkCount+1,0,r?r.index:-1,!a);t.flush(o)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,n=null,r){var i;this.fragCurrent=e;let a=t.details;if(!this.levels||!a)throw Error(`frag load aborted, missing level${a?``:` detail`}s`);let o=null;if(e.encrypted&&!((i=e.decryptdata)!=null&&i.key)){if(this.log(`Loading key for ${e.sn} of [${a.startSN}-${a.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=Z.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then(e=>{if(!this.fragContextChanged(e.frag))return this.hls.trigger(B.KEY_LOADED,e),this.state===Z.KEY_LOADING&&(this.state=Z.IDLE),e}),this.hls.trigger(B.KEY_LOADING,{frag:e}),this.fragCurrent===null)return this.log(`context changed in KEY_LOADING`),Promise.resolve(null)}else e.encrypted||(o=this.keyLoader.loadClear(e,a.encryptedFragments,this.startFragRequested),o&&this.log(`[eme] blocking frag load until media-keys acquired`));let s=this.fragPrevious;if(vi(e)&&(!s||e.sn!==s.sn)){let n=this.shouldLoadParts(t.details,e.end);n!==this.loadingParts&&(this.log(`LL-Part loading ${n?`ON`:`OFF`} loading sn ${s?.sn}->${e.sn}`),this.loadingParts=n)}if(n=Math.max(e.start,n||0),this.loadingParts&&vi(e)){let i=a.partList;if(i&&r){n>a.fragmentEnd&&a.fragmentHint&&(e=a.fragmentHint);let s=this.getNextPart(i,e,n);if(s>-1){let c=i[s];e=this.fragCurrent=c.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${c.index} (${s}/${i.length-1}) of ${this.fragInfo(e,!1,c)}) cc: ${e.cc} [${a.startSN}-${a.endSN}], target: ${parseFloat(n.toFixed(3))}`),this.nextLoadPosition=c.start+c.duration,this.state=Z.FRAG_LOADING;let l;return l=o?o.then(n=>!n||this.fragContextChanged(n.frag)?null:this.doFragPartsLoad(e,c,t,r)).catch(e=>this.handleFragLoadError(e)):this.doFragPartsLoad(e,c,t,r).catch(e=>this.handleFragLoadError(e)),this.hls.trigger(B.FRAG_LOADING,{frag:e,part:c,targetBufferTime:n}),this.fragCurrent===null?Promise.reject(Error(`frag load aborted, context changed in FRAG_LOADING parts`)):l}else if(!e.url||this.loadedEndOfParts(i,n))return Promise.resolve(null)}}if(vi(e)&&this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${n.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${a.partList?.filter(e=>e.loaded).map(e=>`[${e.start}-${e.end}]`)}`),this.loadingParts=!1;else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${`[`+a.startSN+`-`+a.endSN+`]`}, target: ${parseFloat(n.toFixed(3))}`),L(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=Z.FRAG_LOADING;let c=this.config.progressive&&e.type!==H.SUBTITLE,l;return l=c&&o?o.then(t=>!t||this.fragContextChanged(t.frag)?null:this.fragmentLoader.load(e,r)).catch(e=>this.handleFragLoadError(e)):Promise.all([this.fragmentLoader.load(e,c?r:void 0),o]).then(([e])=>(!c&&r&&r(e),e)).catch(e=>this.handleFragLoadError(e)),this.hls.trigger(B.FRAG_LOADING,{frag:e,targetBufferTime:n}),this.fragCurrent===null?Promise.reject(Error(`frag load aborted, context changed in FRAG_LOADING`)):l}doFragPartsLoad(e,t,n,r){return new Promise((i,a)=>{let o=[],s=n.details?.partList,c=t=>{this.fragmentLoader.loadPart(e,t,r).then(r=>{o[t.index]=r;let a=r.part;this.hls.trigger(B.FRAG_LOADED,r);let l=cc(n.details,e.sn,t.index+1)||lc(s,e.sn,t.index+1);if(l)c(l);else return i({frag:e,part:a,partsLoaded:o})}).catch(a)};c(t)})}handleFragLoadError(e){if(`data`in e){let t=e.data;t.frag&&t.details===z.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===R.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(B.ERROR,t)}else this.hls.trigger(B.ERROR,{type:R.OTHER_ERROR,details:z.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){let t=this.getCurrentContext(e);if(!t||this.state!==Z.PARSING){!this.fragCurrent&&this.state!==Z.STOPPED&&this.state!==Z.ERROR&&(this.state=Z.IDLE);return}let{frag:n,part:r,level:i}=t,a=self.performance.now();n.stats.parsing.end=a,r&&(r.stats.parsing.end=a);let o=this.getLevelDetails(),s=o&&n.sn>o.endSN||this.shouldLoadParts(o,n.end);s!==this.loadingParts&&(this.log(`LL-Part loading ${s?`ON`:`OFF`} after parsing segment ending @${n.end.toFixed(2)}`),this.loadingParts=s),this.updateLevelTiming(n,r,i,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){let n=e.partList[0];if(n.fragment.type===H.SUBTITLE)return!1;if(t>=n.end+(e.fragmentHint?.duration||0)&&(this.hls.hasEnoughToStart?this.media?.currentTime||this.lastCurrentTime:this.getLoadPosition())>n.start-n.fragment.duration)return!0}}return!1}getCurrentContext(e){let{levels:t,fragCurrent:n}=this,{level:r,sn:i,part:a}=e;if(!(t!=null&&t[r]))return this.warn(`Levels object was unset while buffering fragment ${i} of ${this.playlistLabel()} ${r}. The current chunk will not be buffered.`),null;let o=t[r],s=o.details,c=a>-1?cc(s,i,a):null,l=c?c.fragment:sc(s,i,n);return l?(n&&n!==l&&(l.stats=n.stats),{frag:l,part:c,level:o}):null}bufferFragmentData(e,t,n,r,i){if(this.state!==Z.PARSING)return;let{data1:a,data2:o}=e,s=a;if(o&&(s=Gi(a,o)),!s.length)return;let c=this.initPTS[t.cc],l=c?-c.baseTime/c.timescale:void 0,u={type:e.type,frag:t,part:n,chunkMeta:r,offset:l,parent:t.type,data:s};if(this.hls.trigger(B.BUFFER_APPENDING,u),e.dropped&&e.independent&&!n){if(i)return;this.flushBufferGap(t)}}flushBufferGap(e){let t=this.media;if(!t)return;if(!X.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}let n=t.currentTime,r=X.bufferInfo(t,n,0),i=e.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,i*.25),o=Math.max(Math.min(e.start-a,r.end-a),n+a);e.start-o>a&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){var n;let r=this.getLoadPosition();if(!L(r))return null;let i=this.lastCurrentTime>r||(n=this.media)!=null&&n.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,r,t,i)}getFwdBufferInfoAtPos(e,t,n,r){let i=X.bufferInfo(e,t,r);if(i.len===0&&i.nextStart!==void 0){let a=this.fragmentTracker.getBufferedFrag(t,n);if(a&&(i.nextStart<=a.end||a.gap)){let n=Math.max(Math.min(i.nextStart,a.end)-t,r);return X.bufferInfo(e,t,n)}}return i}getMaxBufferLength(e){let{config:t}=this,n;return n=e?Math.max(8*t.maxBufferSize/e,t.maxBufferLength):t.maxBufferLength,Math.min(n,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){let n=this.config,r=Math.max(Math.min(e-t,n.maxBufferLength),t),i=Math.max(e-t*3,n.maxMaxBufferLength/2,r);return i>=r?(n.maxMaxBufferLength=i,this.warn(`Reduce max buffer length to ${i}s`),!0):!1}getAppendedFrag(e,t=H.MAIN){let n=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return n&&`fragment`in n?n.fragment:n}getNextFragment(e,t){let n=t.fragments,r=n.length;if(!r)return null;let{config:i}=this,a=n[0].start,o=i.lowLatencyMode&&!!t.partList,s=null;if(t.live){let n=i.initialLiveManifestSize;if(r<n)return this.warn(`Not enough fragments to start playback (have: ${r}, need: ${n})`),null;if(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<a){o&&!this.loadingParts&&(this.log(`LL-Part loading ON for initial live fragment`),this.loadingParts=!0),s=this.getInitialLiveFragment(t);let n=this.hls.startPosition,r=this.hls.liveSyncPosition,i=s?(n!==-1&&n>=a?n:r)||s.start:e;this.log(`Setting startPosition to ${i} to match start frag at live edge. mainStart: ${n} liveSyncPosition: ${r} frag.start: ${s?.start}`),this.startPosition=this.nextLoadPosition=i}}else e<=a&&(s=n[0]);if(!s){let n=this.loadingParts?t.partEnd:t.fragmentEnd;s=this.getFragmentAtPosition(e,n,t)}let c=this.filterReplacedPrimary(s,t);if(!c&&s){let e=s.sn-t.startSN;c=this.filterReplacedPrimary(n[e+1]||null,t)}return this.mapToInitFragWhenRequired(c)}isLoopLoading(e,t){let n=this.fragmentTracker.getState(e);return(n===To.OK||n===To.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,n,r,i){let a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t),a&&!a.gap&&n.nextStart)){let e=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,n.nextStart,r,0);if(e!==null&&n.len+e.len>=i){let e=a.sn;return this.loopSn!==e&&(this.log(`buffer full after gaps in "${r}" playlist starting at sn: ${e}`),this.loopSn=e),null}}return this.loopSn=void 0,a}get primaryPrefetch(){if(wc(this.config)){var e;if(!((e=this.hls.interstitialsManager)==null||(e=e.playingItem)==null)&&e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(wc(this.config)&&e.type!==H.SUBTITLE){let n=this.hls.interstitialsManager,r=n?.bufferingItem;if(r){let n=r.event;if(n){if(n.appendInPlace||Math.abs(e.start-r.start)>1||r.start===0)return null}else if(e.end<=r.start&&t?.live===!1||e.start>r.end&&r.nextEvent&&(r.nextEvent.appendInPlace||e.start-r.end>1))return null}let i=n?.playerQueue;if(i)for(let t=i.length;t--;){let n=i[t].interstitial;if(n.appendInPlace&&e.start>=n.startTime&&e.end<=n.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!e.initSegment.data&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,n){let r=-1,i=!1,a=!0;for(let o=0,s=e.length;o<s;o++){let s=e[o];if(a&&=!s.independent,r>-1&&n<s.start)break;let c=s.loaded;c?r=-1:(i||(s.independent||a)&&s.fragment===t)&&(s.fragment!==t&&this.warn(`Need buffer at ${n} but next unloaded part starts at ${s.start}`),r=o),i=c}return r}loadedEndOfParts(e,t){let n;for(let r=e.length;r--;){if(n=e[r],!n.loaded)return!1;if(t>n.start)return!0}return!1}getInitialLiveFragment(e){let t=e.fragments,n=this.fragPrevious,r=null;if(n){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${n.programDateTime}`),r=ao(t,n.endProgramDateTime,this.config.maxFragLookUpTolerance)),!r){let i=n.sn+1;if(i>=e.startSN&&i<=e.endSN){let a=t[i-e.startSN];n.cc===a.cc&&(r=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${r.sn}`))}r||(r=uo(e,n.cc,n.end),r&&this.log(`Live playlist, switching playlist, load frag with same CC: ${r.sn}`))}}else{let t=this.hls.liveSyncPosition;t!==null&&(r=this.getFragmentAtPosition(t,this.bitrateTest?e.fragmentEnd:e.edge,e))}return r}getFragmentAtPosition(e,t,n){let{config:r}=this,{fragPrevious:i}=this,{fragments:a,endSN:o}=n,{fragmentHint:s}=n,{maxFragLookUpTolerance:c}=r,l=n.partList,u=!!(this.loadingParts&&l!=null&&l.length&&s);u&&!this.bitrateTest&&l[l.length-1].fragment.sn===s.sn&&(a=a.concat(s),o=s.sn);let d;if(e<t){var f;let n=e<this.lastCurrentTime||e>t-c||(f=this.media)!=null&&f.paused||!this.startFragRequested?0:c;d=oo(i,a,e,n)}else d=a[a.length-1];if(d){let e=d.sn-n.startSN,t=this.fragmentTracker.getState(d);if((t===To.OK||t===To.PARTIAL&&d.gap)&&(i=d),i&&d.sn===i.sn&&(!u||l[0].fragment.sn>d.sn||!n.live)&&d.level===i.level){let t=a[e+1];d=d.sn<o&&this.fragmentTracker.getState(t)!==To.OK?t:null}}return d}alignPlaylists(e,t,n){let r=e.fragments.length;if(!r)return this.warn(`No fragments in live playlist`),0;let i=e.fragmentStart,a=!t,o=e.alignedSliding&&L(i);if(a||!o&&!i){_c(n,e);let i=e.fragmentStart;return this.log(`Live playlist sliding: ${i.toFixed(2)} start-sn: ${t?t.startSN:`na`}->${e.startSN} fragments: ${r}`),i}return i}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let n=this.startPosition;n<t&&(n=-1);let r=this.timelineOffset;if(n===-1){let i=this.startTimeOffset!==null,a=i?this.startTimeOffset:e.startTimeOffset;a!==null&&L(a)?(n=t+a,a<0&&(n+=e.edge),n=Math.min(Math.max(t,n),t+e.totalduration),this.log(`Setting startPosition to ${n} for start time offset ${a} found in ${i?`multivariant`:`media`} playlist`),this.startPosition=n):e.live?(n=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${n}`),this.startPosition=-1):(this.log(`setting startPosition to 0 by default`),this.startPosition=n=0),this.lastCurrentTime=n+r}this.nextLoadPosition=n+r}getLoadPosition(){var e;let{media:t}=this,n=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t?n=t.currentTime:this.nextLoadPosition>=0&&(n=this.nextLoadPosition),n}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&vi(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?` part `+t.index:``} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==Z.FRAG_LOADING_WAITING_RETRY)&&(this.state=Z.IDLE)}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){let e=this.getCurrentContext(t.chunkMeta);e&&(t.frag=e.frag)}let n=t.frag;if(!n||n.type!==e||!this.levels)return;if(this.fragContextChanged(n)){this.warn(`Frag load error must match current frag to retry ${n.url} > ${this.fragCurrent?.url}`);return}let r=t.details===z.FRAG_GAP;r&&this.fragmentTracker.fragBuffered(n,!0);let i=t.errorAction;if(!i){this.state=Z.ERROR;return}let{action:a,flags:o,retryCount:s=0,retryConfig:c}=i,l=!!c,u=l&&a===xo.RetryRequest,d=l&&!i.resolved&&o===So.MoveAllAlternatesMatchingHost,f=this.hls.latestLevelDetails?.live;if(!u&&d&&vi(n)&&!n.endList&&f&&!mo(t))this.resetFragmentErrors(e),this.treatAsGap(n),i.resolved=!0;else if((u||d)&&s<c.maxNumRetry){let r=bo(t.response?.code),a=go(c,s);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+a,this.state=Z.FRAG_LOADING_WAITING_RETRY,i.resolved=!0,r){this.log(`Waiting for connection (offline)`),this.retryDate=1/0,t.reason=`offline`;return}this.warn(`Fragment ${n.sn} of ${e} ${n.level} errored with ${t.details}, retrying loading ${s+1}/${c.maxNumRetry} in ${a}ms`)}else if(c)if(this.resetFragmentErrors(e),s<c.maxNumRetry)!r&&a!==xo.RemoveAlternatePermanently&&(i.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${s})`);return}else a===xo.SendAlternateToPenaltyBox?this.state=Z.WAITING_LEVEL:this.state=Z.ERROR;this.tickImmediate()}checkRetryDate(){let e=self.performance.now(),t=this.retryDate,n=t===1/0;(!t||e>=t||n&&!bo(0))&&(n&&this.log(`Connection restored (online)`),this.resetStartWhenNotLoaded(),this.state=Z.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===Z.PARSING||this.state===Z.PARSED){let t=e.frag,n=e.parent,r=this.getFwdBufferInfo(this.mediaBuffer,n),i=r&&r.len>.5;i&&this.reduceMaxBufferLength(r.len,t?.duration||10);let a=!i;return a&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${n} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1}resetFragmentErrors(e){e===H.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==Z.STOPPED&&(this.state=Z.IDLE)}afterBufferFlushed(e,t,n){if(!e)return;let r=X.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,r,n),this.state===Z.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log(`Reset loading state`),this.fragCurrent=null,this.fragPrevious=null,this.state!==Z.STOPPED&&(this.state=Z.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;let e=this.levelLastLoaded,t=e?e.details:null;t!=null&&t.live?(this.log(`resetting startPosition for live start`),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${e.level===-1?`<removed>`:e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,n,r){let i=n.details;if(!i){this.warn(`level.details undefined`);return}if(!Object.keys(e.elementaryStreams).reduce((t,a)=>{let o=e.elementaryStreams[a];if(o){let s=o.endPTS-o.startPTS;if(s<=0)return this.warn(`Could not parse fragment ${e.sn} ${a} duration reliably (${s})`),t||!1;let c=r?0:Qs(i,e,o.startPTS,o.endPTS,o.startDTS,o.endDTS,this);return this.hls.trigger(B.LEVEL_PTS_UPDATED,{details:i,level:n,drift:c,type:a,frag:e,start:o.startPTS,end:o.endPTS}),!0}return t},!1)){let t=this.transmuxer?.error===null;if((n.fragmentError===0||t&&(n.fragmentError<2||e.endList))&&this.treatAsGap(e,n),t){let t=Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(t.message),this.hls.trigger(B.ERROR,{type:R.MEDIA_ERROR,details:z.FRAG_PARSING_ERROR,fatal:!1,error:t,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${n.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=Z.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?` part: `+t.index:``} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(B.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===H.MAIN?`level`:`track`}fragInfo(e,t=!0,n){return`${this.playlistLabel()} ${e.level} (${n?`part`:`frag`}:[${((t&&!n?e.startPTS:(n||e).start)??NaN).toFixed(3)}-${((t&&!n?e.endPTS:(n||e).end)??NaN).toFixed(3)}]${n&&e.type===`main`?`INDEPENDENT=`+(n.independent?`YES`:`NO`):``}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}recoverWorkerError(e){e.event===`demuxerWorker`&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&=(this.transmuxer.destroy(),null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){let t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}};function wc(e){return!!e.interstitialsController&&e.enableInterstitialPlayback!==!1}var Tc=class{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){let{chunks:e,dataLength:t}=this,n;if(e.length)n=e.length===1?e[0]:Ec(e,t);else return new Uint8Array;return this.reset(),n}reset(){this.chunks.length=0,this.dataLength=0}};function Ec(e,t){let n=new Uint8Array(t),r=0;for(let t=0;t<e.length;t++){let i=e[t];n.set(i,r),r+=i.length}return n}var Dc={exports:{}},Oc;function kc(){return Oc?Dc.exports:(Oc=1,(function(e){var t=Object.prototype.hasOwnProperty,n=`~`;function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1));function i(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function a(e,t,r,a,o){if(typeof r!=`function`)throw TypeError(`The listener must be a function`);var s=new i(r,a||e,o),c=n?n+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],s]:e._events[c].push(s):(e._events[c]=s,e._eventsCount++),e}function o(e,t){--e._eventsCount===0?e._events=new r:delete e._events[t]}function s(){this._events=new r,this._eventsCount=0}s.prototype.eventNames=function(){var e=[],r,i;if(this._eventsCount===0)return e;for(i in r=this._events)t.call(r,i)&&e.push(n?i.slice(1):i);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(r)):e},s.prototype.listeners=function(e){var t=n?n+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var i=0,a=r.length,o=Array(a);i<a;i++)o[i]=r[i].fn;return o},s.prototype.listenerCount=function(e){var t=n?n+e:e,r=this._events[t];return r?r.fn?1:r.length:0},s.prototype.emit=function(e,t,r,i,a,o){var s=n?n+e:e;if(!this._events[s])return!1;var c=this._events[s],l=arguments.length,u,d;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,r),!0;case 4:return c.fn.call(c.context,t,r,i),!0;case 5:return c.fn.call(c.context,t,r,i,a),!0;case 6:return c.fn.call(c.context,t,r,i,a,o),!0}for(d=1,u=Array(l-1);d<l;d++)u[d-1]=arguments[d];c.fn.apply(c.context,u)}else{var f=c.length,p;for(d=0;d<f;d++)switch(c[d].once&&this.removeListener(e,c[d].fn,void 0,!0),l){case 1:c[d].fn.call(c[d].context);break;case 2:c[d].fn.call(c[d].context,t);break;case 3:c[d].fn.call(c[d].context,t,r);break;case 4:c[d].fn.call(c[d].context,t,r,i);break;default:if(!u)for(p=1,u=Array(l-1);p<l;p++)u[p-1]=arguments[p];c[d].fn.apply(c[d].context,u)}}return!0},s.prototype.on=function(e,t,n){return a(this,e,t,n,!1)},s.prototype.once=function(e,t,n){return a(this,e,t,n,!0)},s.prototype.removeListener=function(e,t,r,i){var a=n?n+e:e;if(!this._events[a])return this;if(!t)return o(this,a),this;var s=this._events[a];if(s.fn)s.fn===t&&(!i||s.once)&&(!r||s.context===r)&&o(this,a);else{for(var c=0,l=[],u=s.length;c<u;c++)(s[c].fn!==t||i&&!s[c].once||r&&s[c].context!==r)&&l.push(s[c]);l.length?this._events[a]=l.length===1?l[0]:l:o(this,a)}return this},s.prototype.removeAllListeners=function(e){var t;return e?(t=n?n+e:e,this._events[t]&&o(this,t)):(this._events=new r,this._eventsCount=0),this},s.prototype.off=s.prototype.removeListener,s.prototype.addListener=s.prototype.on,s.prefixed=n,s.EventEmitter=s,e.exports=s})(Dc),Dc.exports)}var Ac=di(kc()),jc=`1.6.15`,Mc={};function Nc(){return typeof __HLS_WORKER_BUNDLE__==`function`}function Pc(){let e=Mc[jc];if(e)return e.clientCount++,e;let t=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:`text/javascript`}),n=self.URL.createObjectURL(t),r={worker:new self.Worker(n),objectURL:n,clientCount:1};return Mc[jc]=r,r}function Fc(e){let t=Mc[e];if(t)return t.clientCount++,t;let n=new self.URL(e,self.location.href).href,r={worker:new self.Worker(n),scriptURL:n,clientCount:1};return Mc[e]=r,r}function Ic(e){let t=Mc[e||jc];if(t&&t.clientCount--===1){let{worker:n,objectURL:r}=t;delete Mc[e||jc],r&&self.URL.revokeObjectURL(r),n.terminate()}}function Lc(e,t){return t+10<=e.length&&e[t]===51&&e[t+1]===68&&e[t+2]===73&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function Rc(e,t){return t+10<=e.length&&e[t]===73&&e[t+1]===68&&e[t+2]===51&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function zc(e,t){let n=0;return n=(e[t]&127)<<21,n|=(e[t+1]&127)<<14,n|=(e[t+2]&127)<<7,n|=e[t+3]&127,n}function Bc(e,t){let n=t,r=0;for(;Rc(e,t);){r+=10;let n=zc(e,t+6);r+=n,Lc(e,t+10)&&(r+=10),t+=r}if(r>0)return e.subarray(n,n+r)}function Vc(e,t,n,r){let i=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],a=t[n+2],o=a>>2&15;if(o>12){let t=Error(`invalid ADTS sampling index:${o}`);e.emit(B.ERROR,B.ERROR,{type:R.MEDIA_ERROR,details:z.FRAG_PARSING_ERROR,fatal:!0,error:t,reason:t.message});return}let s=(a>>6&3)+1,c=t[n+3]>>6&3|(a&1)<<2,l=`mp4a.40.`+s,u=i[o],d=o;(s===5||s===29)&&(d-=3);let f=[s<<3|(d&14)>>1,(d&1)<<7|c<<3];return G.log(`manifest codec:${r}, parsed codec:${l}, channels:${c}, rate:${u} (ADTS object type:${s} sampling index:${o})`),{config:f,samplerate:u,channelCount:c,codec:l,parsedCodec:l,manifestCodec:r}}function Hc(e,t){return e[t]===255&&(e[t+1]&246)==240}function Uc(e,t){return e[t+1]&1?7:9}function Wc(e,t){return(e[t+3]&3)<<11|e[t+4]<<3|(e[t+5]&224)>>>5}function Gc(e,t){return t+5<e.length}function Kc(e,t){return t+1<e.length&&Hc(e,t)}function qc(e,t){return Gc(e,t)&&Hc(e,t)&&Wc(e,t)<=e.length-t}function Jc(e,t){if(Kc(e,t)){let n=Uc(e,t);if(t+n>=e.length)return!1;let r=Wc(e,t);if(r<=n)return!1;let i=t+r;return i===e.length||Kc(e,i)}return!1}function Yc(e,t,n,r,i){if(!e.samplerate){let a=Vc(t,n,r,i);if(!a)return;U(e,a)}}function Xc(e){return 1024*9e4/e}function Zc(e,t){let n=Uc(e,t);if(t+n<=e.length){let r=Wc(e,t)-n;if(r>0)return{headerLength:n,frameLength:r}}}function Qc(e,t,n,r,i){let a=r+i*Xc(e.samplerate),o=Zc(t,n),s;if(o){let{frameLength:r,headerLength:i}=o,c=i+r,l=Math.max(0,n+c-t.length);l?(s=new Uint8Array(c-i),s.set(t.subarray(n+i,t.length),0)):s=t.subarray(n+i,n+c);let u={unit:s,pts:a};return l||e.samples.push(u),{sample:u,length:c,missing:l}}let c=t.length-n;return s=new Uint8Array(c),s.set(t.subarray(n,t.length),0),{sample:{unit:s,pts:a},length:c,missing:-1}}function $c(e,t){return Rc(e,t)&&zc(e,t+6)+10<=e.length-t}function el(e){return e instanceof ArrayBuffer?e:e.byteOffset==0&&e.byteLength==e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer}function tl(e,t=0,n=1/0){return nl(e,t,n,Uint8Array)}function nl(e,t,n,r){let i=rl(e),a=1;`BYTES_PER_ELEMENT`in r&&(a=r.BYTES_PER_ELEMENT);let o=il(e)?e.byteOffset:0,s=(o+e.byteLength)/a,c=(o+t)/a,l=Math.floor(Math.max(0,Math.min(c,s)));return new r(i,l,Math.floor(Math.min(l+Math.max(n,0),s))-l)}function rl(e){return e instanceof ArrayBuffer?e:e.buffer}function il(e){return e&&e.buffer instanceof ArrayBuffer&&e.byteLength!==void 0&&e.byteOffset!==void 0}function al(e){let t={key:e.type,description:``,data:``,mimeType:null,pictureType:null};if(e.size<2)return;if(e.data[0]!==3){console.log(`Ignore frame with unrecognized character encoding`);return}let n=e.data.subarray(1).indexOf(0);if(n===-1)return;let r=ci(tl(e.data,1,n)),i=e.data[2+n],a=e.data.subarray(3+n).indexOf(0);if(a===-1)return;let o=ci(tl(e.data,3+n,a)),s;return s=r===`-->`?ci(tl(e.data,4+n+a)):el(e.data.subarray(4+n+a)),t.mimeType=r,t.pictureType=i,t.description=o,t.data=s,t}function ol(e){if(e.size<2)return;let t=ci(e.data,!0),n=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:n.buffer}}function sl(e){if(e.size<2)return;if(e.type===`TXXX`){let t=1,n=ci(e.data.subarray(t),!0);t+=n.length+1;let r=ci(e.data.subarray(t));return{key:e.type,info:n,data:r}}let t=ci(e.data.subarray(1));return{key:e.type,info:``,data:t}}function cl(e){if(e.type===`WXXX`){if(e.size<2)return;let t=1,n=ci(e.data.subarray(t),!0);t+=n.length+1;let r=ci(e.data.subarray(t));return{key:e.type,info:n,data:r}}let t=ci(e.data);return{key:e.type,info:``,data:t}}function ll(e){return e.type===`PRIV`?ol(e):e.type[0]===`W`?cl(e):e.type===`APIC`?al(e):sl(e)}function ul(e){let t=String.fromCharCode(e[0],e[1],e[2],e[3]),n=zc(e,4);return{type:t,size:n,data:e.subarray(10,10+n)}}var dl=10,fl=10;function pl(e){let t=0,n=[];for(;Rc(e,t);){let r=zc(e,t+6);e[t+5]>>6&1&&(t+=dl),t+=dl;let i=t+r;for(;t+fl<i;){let r=ul(e.subarray(t)),i=ll(r);i&&n.push(i),t+=r.size+dl}Lc(e,t)&&(t+=dl)}return n}function ml(e){return e&&e.key===`PRIV`&&e.info===`com.apple.streaming.transportStreamTimestamp`}function hl(e){if(e.data.byteLength===8){let t=new Uint8Array(e.data),n=t[3]&1,r=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return r/=45,n&&(r+=47721858.84),Math.round(r)}}function gl(e){let t=pl(e);for(let e=0;e<t.length;e++){let n=t[e];if(ml(n))return hl(n)}}var _l=function(e){return e.audioId3=`org.id3`,e.dateRange=`com.apple.quicktime.HLS`,e.emsg=`https://aomedia.org/emsg/ID3`,e.misbklv=`urn:misb:KLV:bin:1910.1`,e}({});function vl(e=``,t=9e4){return{type:e,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}var yl=class{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,n,r){this._id3Track={type:`id3`,id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,n){}demux(e,t){this.cachedData&&=(e=Gi(this.cachedData,e),null);let n=Bc(e,0),r=n?n.length:0,i,a=this._audioTrack,o=this._id3Track,s=n?gl(n):void 0,c=e.length;for((this.basePTS===null||this.frameIndex===0&&L(s))&&(this.basePTS=bl(s,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),n&&n.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:_l.audioId3,duration:1/0});r<c;){if(this.canParse(e,r)){let t=this.appendFrame(a,e,r);t?(this.frameIndex++,this.lastPTS=t.sample.pts,r+=t.length,i=r):r=c}else $c(e,r)?(n=Bc(e,r),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:_l.audioId3,duration:1/0}),r+=n.length,i=r):r++;if(r===c&&i!==c){let t=e.slice(i);this.cachedData?this.cachedData=Gi(this.cachedData,t):this.cachedData=t}}return{audioTrack:a,videoTrack:vl(),id3Track:o,textTrack:vl()}}demuxSampleAes(e,t,n){return Promise.reject(Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){let t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:vl(),id3Track:this._id3Track,textTrack:vl()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}},bl=(e,t,n)=>{if(L(e))return e*90;let r=n?n.baseTime*9e4/n.timescale:0;return t*9e4+r},xl=null,Sl=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],Cl=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],wl=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Tl=[0,1,1,4];function El(e,t,n,r,i){if(n+24>t.length)return;let a=Dl(t,n);if(a&&n+a.frameLength<=t.length){let o=r+i*(a.samplesPerFrame*9e4/a.sampleRate),s={unit:t.subarray(n,n+a.frameLength),pts:o,dts:o};return e.config=[],e.channelCount=a.channelCount,e.samplerate=a.sampleRate,e.samples.push(s),{sample:s,length:a.frameLength,missing:0}}}function Dl(e,t){let n=e[t+1]>>3&3,r=e[t+1]>>1&3,i=e[t+2]>>4&15,a=e[t+2]>>2&3;if(n!==1&&i!==0&&i!==15&&a!==3){let o=e[t+2]>>1&1,s=e[t+3]>>6,c=Sl[(n===3?3-r:r===3?3:4)*14+i-1]*1e3,l=Cl[(n===3?0:n===2?1:2)*3+a],u=s===3?1:2,d=wl[n][r],f=Tl[r],p=d*8*f,m=Math.floor(d*c/l+o)*f;if(xl===null){let e=(navigator.userAgent||``).match(/Chrome\/(\d+)/i);xl=e?parseInt(e[1]):0}return xl&&xl<=87&&r===2&&c>=224e3&&s===0&&(e[t+3]=e[t+3]|128),{sampleRate:l,channelCount:u,frameLength:m,samplesPerFrame:p}}}function Ol(e,t){return e[t]===255&&(e[t+1]&224)==224&&(e[t+1]&6)!=0}function kl(e,t){return t+1<e.length&&Ol(e,t)}function Al(e,t){return Ol(e,t)&&4<=e.length-t}function jl(e,t){if(t+1<e.length&&Ol(e,t)){let n=Dl(e,t),r=4;n!=null&&n.frameLength&&(r=n.frameLength);let i=t+r;return i===e.length||kl(e,i)}return!1}var Ml=class extends yl{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,n,r){super.resetInitSegment(e,t,n,r),this._audioTrack={container:`audio/adts`,type:`audio`,id:2,pid:-1,sequenceNumber:0,segmentCodec:`aac`,samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;let n=Bc(e,0)?.length||0;if(jl(e,n))return!1;for(let r=e.length;n<r;n++)if(Jc(e,n))return t.log(`ADTS sync word found !`),!0;return!1}canParse(e,t){return qc(e,t)}appendFrame(e,t,n){Yc(e,this.observer,t,n,e.manifestCodec);let r=Qc(e,t,n,this.basePTS,this.frameIndex);if(r&&r.missing===0)return r}},Nl=(e,t)=>{let n=0,r=5;t+=r;let i=new Uint32Array(1),a=new Uint32Array(1),o=new Uint8Array(1);for(;r>0;){o[0]=e[t];let s=Math.min(r,8),c=8-s;a[0]=4278190080>>>24+c<<c,i[0]=(o[0]&a[0])>>c,n=n?n<<s|i[0]:i[0],t+=1,r-=s}return n},Pl=class extends yl{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,n,r){super.resetInitSegment(e,t,n,r),this._audioTrack={container:`audio/ac-3`,type:`audio`,id:2,pid:-1,sequenceNumber:0,segmentCodec:`ac3`,samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,n){let r=Fl(e,t,n,this.basePTS,this.frameIndex);if(r!==-1)return{sample:e.samples[e.samples.length-1],length:r,missing:0}}static probe(e){if(!e)return!1;let t=Bc(e,0);if(!t)return!1;let n=t.length;return e[n]===11&&e[n+1]===119&&gl(t)!==void 0&&Nl(e,n)<16}};function Fl(e,t,n,r,i){if(n+8>t.length||t[n]!==11||t[n+1]!==119)return-1;let a=t[n+4]>>6;if(a>=3)return-1;let o=[48e3,44100,32e3][a],s=t[n+4]&63,c=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][s*3+a]*2;if(n+c>t.length)return-1;let l=t[n+6]>>5,u=0;l===2?u+=2:(l&1&&l!==1&&(u+=2),l&4&&(u+=2));let d=(t[n+6]<<8|t[n+7])>>12-u&1,f=[2,1,2,3,3,4,4,5][l]+d,p=t[n+5]>>3,m=t[n+5]&7,h=new Uint8Array([a<<6|p<<1|m>>2,(m&3)<<6|l<<3|d<<2|s>>4,s<<4&224]),g=r+i*(1536/o*9e4),_=t.subarray(n,n+c);return e.config=h,e.channelCount=f,e.samplerate=o,e.samples.push({unit:_,pts:g}),c}var Il=class extends yl{resetInitSegment(e,t,n,r){super.resetInitSegment(e,t,n,r),this._audioTrack={container:`audio/mpeg`,type:`audio`,id:2,pid:-1,sequenceNumber:0,segmentCodec:`mp3`,samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;let t=Bc(e,0),n=t?.length||0;if(t&&e[n]===11&&e[n+1]===119&&gl(t)!==void 0&&Nl(e,n)<=16)return!1;for(let t=e.length;n<t;n++)if(jl(e,n))return G.log(`MPEG Audio sync word found !`),!0;return!1}canParse(e,t){return Al(e,t)}appendFrame(e,t,n){if(this.basePTS!==null)return El(e,t,n,this.basePTS,this.frameIndex)}},Ll=/\/emsg[-/]ID3/i,Rl=class{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,n,r){let i=this.videoTrack=vl(`video`,1),a=this.audioTrack=vl(`audio`,1),o=this.txtTrack=vl(`text`,1);if(this.id3Track=vl(`id3`,1),this.timeOffset=0,!(e!=null&&e.byteLength))return;let s=Mi(e);if(s.video){let{id:e,timescale:t,codec:n,supplemental:r}=s.video;i.id=e,i.timescale=o.timescale=t,i.codec=n,i.supplemental=r}if(s.audio){let{id:e,timescale:t,codec:n}=s.audio;a.id=e,a.timescale=t,a.codec=n}o.id=Ti.text,i.sampleDuration=0,i.duration=a.duration=r}resetContiguity(){this.remainderData=null}static probe(e){return Ai(e)}demux(e,t){this.timeOffset=t;let n=e,r=this.videoTrack,i=this.txtTrack;if(this.config.progressive){this.remainderData&&(n=Gi(this.remainderData,e));let t=Wi(n);this.remainderData=t.remainder,r.samples=t.valid||new Uint8Array}else r.samples=n;let a=this.extractID3Track(r,t);return i.samples=Ki(t,r),{videoTrack:r,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack}}flush(){let e=this.timeOffset,t=this.videoTrack,n=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;let r=this.extractID3Track(t,this.timeOffset);return n.samples=Ki(e,t),{videoTrack:t,audioTrack:vl(),id3Track:r,textTrack:vl()}}extractID3Track(e,t){let n=this.id3Track;if(e.samples.length){let r=J(e.samples,[`emsg`]);r&&r.forEach(e=>{let r=Zi(e);if(Ll.test(r.schemeIdUri)){let e=zl(r,t),i=r.eventDuration===4294967295?1/0:r.eventDuration/r.timeScale;i<=.001&&(i=1/0);let a=r.payload;n.samples.push({data:a,len:a.byteLength,dts:e,pts:e,type:_l.emsg,duration:i})}else if(this.config.enableEmsgKLVMetadata&&r.schemeIdUri.startsWith(`urn:misb:KLV:bin:1910.1`)){let e=zl(r,t);n.samples.push({data:r.payload,len:r.payload.byteLength,dts:e,pts:e,type:_l.misbklv,duration:1/0})}})}return n}demuxSampleAes(e,t,n){return Promise.reject(Error(`The MP4 demuxer does not support SAMPLE-AES decryption`))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}};function zl(e,t){return L(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}var Bl=class{constructor(e,t,n){this.keyData=void 0,this.decrypter=void 0,this.keyData=n,this.decrypter=new Lo(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,Ao.cbc)}decryptAacSample(e,t,n){let r=e[t].unit;if(r.length<=16)return;let i=r.subarray(16,r.length-r.length%16),a=i.buffer.slice(i.byteOffset,i.byteOffset+i.length);this.decryptBuffer(a).then(i=>{let a=new Uint8Array(i);r.set(a,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,n)}).catch(n)}decryptAacSamples(e,t,n){for(;;t++){if(t>=e.length){n();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,n),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){let t=Math.floor((e.length-48)/160)*16+16,n=new Int8Array(t),r=0;for(let t=32;t<e.length-16;t+=160,r+=16)n.set(e.subarray(t,t+16),r);return n}getAvcDecryptedUnit(e,t){let n=new Uint8Array(t),r=0;for(let t=32;t<e.length-16;t+=160,r+=16)e.set(n.subarray(r,r+16),t);return e}decryptAvcSample(e,t,n,r,i){let a=Xi(i.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then(o=>{i.data=this.getAvcDecryptedUnit(a,o),this.decrypter.isSync()||this.decryptAvcSamples(e,t,n+1,r)}).catch(r)}decryptAvcSamples(e,t,n,r){if(e instanceof Uint8Array)throw Error(`Cannot decrypt samples of type Uint8Array`);for(;;t++,n=0){if(t>=e.length){r();return}let i=e[t].units;for(;!(n>=i.length);n++){let a=i[n];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(e,t,n,r,a),!this.decrypter.isSync()))return}}}},Vl=class{constructor(){this.VideoSample=null}createVideoSample(e,t,n){return{key:e,frame:!1,pts:t,dts:n,units:[],length:0}}getLastNalUnit(e){var t;let n=this.VideoSample,r;if((!n||n.units.length===0)&&(n=e[e.length-1]),(t=n)!=null&&t.units){let e=n.units;r=e[e.length-1]}return r}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){let n=t.samples,r=n.length;if(r){let t=n[r-1];e.pts=t.pts,e.dts=t.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,n){let r=t.byteLength,i=e.naluState||0,a=i,o=[],s=0,c,l,u,d=-1,f=0;for(i===-1&&(d=0,f=this.getNALuType(t,0),i=0,s=1);s<r;){if(c=t[s++],!i){i=c?0:1;continue}if(i===1){i=c?0:2;continue}if(!c)i=3;else if(c===1){if(l=s-i-1,d>=0){let e={data:t.subarray(d,l),type:f};o.push(e)}else{let n=this.getLastNalUnit(e.samples);n&&(a&&s<=4-a&&n.state&&(n.data=n.data.subarray(0,n.data.byteLength-a)),l>0&&(n.data=Gi(n.data,t.subarray(0,l)),n.state=0))}s<r?(u=this.getNALuType(t,s),d=s,f=u,i=0):i=-1}else i=0}if(d>=0&&i>=0){let e={data:t.subarray(d,r),type:f,state:i};o.push(e)}if(o.length===0){let n=this.getLastNalUnit(e.samples);n&&(n.data=Gi(n.data,t))}return e.naluState=i,o}},Hl=class{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){let e=this.data,t=this.bytesAvailable,n=e.byteLength-t,r=new Uint8Array(4),i=Math.min(4,t);if(i===0)throw Error(`no bytes available`);r.set(e.subarray(n,n+i)),this.word=new DataView(r.buffer).getUint32(0),this.bitsAvailable=i*8,this.bytesAvailable-=i}skipBits(e){let t;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e),n=this.word>>>32-t;if(e>32&&G.error(`Cannot read more than 32 bits at a time`),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw Error(`no bits available`);return t=e-t,t>0&&this.bitsAvailable?n<<t|this.readBits(t):n}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){let e=this.skipLZ();return this.readBits(e+1)-1}readEG(){let e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}},Ul=class extends Vl{parsePES(e,t,n,r){let i=this.parseNALu(e,n.data,r),a=this.VideoSample,o,s=!1;n.data=null,a&&i.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts)),i.forEach(r=>{var i,c;switch(r.type){case 1:{let t=!1;o=!0;let i=r.data;if(s&&i.length>4){let e=this.readSliceType(i);(e===2||e===4||e===7||e===9)&&(t=!0)}if(t){var l;(l=a)!=null&&l.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts),a.frame=!0,a.key=t;break}case 5:o=!0,(i=a)!=null&&i.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts),a.key=!0,a.frame=!0;break;case 6:o=!0,Yi(r.data,1,n.pts,t.samples);break;case 7:{o=!0,s=!0;let t=r.data,n=this.readSPS(t);if(!e.sps||e.width!==n.width||e.height!==n.height||e.pixelRatio?.[0]!==n.pixelRatio[0]||e.pixelRatio?.[1]!==n.pixelRatio[1]){e.width=n.width,e.height=n.height,e.pixelRatio=n.pixelRatio,e.sps=[t];let r=t.subarray(1,4),i=`avc1.`;for(let e=0;e<3;e++){let t=r[e].toString(16);t.length<2&&(t=`0`+t),i+=t}e.codec=i}break}case 8:o=!0,e.pps=[r.data];break;case 9:o=!0,e.audFound=!0,(c=a)!=null&&c.frame&&(this.pushAccessUnit(a,e),a=null),a||=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts);break;case 12:o=!0;break;default:o=!1;break}a&&o&&a.units.push(r)}),r&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){let t=new Hl(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let n=8,r=8,i;for(let a=0;a<e;a++)r!==0&&(i=t.readEG(),r=(n+i+256)%256),n=r===0?n:r}readSPS(e){let t=new Hl(e),n=0,r=0,i=0,a=0,o,s,c,l=t.readUByte.bind(t),u=t.readBits.bind(t),d=t.readUEG.bind(t),f=t.readBoolean.bind(t),p=t.skipBits.bind(t),m=t.skipEG.bind(t),h=t.skipUEG.bind(t),g=this.skipScalingList.bind(this);l();let _=l();if(u(5),p(3),l(),h(),_===100||_===110||_===122||_===244||_===44||_===83||_===86||_===118||_===128){let e=d();if(e===3&&p(1),h(),h(),p(1),f())for(s=e===3?12:8,c=0;c<s;c++)f()&&g(c<6?16:64,t)}h();let v=d();if(v===0)d();else if(v===1)for(p(1),m(),m(),o=d(),c=0;c<o;c++)m();h(),p(1);let y=d(),b=d(),x=u(1);x===0&&p(1),p(1),f()&&(n=d(),r=d(),i=d(),a=d());let S=[1,1];if(f()&&f())switch(l()){case 1:S=[1,1];break;case 2:S=[12,11];break;case 3:S=[10,11];break;case 4:S=[16,11];break;case 5:S=[40,33];break;case 6:S=[24,11];break;case 7:S=[20,11];break;case 8:S=[32,11];break;case 9:S=[80,33];break;case 10:S=[18,11];break;case 11:S=[15,11];break;case 12:S=[64,33];break;case 13:S=[160,99];break;case 14:S=[4,3];break;case 15:S=[3,2];break;case 16:S=[2,1];break;case 255:S=[l()<<8|l(),l()<<8|l()];break}return{width:Math.ceil((y+1)*16-n*2-r*2),height:(2-x)*(b+1)*16-(x?2:4)*(i+a),pixelRatio:S}}},Wl=class extends Vl{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,n,r){let i=this.parseNALu(e,n.data,r),a=this.VideoSample,o,s=!1;n.data=null,a&&i.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts)),i.forEach(r=>{var i,c;switch(r.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts),a.frame=!0,o=!0;break;case 16:case 17:case 18:case 21:if(o=!0,s){var l;(l=a)!=null&&l.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts),a.key=!0,a.frame=!0;break;case 19:case 20:o=!0,(i=a)!=null&&i.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts),a.key=!0,a.frame=!0;break;case 39:o=!0,Yi(r.data,2,n.pts,t.samples);break;case 32:o=!0,e.vps||(typeof e.params!=`object`&&(e.params={}),e.params=U(e.params,this.readVPS(r.data)),this.initVPS=r.data),e.vps=[r.data];break;case 33:if(o=!0,s=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],r.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){let t=this.readSPS(r.data);e.width=t.width,e.height=t.height,e.pixelRatio=t.pixelRatio,e.codec=t.codecString,e.sps=[],typeof e.params!=`object`&&(e.params={});for(let n in t.params)e.params[n]=t.params[n]}this.pushParameterSet(e.sps,r.data,e.vps),a||=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts),a.key=!0;break;case 34:if(o=!0,typeof e.params==`object`){if(!e.pps){e.pps=[];let t=this.readPPS(r.data);for(let n in t)e.params[n]=t[n]}this.pushParameterSet(e.pps,r.data,e.vps)}break;case 35:o=!0,e.audFound=!0,(c=a)!=null&&c.frame&&(this.pushAccessUnit(a,e),a=null),a||=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts);break;default:o=!1;break}a&&o&&a.units.push(r)}),r&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}pushParameterSet(e,t,n){(n&&n[0]===this.initVPS||!n&&!e.length)&&e.push(t)}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){let t=new Uint8Array(e.byteLength),n=0;for(let r=0;r<e.byteLength;r++)r>=2&&e[r]===3&&e[r-1]===0&&e[r-2]===0||(t[n]=e[r],n++);return new Uint8Array(t.buffer,0,n)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&=null}readVPS(e){let t=new Hl(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);let n=t.readBits(3),r=t.readBoolean();return{numTemporalLayers:n+1,temporalIdNested:r}}readSPS(e){let t=new Hl(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);let n=t.readBits(3);t.readBoolean();let r=t.readBits(2),i=t.readBoolean(),a=t.readBits(5),o=t.readUByte(),s=t.readUByte(),c=t.readUByte(),l=t.readUByte(),u=t.readUByte(),d=t.readUByte(),f=t.readUByte(),p=t.readUByte(),m=t.readUByte(),h=t.readUByte(),g=t.readUByte(),_=[],v=[];for(let e=0;e<n;e++)_.push(t.readBoolean()),v.push(t.readBoolean());if(n>0)for(let e=n;e<8;e++)t.readBits(2);for(let e=0;e<n;e++)_[e]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),v[e]&&t.readUByte();t.readUEG();let y=t.readUEG();y==3&&t.skipBits(1);let b=t.readUEG(),x=t.readUEG(),S=t.readBoolean(),C=0,w=0,T=0,E=0;S&&(C+=t.readUEG(),w+=t.readUEG(),T+=t.readUEG(),E+=t.readUEG());let ee=t.readUEG(),D=t.readUEG(),te=t.readUEG(),ne=t.readBoolean();for(let e=ne?0:n;e<=n;e++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(let e=0;e<4;e++)for(let n=0;n<(e===3?2:6);n++)if(!t.readBoolean())t.readUEG();else{let n=Math.min(64,1<<4+(e<<1));e>1&&t.readEG();for(let e=0;e<n;e++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());let O=t.readUEG(),k=0;for(let e=0;e<O;e++){let n=!1;if(e!==0&&(n=t.readBoolean()),n){e===O&&t.readUEG(),t.readBoolean(),t.readUEG();let n=0;for(let e=0;e<=k;e++){let e=t.readBoolean(),r=!1;e||(r=t.readBoolean()),(e||r)&&n++}k=n}else{let e=t.readUEG(),n=t.readUEG();k=e+n;for(let n=0;n<e;n++)t.readUEG(),t.readBoolean();for(let e=0;e<n;e++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){let e=t.readUEG();for(let n=0;n<e;n++){for(let e=0;e<te+4;e++)t.readBits(1);t.readBits(1)}}let re=0,ie=1,ae=1,oe=!0,se=1,ce=0;t.readBoolean(),t.readBoolean();let le=!1;if(t.readBoolean()){if(t.readBoolean()){let e=t.readUByte();e>0&&e<16?(ie=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][e-1],ae=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][e-1]):e===255&&(ie=t.readBits(16),ae=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),le=t.readBoolean(),le&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(se=t.readBits(32),ce=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){let e=t.readBoolean(),r=t.readBoolean(),i=!1;(e||r)&&(i=t.readBoolean(),i&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),i&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let a=0;a<=n;a++){oe=t.readBoolean();let n=oe||t.readBoolean(),a=!1;n?t.readEG():a=t.readBoolean();let o=a?1:t.readUEG()+1;if(e)for(let e=0;e<o;e++)t.readUEG(),t.readUEG(),i&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(r)for(let e=0;e<o;e++)t.readUEG(),t.readUEG(),i&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),re=t.readUEG())}let ue=b,de=x;if(S){let e=1,t=1;y===1?e=t=2:y==2&&(e=2),ue=b-e*w-e*C,de=x-t*E-t*T}let fe=r?[`A`,`B`,`C`][r]:``,pe=o<<24|s<<16|c<<8|l,me=0;for(let e=0;e<32;e++)me=(me|(pe>>e&1)<<31-e)>>>0;let he=me.toString(16);return a===1&&he===`2`&&(he=`6`),{codecString:`hvc1.${fe}${a}.${he}.${i?`H`:`L`}${g}.B0`,params:{general_tier_flag:i,general_profile_idc:a,general_profile_space:r,general_profile_compatibility_flags:[o,s,c,l],general_constraint_indicator_flags:[u,d,f,p,m,h],general_level_idc:g,bit_depth:ee+8,bit_depth_luma_minus8:ee,bit_depth_chroma_minus8:D,min_spatial_segmentation_idc:re,chroma_format_idc:y,frame_rate:{fixed:oe,fps:ce/se}},width:ue,height:de,pixelRatio:[ie,ae]}}readPPS(e){let t=new Hl(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);let n=t.readBoolean(),r=t.readBoolean(),i=1;return r&&n?i=0:r?i=3:n&&(i=2),{parallelismType:i}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}},Gl=188,Kl=class e{constructor(e,t,n,r){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=n,this.logger=r,this.videoParser=null}static probe(t,n){let r=e.syncOffset(t);return r>0&&n.warn(`MPEG2-TS detected but first sync word found @ offset ${r}`),r!==-1}static syncOffset(e){let t=e.length,n=Math.min(Gl*5,t-Gl)+1,r=0;for(;r<n;){let i=!1,a=-1,o=0;for(let s=r;s<t;s+=Gl)if(e[s]===71&&(t-s===Gl||e[s+Gl]===71)){if(o++,a===-1&&(a=s,a!==0&&(n=Math.min(a+Gl*99,e.length-Gl)+1)),i||=ql(e,s)===0,i&&o>1&&(a===0&&o>2||s+Gl>n))return a}else if(o)return-1;else break;r++}return-1}static createTrack(e,t){return{container:e===`video`||e===`audio`?`video/mp2t`:void 0,type:e,id:Ti[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e===`audio`?t:void 0}}resetInitSegment(t,n,r,i){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=e.createTrack(`video`),this._videoTrack.duration=i,this._audioTrack=e.createTrack(`audio`,i),this._id3Track=e.createTrack(`id3`),this._txtTrack=e.createTrack(`text`),this._audioTrack.segmentCodec=`aac`,this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=n,this.videoCodec=r}resetTimeStamp(){}resetContiguity(){let{_audioTrack:e,_videoTrack:t,_id3Track:n}=this;e&&(e.pesData=null),t&&(t.pesData=null),n&&(n.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(t,n,r=!1,i=!1){r||(this.sampleAes=null);let a,o=this._videoTrack,s=this._audioTrack,c=this._id3Track,l=this._txtTrack,u=o.pid,d=o.pesData,f=s.pid,p=c.pid,m=s.pesData,h=c.pesData,g=null,_=this.pmtParsed,v=this._pmtId,y=t.length;if(this.remainderData&&=(t=Gi(this.remainderData,t),y=t.length,null),y<Gl&&!i)return this.remainderData=t,{audioTrack:s,videoTrack:o,id3Track:c,textTrack:l};let b=Math.max(0,e.syncOffset(t));y-=(y-b)%Gl,y<t.byteLength&&!i&&(this.remainderData=new Uint8Array(t.buffer,y,t.buffer.byteLength-y));let x=0;for(let e=b;e<y;e+=Gl)if(t[e]===71){let n=!!(t[e+1]&64),i=ql(t,e),y=(t[e+3]&48)>>4,x;if(y>1){if(x=e+5+t[e+4],x===e+Gl)continue}else x=e+4;switch(i){case u:n&&(d&&(a=Ql(d,this.logger))&&(this.readyVideoParser(o.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(o,l,a,!1)),d={data:[],size:0}),d&&(d.data.push(t.subarray(x,e+Gl)),d.size+=e+Gl-x);break;case f:if(n){if(m&&(a=Ql(m,this.logger)))switch(s.segmentCodec){case`aac`:this.parseAACPES(s,a);break;case`mp3`:this.parseMPEGPES(s,a);break;case`ac3`:this.parseAC3PES(s,a);break}m={data:[],size:0}}m&&(m.data.push(t.subarray(x,e+Gl)),m.size+=e+Gl-x);break;case p:n&&(h&&(a=Ql(h,this.logger))&&this.parseID3PES(c,a),h={data:[],size:0}),h&&(h.data.push(t.subarray(x,e+Gl)),h.size+=e+Gl-x);break;case 0:n&&(x+=t[x]+1),v=this._pmtId=Jl(t,x);break;case v:{n&&(x+=t[x]+1);let i=Yl(t,x,this.typeSupported,r,this.observer,this.logger);u=i.videoPid,u>0&&(o.pid=u,o.segmentCodec=i.segmentVideoCodec),f=i.audioPid,f>0&&(s.pid=f,s.segmentCodec=i.segmentAudioCodec),p=i.id3Pid,p>0&&(c.pid=p),g!==null&&!_&&(this.logger.warn(`MPEG-TS PMT found at ${e} after unknown PID '${g}'. Backtracking to sync byte @${b} to parse all TS packets.`),g=null,e=b-188),_=this.pmtParsed=!0;break}case 17:case 8191:break;default:g=i;break}}else x++;x>0&&Xl(this.observer,Error(`Found ${x} TS packet/s that do not start with 0x47`),void 0,this.logger),o.pesData=d,s.pesData=m,c.pesData=h;let S={audioTrack:s,videoTrack:o,id3Track:c,textTrack:l};return i&&this.extractRemainingSamples(S),S}flush(){let{remainderData:e}=this;this.remainderData=null;let t;return t=e?this.demux(e,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){let{audioTrack:t,videoTrack:n,id3Track:r,textTrack:i}=e,a=n.pesData,o=t.pesData,s=r.pesData,c;if(a&&(c=Ql(a,this.logger))?(this.readyVideoParser(n.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(n,i,c,!0),n.pesData=null)):n.pesData=a,o&&(c=Ql(o,this.logger))){switch(t.segmentCodec){case`aac`:this.parseAACPES(t,c);break;case`mp3`:this.parseMPEGPES(t,c);break;case`ac3`:this.parseAC3PES(t,c);break}t.pesData=null}else o!=null&&o.size&&this.logger.log(`last AAC PES packet truncated,might overlap between fragments`),t.pesData=o;s&&(c=Ql(s,this.logger))?(this.parseID3PES(r,c),r.pesData=null):r.pesData=s}demuxSampleAes(e,t,n){let r=this.demux(e,n,!0,!this.config.progressive),i=this.sampleAes=new Bl(this.observer,this.config,t);return this.decrypt(r,i)}readyVideoParser(e){this.videoParser===null&&(e===`avc`?this.videoParser=new Ul:e===`hevc`&&(this.videoParser=new Wl))}decrypt(e,t){return new Promise(n=>{let{audioTrack:r,videoTrack:i}=e;r.samples&&r.segmentCodec===`aac`?t.decryptAacSamples(r.samples,0,()=>{i.samples?t.decryptAvcSamples(i.samples,0,0,()=>{n(e)}):n(e)}):i.samples&&t.decryptAvcSamples(i.samples,0,0,()=>{n(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(e,t){let n=0,r=this.aacOverFlow,i=t.data;if(r){this.aacOverFlow=null;let t=r.missing,a=r.sample.unit.byteLength;if(t===-1)i=Gi(r.sample.unit,i);else{let o=a-t;r.sample.unit.set(i.subarray(0,t),o),e.samples.push(r.sample),n=r.missing}}let a,o;for(a=n,o=i.length;a<o-1&&!Kc(i,a);a++);if(a!==n){let e,t=a<o-1;if(e=t?`AAC PES did not start with ADTS header,offset:${a}`:`No ADTS header found in AAC PES`,Xl(this.observer,Error(e),t,this.logger),!t)return}Yc(e,this.observer,i,a,this.audioCodec);let s;if(t.pts!==void 0)s=t.pts;else if(r){let t=Xc(e.samplerate);s=r.sample.pts+t}else{this.logger.warn(`[tsdemuxer]: AAC PES unknown PTS`);return}let c=0,l;for(;a<o;)if(l=Qc(e,i,a,s,c),a+=l.length,l.missing){this.aacOverFlow=l;break}else for(c++;a<o-1&&!Kc(i,a);a++);}parseMPEGPES(e,t){let n=t.data,r=n.length,i=0,a=0,o=t.pts;if(o===void 0){this.logger.warn(`[tsdemuxer]: MPEG PES unknown PTS`);return}for(;a<r;)if(kl(n,a)){let t=El(e,n,a,o,i);if(t)a+=t.length,i++;else break}else a++}parseAC3PES(e,t){{let n=t.data,r=t.pts;if(r===void 0){this.logger.warn(`[tsdemuxer]: AC3 PES unknown PTS`);return}let i=n.length,a=0,o=0,s;for(;o<i&&(s=Fl(e,n,o,r,a++))>0;)o+=s}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn(`[tsdemuxer]: ID3 PES unknown PTS`);return}let n=U({},t,{type:this._videoTrack?_l.emsg:_l.audioId3,duration:1/0});e.samples.push(n)}};function ql(e,t){return((e[t+1]&31)<<8)+e[t+2]}function Jl(e,t){return(e[t+10]&31)<<8|e[t+11]}function Yl(e,t,n,r,i,a){let o={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:`avc`,segmentAudioCodec:`aac`},s=(e[t+1]&15)<<8|e[t+2],c=t+3+s-4,l=(e[t+10]&15)<<8|e[t+11];for(t+=12+l;t<c;){let s=ql(e,t),c=(e[t+3]&15)<<8|e[t+4];switch(e[t]){case 207:if(!r){Zl(`ADTS AAC`,a);break}case 15:o.audioPid===-1&&(o.audioPid=s);break;case 21:o.id3Pid===-1&&(o.id3Pid=s);break;case 219:if(!r){Zl(`H.264`,a);break}case 27:o.videoPid===-1&&(o.videoPid=s);break;case 3:case 4:!n.mpeg&&!n.mp3?a.log(`MPEG audio found, not supported in this browser`):o.audioPid===-1&&(o.audioPid=s,o.segmentAudioCodec=`mp3`);break;case 193:if(!r){Zl(`AC-3`,a);break}case 129:n.ac3?o.audioPid===-1&&(o.audioPid=s,o.segmentAudioCodec=`ac3`):a.log(`AC-3 audio found, not supported in this browser`);break;case 6:if(o.audioPid===-1&&c>0){let r=t+5,i=c;for(;i>2;){switch(e[r]){case 106:n.ac3===!0?(o.audioPid=s,o.segmentAudioCodec=`ac3`):a.log(`AC-3 audio found, not supported in this browser for now`);break}let t=e[r+1]+2;r+=t,i-=t}}break;case 194:case 135:return Xl(i,Error(`Unsupported EC-3 in M2TS found`),void 0,a),o;case 36:o.videoPid===-1&&(o.videoPid=s,o.segmentVideoCodec=`hevc`,a.log(`HEVC in M2TS found`));break}t+=c+5}return o}function Xl(e,t,n,r){r.warn(`parsing error: ${t.message}`),e.emit(B.ERROR,B.ERROR,{type:R.MEDIA_ERROR,details:z.FRAG_PARSING_ERROR,fatal:!1,levelRetry:n,error:t,reason:t.message})}function Zl(e,t){t.log(`${e} with AES-128-CBC encryption found in unencrypted stream`)}function Ql(e,t){let n=0,r,i,a,o,s,c=e.data;if(!e||e.size===0)return null;for(;c[0].length<19&&c.length>1;)c[0]=Gi(c[0],c[1]),c.splice(1,1);if(r=c[0],(r[0]<<16)+(r[1]<<8)+r[2]===1){if(i=(r[4]<<8)+r[5],i&&i>e.size-6)return null;let l=r[7];l&192&&(o=(r[9]&14)*536870912+(r[10]&255)*4194304+(r[11]&254)*16384+(r[12]&255)*128+(r[13]&254)/2,l&64?(s=(r[14]&14)*536870912+(r[15]&255)*4194304+(r[16]&254)*16384+(r[17]&255)*128+(r[18]&254)/2,o-s>60*9e4&&(t.warn(`${Math.round((o-s)/9e4)}s delta between PTS and DTS, align them`),o=s)):s=o),a=r[8];let u=a+9;if(e.size<=u)return null;e.size-=u;let d=new Uint8Array(e.size);for(let e=0,t=c.length;e<t;e++){r=c[e];let t=r.byteLength;if(u)if(u>t){u-=t;continue}else r=r.subarray(u),t-=u,u=0;d.set(r,n),n+=t}return i&&(i-=a+3),{data:d,pts:o,dts:s,len:i}}return null}var $l=class{static getSilentFrame(e,t){switch(e){case`mp4a.40.2`:if(t===1)return new Uint8Array([0,200,0,128,35,128]);if(t===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(t===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(t===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(t===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(t===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(t===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===2||t===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);break}}},eu=2**32-1,tu=class e{static init(){e.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let t;for(t in e.types)e.types.hasOwnProperty(t)&&(e.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);e.HDLR_TYPES={video:new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),audio:new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0])};let n=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]);e.STTS=e.STSC=e.STCO=new Uint8Array([0,0,0,0,0,0,0,0]),e.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),e.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),e.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),e.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);let r=new Uint8Array([105,115,111,109]),i=new Uint8Array([97,118,99,49]),a=new Uint8Array([0,0,0,1]);e.FTYP=e.box(e.types.ftyp,r,a,r,i),e.DINF=e.box(e.types.dinf,e.box(e.types.dref,n))}static box(e,...t){let n=8,r=t.length,i=r;for(;r--;)n+=t[r].byteLength;let a=new Uint8Array(n);for(a[0]=n>>24&255,a[1]=n>>16&255,a[2]=n>>8&255,a[3]=n&255,a.set(e,4),r=0,n=8;r<i;r++)a.set(t[r],n),n+=t[r].byteLength;return a}static hdlr(t){return e.box(e.types.hdlr,e.HDLR_TYPES[t])}static mdat(t){return e.box(e.types.mdat,t)}static mdhd(t,n){n*=t;let r=Math.floor(n/(eu+1)),i=Math.floor(n%(eu+1));return e.box(e.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,r>>24,r>>16&255,r>>8&255,r&255,i>>24,i>>16&255,i>>8&255,i&255,85,196,0,0]))}static mdia(t){return e.box(e.types.mdia,e.mdhd(t.timescale||0,t.duration||0),e.hdlr(t.type),e.minf(t))}static mfhd(t){return e.box(e.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255]))}static minf(t){return t.type===`audio`?e.box(e.types.minf,e.box(e.types.smhd,e.SMHD),e.DINF,e.stbl(t)):e.box(e.types.minf,e.box(e.types.vmhd,e.VMHD),e.DINF,e.stbl(t))}static moof(t,n,r){return e.box(e.types.moof,e.mfhd(t),e.traf(r,n))}static moov(t){let n=t.length,r=[];for(;n--;)r[n]=e.trak(t[n]);return e.box.apply(null,[e.types.moov,e.mvhd(t[0].timescale||0,t[0].duration||0)].concat(r,e.mvex(t)))}static mvex(t){let n=t.length,r=[];for(;n--;)r[n]=e.trex(t[n]);return e.box.apply(null,[e.types.mvex,...r])}static mvhd(t,n){n*=t;let r=Math.floor(n/(eu+1)),i=Math.floor(n%(eu+1)),a=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,r>>24,r>>16&255,r>>8&255,r&255,i>>24,i>>16&255,i>>8&255,i&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return e.box(e.types.mvhd,a)}static sdtp(t){let n=t.samples||[],r=new Uint8Array(4+n.length),i,a;for(i=0;i<n.length;i++)a=n[i].flags,r[i+4]=a.dependsOn<<4|a.isDependedOn<<2|a.hasRedundancy;return e.box(e.types.sdtp,r)}static stbl(t){return e.box(e.types.stbl,e.stsd(t),e.box(e.types.stts,e.STTS),e.box(e.types.stsc,e.STSC),e.box(e.types.stsz,e.STSZ),e.box(e.types.stco,e.STCO))}static avc1(t){let n=[],r=[],i,a,o;for(i=0;i<t.sps.length;i++)a=t.sps[i],o=a.byteLength,n.push(o>>>8&255),n.push(o&255),n=n.concat(Array.prototype.slice.call(a));for(i=0;i<t.pps.length;i++)a=t.pps[i],o=a.byteLength,r.push(o>>>8&255),r.push(o&255),r=r.concat(Array.prototype.slice.call(a));let s=e.box(e.types.avcC,new Uint8Array([1,n[3],n[4],n[5],255,224|t.sps.length].concat(n,[t.pps.length],r))),c=t.width,l=t.height,u=t.pixelRatio[0],d=t.pixelRatio[1];return e.box(e.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,c>>8&255,c&255,l>>8&255,l&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),s,e.box(e.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(e.types.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,u&255,d>>24,d>>16&255,d>>8&255,d&255])))}static esds(e){let t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...t,6,1,2])}static audioStsd(e){let t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,t&255,0,0])}static mp4a(t){return e.box(e.types.mp4a,e.audioStsd(t),e.box(e.types.esds,e.esds(t)))}static mp3(t){return e.box(e.types[`.mp3`],e.audioStsd(t))}static ac3(t){return e.box(e.types[`ac-3`],e.audioStsd(t),e.box(e.types.dac3,t.config))}static stsd(t){let{segmentCodec:n}=t;if(t.type===`audio`){if(n===`aac`)return e.box(e.types.stsd,e.STSD,e.mp4a(t));if(n===`ac3`&&t.config)return e.box(e.types.stsd,e.STSD,e.ac3(t));if(n===`mp3`&&t.codec===`mp3`)return e.box(e.types.stsd,e.STSD,e.mp3(t))}else if(t.pps&&t.sps){if(n===`avc`)return e.box(e.types.stsd,e.STSD,e.avc1(t));if(n===`hevc`&&t.vps)return e.box(e.types.stsd,e.STSD,e.hvc1(t))}else throw Error(`video track missing pps or sps`);throw Error(`unsupported ${t.type} segment codec (${n}/${t.codec})`)}static tkhd(t){let n=t.id,r=(t.duration||0)*(t.timescale||0),i=t.width||0,a=t.height||0,o=Math.floor(r/(eu+1)),s=Math.floor(r%(eu+1));return e.box(e.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,n>>24&255,n>>16&255,n>>8&255,n&255,0,0,0,0,o>>24,o>>16&255,o>>8&255,o&255,s>>24,s>>16&255,s>>8&255,s&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,i>>8&255,i&255,0,0,a>>8&255,a&255,0,0]))}static traf(t,n){let r=e.sdtp(t),i=t.id,a=Math.floor(n/(eu+1)),o=Math.floor(n%(eu+1));return e.box(e.types.traf,e.box(e.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,i&255])),e.box(e.types.tfdt,new Uint8Array([1,0,0,0,a>>24,a>>16&255,a>>8&255,a&255,o>>24,o>>16&255,o>>8&255,o&255])),e.trun(t,r.length+16+20+8+16+8+8),r)}static trak(t){return t.duration=t.duration||4294967295,e.box(e.types.trak,e.tkhd(t),e.mdia(t))}static trex(t){let n=t.id;return e.box(e.types.trex,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,n&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,n){let r=t.samples||[],i=r.length,a=12+16*i,o=new Uint8Array(a),s,c,l,u,d,f;for(n+=8+a,o.set([t.type===`video`?1:0,0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,i&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255],0),s=0;s<i;s++)c=r[s],l=c.duration,u=c.size,d=c.flags,f=c.cts,o.set([l>>>24&255,l>>>16&255,l>>>8&255,l&255,u>>>24&255,u>>>16&255,u>>>8&255,u&255,d.isLeading<<2|d.dependsOn,d.isDependedOn<<6|d.hasRedundancy<<4|d.paddingValue<<1|d.isNonSync,d.degradPrio&61440,d.degradPrio&15,f>>>24&255,f>>>16&255,f>>>8&255,f&255],12+16*s);return e.box(e.types.trun,o)}static initSegment(t){e.types||e.init();let n=e.moov(t);return Gi(e.FTYP,n)}static hvc1(t){let n=t.params,r=[t.vps,t.sps,t.pps],i=new Uint8Array([1,n.general_profile_space<<6|(n.general_tier_flag?32:0)|n.general_profile_idc,n.general_profile_compatibility_flags[0],n.general_profile_compatibility_flags[1],n.general_profile_compatibility_flags[2],n.general_profile_compatibility_flags[3],n.general_constraint_indicator_flags[0],n.general_constraint_indicator_flags[1],n.general_constraint_indicator_flags[2],n.general_constraint_indicator_flags[3],n.general_constraint_indicator_flags[4],n.general_constraint_indicator_flags[5],n.general_level_idc,240|n.min_spatial_segmentation_idc>>8,255&n.min_spatial_segmentation_idc,252|n.parallelismType,252|n.chroma_format_idc,248|n.bit_depth_luma_minus8,248|n.bit_depth_chroma_minus8,0,parseInt(n.frame_rate.fps),3|n.temporal_id_nested<<2|n.num_temporal_layers<<3|(n.frame_rate.fixed?64:0),r.length]),a=i.length;for(let e=0;e<r.length;e+=1){a+=3;for(let t=0;t<r[e].length;t+=1)a+=2+r[e][t].length}let o=new Uint8Array(a);o.set(i,0),a=i.length;let s=r.length-1;for(let e=0;e<r.length;e+=1){o.set(new Uint8Array([32+e|(e===s?128:0),0,r[e].length]),a),a+=3;for(let t=0;t<r[e].length;t+=1)o.set(new Uint8Array([r[e][t].length>>8,r[e][t].length&255]),a),a+=2,o.set(r[e][t],a),a+=r[e][t].length}let c=e.box(e.types.hvcC,o),l=t.width,u=t.height,d=t.pixelRatio[0],f=t.pixelRatio[1];return e.box(e.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,l&255,u>>8&255,u&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),c,e.box(e.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(e.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,d&255,f>>24,f>>16&255,f>>8&255,f&255])))}};tu.types=void 0,tu.HDLR_TYPES=void 0,tu.STTS=void 0,tu.STSC=void 0,tu.STCO=void 0,tu.STSZ=void 0,tu.VMHD=void 0,tu.SMHD=void 0,tu.STSD=void 0,tu.FTYP=void 0,tu.DINF=void 0;var nu=9e4;function ru(e,t,n=1,r=!1){let i=e*t*n;return r?Math.round(i):i}function iu(e,t,n=1,r=!1){return ru(e,t,1/n,r)}function au(e,t=!1){return ru(e,1e3,1/nu,t)}function ou(e,t=1){return ru(e,nu,1/t)}function su(e){let{baseTime:t,timescale:n,trackId:r}=e;return`${t/n} (${t}/${n}) trackId: ${r}`}var cu=10*1e3,lu=1024,uu=1152,du=1536,fu=null,pu=null;function mu(e,t,n,r){return{duration:t,size:n,cts:r,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}}var hu=class extends Zr{constructor(e,t,n,r){if(super(`mp4-remuxer`,r),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=n,this.ISGenerated=!1,fu===null){let e=(navigator.userAgent||``).match(/Chrome\/(\d+)/i);fu=e?parseInt(e[1]):0}if(pu===null){let e=navigator.userAgent.match(/Safari\/(\d+)/i);pu=e?parseInt(e[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){let t=this._initPTS;(!t||!e||e.trackId!==t.trackId||e.baseTime!==t.baseTime||e.timescale!==t.timescale)&&this.log(`Reset initPTS: ${t&&su(t)} > ${e&&su(e)}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log(`reset next timestamp`),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log(`ISGenerated flag reset`),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1,n=e[0].pts,r=e.reduce((e,r)=>{let i=r.pts,a=i-e;return a<-4294967296&&(t=!0,i=gu(i,n),a=i-e),a>0?e:i},n);return t&&this.debug(`PTS rollover detected`),r}remux(e,t,n,r,i,a,o,s){let c,l,u,d,f,p,m=i,h=i,g=e.pid>-1,_=t.pid>-1,v=t.samples.length,y=e.samples.length>0,b=o&&v>0||v>1;if((!g||y)&&(!_||b)||this.ISGenerated||o){if(this.ISGenerated){let e=this.videoTrackConfig;(e&&(t.width!==e.width||t.height!==e.height||t.pixelRatio?.[0]!==e.pixelRatio?.[0]||t.pixelRatio?.[1]!==e.pixelRatio?.[1])||!e&&b||this.nextAudioTs===null&&y)&&this.resetInitSegment()}this.ISGenerated||(u=this.generateIS(e,t,i,a));let n=this.isVideoContiguous,r=-1,o;if(b&&(r=_u(t.samples),!n&&this.config.forceKeyFrameOnDiscontinuity))if(p=!0,r>0){this.warn(`Dropped ${r} out of ${v} video samples due to a missing keyframe`);let e=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(r),t.dropped+=r,h+=(t.samples[0].pts-e)/t.inputTimeScale,o=h}else r===-1&&(this.warn(`No keyframe found out of ${v} video samples`),p=!1);if(this.ISGenerated){if(y&&b){let n=this.getVideoStartPts(t.samples),r=(gu(e.samples[0].pts,n)-n)/t.inputTimeScale;m+=Math.max(0,r),h+=Math.max(0,-r)}if(y){if(e.samplerate||(this.warn(`regenerate InitSegment as audio detected`),u=this.generateIS(e,t,i,a)),l=this.remuxAudio(e,m,this.isAudioContiguous,a,_||b||s===H.AUDIO?h:void 0),b){let r=l?l.endPTS-l.startPTS:0;t.inputTimeScale||(this.warn(`regenerate InitSegment as video detected`),u=this.generateIS(e,t,i,a)),c=this.remuxVideo(t,h,n,r)}}else b&&(c=this.remuxVideo(t,h,n,0));c&&(c.firstKeyFrame=r,c.independent=r!==-1,c.firstKeyFramePTS=o)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(n.samples.length&&(f=vu(n,i,this._initPTS,this._initDTS)),r.samples.length&&(d=yu(r,i,this._initPTS))),{audio:l,video:c,initSegment:u,independent:p,text:d,id3:f}}computeInitPts(e,t,n,r){let i=Math.round(n*t),a=gu(e,i);if(a<i+t)for(this.log(`Adjusting PTS for rollover in timeline near ${(i-a)/t} ${r}`);a<i+t;)a+=8589934592;return a-i}generateIS(e,t,n,r){let i=e.samples,a=t.samples,o=this.typeSupported,s={},c=this._initPTS,l=!c||r,u=`audio/mp4`,d,f,p,m=-1;if(l&&(d=f=1/0),e.config&&i.length){switch(e.timescale=e.samplerate,e.segmentCodec){case`mp3`:o.mpeg?(u=`audio/mpeg`,e.codec=``):o.mp3&&(e.codec=`mp3`);break;case`ac3`:e.codec=`ac-3`;break}s.audio={id:`audio`,container:u,codec:e.codec,initSegment:e.segmentCodec===`mp3`&&o.mpeg?new Uint8Array:tu.initSegment([e]),metadata:{channelCount:e.channelCount}},l&&(m=e.id,p=e.inputTimeScale,!c||p!==c.timescale?d=f=this.computeInitPts(i[0].pts,p,n,`audio`):l=!1)}if(t.sps&&t.pps&&a.length){if(t.timescale=t.inputTimeScale,s.video={id:`main`,container:`video/mp4`,codec:t.codec,initSegment:tu.initSegment([t]),metadata:{width:t.width,height:t.height}},l)if(m=t.id,p=t.inputTimeScale,!c||p!==c.timescale){let e=this.getVideoStartPts(a),t=gu(a[0].dts,e),r=this.computeInitPts(t,p,n,`video`),i=this.computeInitPts(e,p,n,`video`);f=Math.min(f,r),d=Math.min(d,i)}else l=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(s).length)return this.ISGenerated=!0,l?(c&&this.warn(`Timestamps at playlist time: ${r?``:`~`}${n} ${d/p} != initPTS: ${c.baseTime/c.timescale} (${c.baseTime}/${c.timescale}) trackId: ${c.trackId}`),this.log(`Found initPTS at playlist time: ${n} offset: ${d/p} (${d}/${p}) trackId: ${m}`),this._initPTS={baseTime:d,timescale:p,trackId:m},this._initDTS={baseTime:f,timescale:p,trackId:m}):d=p=void 0,{tracks:s,initPTS:d,timescale:p,trackId:m}}remuxVideo(e,t,n,r){let i=e.inputTimeScale,a=e.samples,o=[],s=a.length,c=this._initPTS,l=c.baseTime*i/c.timescale,u=this.nextVideoTs,d=8,f=this.videoSampleDuration,p,m,h=1/0,g=-1/0,_=!1;if(!n||u===null){let e=l+t*i,r=a[0].pts-gu(a[0].dts,a[0].pts);fu&&u!==null&&Math.abs(e-r-(u+l))<15e3?n=!0:u=e-r-l}let v=u+l;for(let e=0;e<s;e++){let t=a[e];t.pts=gu(t.pts,v),t.dts=gu(t.dts,v),t.dts<a[e>0?e-1:e].dts&&(_=!0)}_&&a.sort(function(e,t){let n=e.dts-t.dts,r=e.pts-t.pts;return n||r}),p=a[0].dts,m=a[a.length-1].dts;let y=m-p,b=y?Math.round(y/(s-1)):f||e.inputTimeScale/30;if(n){let n=p-v,r=n>b,i=n<-1;if((r||i)&&(r?this.warn(`${(e.segmentCodec||``).toUpperCase()}: ${au(n,!0)} ms (${n}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||``).toUpperCase()}: ${au(-n,!0)} ms (${n}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!i||v>=a[0].pts||fu)){p=v;let e=a[0].pts-n;if(r)a[0].dts=p,a[0].pts=e;else{let t=!0;for(let r=0;r<a.length&&!(a[r].dts>e&&t);r++){let e=a[r].pts;if(a[r].dts-=n,a[r].pts-=n,r<a.length-1){let n=a[r+1].pts;t=n<=a[r].pts==n<=e}}}this.log(`Video: Initial PTS/DTS adjusted: ${au(e,!0)}/${au(p,!0)}, delta: ${au(n,!0)} ms`)}}p=Math.max(0,p);let x=0,S=0,C=p;for(let e=0;e<s;e++){let t=a[e],n=t.units,r=n.length,i=0;for(let e=0;e<r;e++)i+=n[e].data.length;S+=i,x+=r,t.length=i,t.dts<C?(t.dts=C,C+=b/4|0||1):C=t.dts,h=Math.min(t.pts,h),g=Math.max(t.pts,g)}m=a[s-1].dts;let w=S+4*x+8,T;try{T=new Uint8Array(w)}catch(e){this.observer.emit(B.ERROR,B.ERROR,{type:R.MUX_ERROR,details:z.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:w,reason:`fail allocating video mdat ${w}`});return}let E=new DataView(T.buffer);E.setUint32(0,w),T.set(tu.types.mdat,4);let ee=!1,D=1/0,te=1/0,ne=-1/0,O=-1/0;for(let e=0;e<s;e++){let t=a[e],n=t.units,c=0;for(let e=0,t=n.length;e<t;e++){let t=n[e],r=t.data,i=t.data.byteLength;E.setUint32(d,i),d+=4,T.set(r,d),d+=i,c+=4+i}let u;if(e<s-1)f=a[e+1].dts-t.dts,u=a[e+1].pts-t.pts;else{let n=this.config,o=e>0?t.dts-a[e-1].dts:b;if(u=e>0?t.pts-a[e-1].pts:b,n.stretchShortVideoTrack&&this.nextAudioTs!==null){let e=Math.floor(n.maxBufferHole*i),a=(r?h+r*i:this.nextAudioTs+l)-t.pts;a>e?(f=a-o,f<0?f=o:ee=!0,this.log(`It is approximately ${a/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=o}else f=o}let p=Math.round(t.pts-t.dts);D=Math.min(D,f),ne=Math.max(ne,f),te=Math.min(te,u),O=Math.max(O,u),o.push(mu(t.key,f,c,p))}if(o.length){if(fu){if(fu<70){let e=o[0].flags;e.dependsOn=2,e.isNonSync=0}}else if(pu&&O-te<ne-D&&b/ne<.025&&o[0].cts===0){this.warn(`Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.`);let e=p;for(let t=0,n=o.length;t<n;t++){let r=e+o[t].duration,i=e+o[t].cts;if(t<n-1){let e=r+o[t+1].cts;o[t].duration=e-i}else o[t].duration=t?o[t-1].duration:b;o[t].cts=0,e=r}}}f=ee||!f?b:f,this.nextVideoTs=u=m+f-l,this.videoSampleDuration=f,this.isVideoContiguous=!0;let k={data1:tu.moof(e.sequenceNumber++,p,U(e,{samples:o})),data2:T,startPTS:(h-l)/i,endPTS:(g+f-l)/i,startDTS:(p-l)/i,endDTS:u/i,type:`video`,hasAudio:!1,hasVideo:!0,nb:o.length,dropped:e.dropped};return e.samples=[],e.dropped=0,k}getSamplesPerFrame(e){switch(e.segmentCodec){case`mp3`:return uu;case`ac3`:return du;default:return lu}}remuxAudio(e,t,n,r,i){let a=e.inputTimeScale,o=a/(e.samplerate?e.samplerate:a),s=this.getSamplesPerFrame(e),c=s*o,l=this._initPTS,u=e.segmentCodec===`mp3`&&this.typeSupported.mpeg,d=[],f=i!==void 0,p=e.samples,m=u?0:8,h=this.nextAudioTs||-1,g=l.baseTime*a/l.timescale,_=g+t*a;if(this.isAudioContiguous=n||=p.length&&h>0&&(r&&Math.abs(_-(h+g))<9e3||Math.abs(gu(p[0].pts,_)-(h+g))<20*c),p.forEach(function(e){e.pts=gu(e.pts,_)}),!n||h<0){let e=p.length;if(p=p.filter(e=>e.pts>=0),e!==p.length&&this.warn(`Removed ${p.length-e} of ${e} samples (initPTS ${g} / ${a})`),!p.length)return;h=i===0?0:r&&!f?Math.max(0,_-g):p[0].pts-g}if(e.segmentCodec===`aac`){let t=this.config.maxAudioFramesDrift;for(let n=0,r=h+g;n<p.length;n++){let i=p[n],o=i.pts,s=o-r,l=Math.abs(1e3*s/a);if(s<=-t*c&&f)n===0&&(this.warn(`Audio frame @ ${(o/a).toFixed(3)}s overlaps marker by ${Math.round(1e3*s/a)} ms.`),this.nextAudioTs=h=o-g,r=o);else if(s>=t*c&&l<cu&&f){let t=Math.round(s/c);for(r=o-t*c;r<0&&t&&c;)t--,r+=c;n===0&&(this.nextAudioTs=h=r-g),this.warn(`Injecting ${t} audio frames @ ${((r-g)/a).toFixed(3)}s due to ${Math.round(1e3*s/a)} ms gap.`);for(let a=0;a<t;a++){let t=$l.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);t||=(this.log(`Unable to get silent frame for given audio codec; duplicating last frame instead.`),i.unit.subarray()),p.splice(n,0,{unit:t,pts:r}),r+=c,n++}}i.pts=r,r+=c}}let v=null,y=null,b,x=0,S=p.length;for(;S--;)x+=p[S].unit.byteLength;for(let t=0,r=p.length;t<r;t++){let r=p[t],i=r.unit,a=r.pts;if(y!==null){let e=d[t-1];e.duration=Math.round((a-y)/o)}else if(n&&e.segmentCodec===`aac`&&(a=h+g),v=a,x>0){x+=m;try{b=new Uint8Array(x)}catch(e){this.observer.emit(B.ERROR,B.ERROR,{type:R.MUX_ERROR,details:z.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:x,reason:`fail allocating audio mdat ${x}`});return}u||(new DataView(b.buffer).setUint32(0,x),b.set(tu.types.mdat,4))}else return;b.set(i,m);let c=i.byteLength;m+=c,d.push(mu(!0,s,c,0)),y=a}let C=d.length;if(!C)return;let w=d[d.length-1];h=y-g,this.nextAudioTs=h+o*w.duration;let T=u?new Uint8Array:tu.moof(e.sequenceNumber++,v/o,U({},e,{samples:d}));e.samples=[];let E=(v-g)/a,ee=this.nextAudioTs/a,D={data1:T,data2:b,startPTS:E,endPTS:ee,startDTS:E,endDTS:ee,type:`audio`,hasAudio:!0,hasVideo:!1,nb:C};return this.isAudioContiguous=!0,D}};function gu(e,t){let n;if(t===null)return e;for(n=t<e?-8589934592:8589934592;Math.abs(e-t)>4294967296;)e+=n;return e}function _u(e){for(let t=0;t<e.length;t++)if(e[t].key)return t;return-1}function vu(e,t,n,r){let i=e.samples.length;if(!i)return;let a=e.inputTimeScale;for(let o=0;o<i;o++){let i=e.samples[o];i.pts=gu(i.pts-n.baseTime*a/n.timescale,t*a)/a,i.dts=gu(i.dts-r.baseTime*a/r.timescale,t*a)/a}let o=e.samples;return e.samples=[],{samples:o}}function yu(e,t,n){let r=e.samples.length;if(!r)return;let i=e.inputTimeScale;for(let a=0;a<r;a++){let r=e.samples[a];r.pts=gu(r.pts-n.baseTime*i/n.timescale,t*i)/i}e.samples.sort((e,t)=>e.pts-t.pts);let a=e.samples;return e.samples=[],{samples:a}}var bu=class extends Zr{constructor(e,t,n,r){super(`passthrough-remuxer`,r),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(e){this.lastEndTime=null;let t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,n,r){this.audioCodec=t,this.videoCodec=n,this.generateInitSegment(e,r),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:n,videoCodec:r}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}let{audio:i,video:a}=this.initData=Mi(e);if(t)zi(e,t);else{let e=i||a;e!=null&&e.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${e.codec}")!`)}i&&(n=Cu(i,K.AUDIO,this)),a&&(r=Cu(a,K.VIDEO,this));let o={};i&&a?o.audiovideo={container:`video/mp4`,codec:n+`,`+r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:`main`}:i?o.audio={container:`audio/mp4`,codec:n,encrypted:i.encrypted,initSegment:e,id:`audio`}:a?o.video={container:`video/mp4`,codec:r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:`main`}:this.warn(`initSegment does not contain moov or trak boxes.`),this.initTracks=o}remux(e,t,n,r,i,a){var o,s;let{initPTS:c,lastEndTime:l}=this,u={audio:void 0,video:void 0,text:r,id3:n,initSegment:void 0};L(l)||(l=this.lastEndTime=i||0);let d=t.samples;if(!d.length)return u;let f={initPTS:void 0,timescale:void 0,trackId:void 0},p=this.initData;if((o=p)!=null&&o.length||(this.generateInitSegment(d),p=this.initData),!((s=p)!=null&&s.length))return this.warn(`Failed to generate initSegment.`),u;this.emitInitSegment&&=(f.tracks=this.initTracks,!1);let m=Ui(d,p,this),h=p.audio?m[p.audio.id]:null,g=p.video?m[p.video.id]:null,_=xu(g,1/0),v=xu(h,1/0),y=xu(g,0,!0),b=xu(h,0,!0),x=i,S=0,C=h&&(!g||!c&&v<_||c&&c.trackId===p.audio.id),w=C?h:g;if(w){let e=w.timescale,t=w.start-i*e,n=C?p.audio.id:p.video.id;x=w.start/e,S=C?b-v:y-_,(a||!c)&&(Su(c,x,i,S)||e!==c.timescale)&&(c&&this.warn(`Timestamps at playlist time: ${a?``:`~`}${i} ${t/e} != initPTS: ${c.baseTime/c.timescale} (${c.baseTime}/${c.timescale}) trackId: ${c.trackId}`),this.log(`Found initPTS at playlist time: ${i} offset: ${x-i} (${t}/${e}) trackId: ${n}`),c=null,f.initPTS=t,f.timescale=e,f.trackId=n)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${i}`);c?(f.initPTS=c.baseTime,f.timescale=c.timescale,f.trackId=c.trackId):((!f.timescale||f.trackId===void 0||f.initPTS===void 0)&&(this.warn(`Could not set initPTS`),f.initPTS=x,f.timescale=1,f.trackId=-1),this.initPTS=c={baseTime:f.initPTS,timescale:f.timescale,trackId:f.trackId});let T=x-c.baseTime/c.timescale,E=T+S;S>0?this.lastEndTime=E:(this.warn(`Duration parsed from mp4 should be greater than zero`),this.resetNextTimestamp());let ee=!!p.audio,D=!!p.video,te=``;ee&&(te+=`audio`),D&&(te+=`video`);let ne=(p.audio?p.audio.encrypted:!1)||(p.video?p.video.encrypted:!1),O={data1:d,startPTS:T,startDTS:T,endPTS:E,endDTS:E,type:te,hasAudio:ee,hasVideo:D,nb:1,dropped:0,encrypted:ne};u.audio=ee&&!D?O:void 0,u.video=D?O:void 0;let k=g?.sampleCount;if(k){let e=g.keyFrameIndex,t=e!==-1;O.nb=k,O.dropped=e===0||this.isVideoContiguous?0:t?e:k,O.independent=t,O.firstKeyFrame=e,t&&g.keyFrameStart&&(O.firstKeyFramePTS=(g.keyFrameStart-c.baseTime)/c.timescale),this.isVideoContiguous||(u.independent=t),this.isVideoContiguous||=t,O.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${e}/${k} dropped: ${O.dropped} start: ${O.firstKeyFramePTS||`NA`}`)}return u.initSegment=f,u.id3=vu(n,i,c,c),r.samples.length&&(u.text=yu(r,i,c)),u}};function xu(e,t,n=!1){return e?.start===void 0?t:(e.start+(n?e.duration:0))/e.timescale}function Su(e,t,n,r){if(e===null)return!0;let i=Math.max(r,1),a=t-e.baseTime/e.timescale;return Math.abs(a-n)>i}function Cu(e,t,n){let r=e.codec;return r&&r.length>4?r:t===K.AUDIO?r===`ec-3`||r===`ac-3`||r===`alac`?r:r===`fLaC`||r===`Opus`?pa(r,!1):(n.warn(`Unhandled audio codec "${r}" in mp4 MAP`),r||`mp4a`):(n.warn(`Unhandled video codec "${r}" in mp4 MAP`),r||`avc1`)}var wu;try{wu=self.performance.now.bind(self.performance)}catch{wu=Date.now}var Tu=[{demux:Rl,remux:bu},{demux:Kl,remux:hu},{demux:Ml,remux:hu},{demux:Il,remux:hu}];Tu.splice(2,0,{demux:Pl,remux:hu});var Eu=class{constructor(e,t,n,r,i,a){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=n,this.id=i,this.logger=a}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,n,r){let i=n.transmuxing;i.executeStart=wu();let a=new Uint8Array(e),{currentTransmuxState:o,transmuxConfig:s}=this;r&&(this.currentTransmuxState=r);let{contiguous:c,discontinuity:l,trackSwitch:u,accurateTimeOffset:d,timeOffset:f,initSegmentChange:p}=r||o,{audioCodec:m,videoCodec:h,defaultInitPts:g,duration:_,initSegmentData:v}=s,y=Du(a,t);if(y&&us(y.method)){let e=this.getDecrypter(),t=ds(y.method);if(e.isSync()){let r=e.softwareDecrypt(a,y.key.buffer,y.iv.buffer,t);if(n.part>-1){let t=e.flush();r=t&&t.buffer}if(!r)return i.executeEnd=wu(),Ou(n);a=new Uint8Array(r)}else return this.asyncResult=!0,this.decryptionPromise=e.webCryptoDecrypt(a,y.key.buffer,y.iv.buffer,t).then(e=>{let t=this.push(e,null,n);return this.decryptionPromise=null,t}),this.decryptionPromise}let b=this.needsProbing(l,u);if(b){let e=this.configureTransmuxer(a);if(e)return this.logger.warn(`[transmuxer] ${e.message}`),this.observer.emit(B.ERROR,B.ERROR,{type:R.MEDIA_ERROR,details:z.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message}),i.executeEnd=wu(),Ou(n)}(l||u||p||b)&&this.resetInitSegment(v,m,h,_,t),(l||p||b)&&this.resetInitialTimestamp(g),c||this.resetContiguity();let x=this.transmux(a,y,f,d,n);this.asyncResult=ku(x);let S=this.currentTransmuxState;return S.contiguous=!0,S.discontinuity=!1,S.trackSwitch=!1,i.executeEnd=wu(),x}flush(e){let t=e.transmuxing;t.executeStart=wu();let{decrypter:n,currentTransmuxState:r,decryptionPromise:i}=this;if(i)return this.asyncResult=!0,i.then(()=>this.flush(e));let a=[],{timeOffset:o}=r;if(n){let t=n.flush();t&&a.push(this.push(t.buffer,null,e))}let{demuxer:s,remuxer:c}=this;if(!s||!c){t.executeEnd=wu();let n=[Ou(e)];return this.asyncResult?Promise.resolve(n):n}let l=s.flush(o);return ku(l)?(this.asyncResult=!0,l.then(t=>(this.flushRemux(a,t,e),a))):(this.flushRemux(a,l,e),this.asyncResult?Promise.resolve(a):a)}flushRemux(e,t,n){let{audioTrack:r,videoTrack:i,id3Track:a,textTrack:o}=t,{accurateTimeOffset:s,timeOffset:c}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${n.sn}${n.part>-1?` part: `+n.part:``} of ${this.id===H.MAIN?`level`:`track`} ${n.level}`);let l=this.remuxer.remux(r,i,a,o,c,s,!0,this.id);e.push({remuxResult:l,chunkMeta:n}),n.transmuxing.executeEnd=wu()}resetInitialTimestamp(e){let{demuxer:t,remuxer:n}=this;!t||!n||(t.resetTimeStamp(e),n.resetTimeStamp(e))}resetContiguity(){let{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,n,r,i){let{demuxer:a,remuxer:o}=this;!a||!o||(a.resetInitSegment(e,t,n,r),o.resetInitSegment(e,t,n,i))}destroy(){this.demuxer&&=(this.demuxer.destroy(),void 0),this.remuxer&&=(this.remuxer.destroy(),void 0)}transmux(e,t,n,r,i){let a;return a=t&&t.method===`SAMPLE-AES`?this.transmuxSampleAes(e,t,n,r,i):this.transmuxUnencrypted(e,n,r,i),a}transmuxUnencrypted(e,t,n,r){let{audioTrack:i,videoTrack:a,id3Track:o,textTrack:s}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(i,a,o,s,t,n,!1,this.id),chunkMeta:r}}transmuxSampleAes(e,t,n,r,i){return this.demuxer.demuxSampleAes(e,t,n).then(e=>({remuxResult:this.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,n,r,!1,this.id),chunkMeta:i}))}configureTransmuxer(e){let{config:t,observer:n,typeSupported:r}=this,i;for(let t=0,n=Tu.length;t<n;t++){var a;if((a=Tu[t].demux)!=null&&a.probe(e,this.logger)){i=Tu[t];break}}if(!i)return Error(`Failed to find demuxer by probing fragment data`);let o=this.demuxer,s=this.remuxer,c=i.remux,l=i.demux;(!s||!(s instanceof c))&&(this.remuxer=new c(n,t,r,this.logger)),(!o||!(o instanceof l))&&(this.demuxer=new l(n,t,r,this.logger),this.probe=l.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||=this.decrypter=new Lo(this.config),e}};function Du(e,t){let n=null;return e.byteLength>0&&t?.key!=null&&t.iv!==null&&t.method!=null&&(n=t),n}var Ou=e=>({remuxResult:{},chunkMeta:e});function ku(e){return`then`in e&&e.then instanceof Function}var Au=class{constructor(e,t,n,r,i){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=n,this.duration=r,this.defaultInitPts=i||null}},ju=class{constructor(e,t,n,r,i,a){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=n,this.trackSwitch=r,this.timeOffset=i,this.initSegmentChange=a}},Mu=0,Nu=class{constructor(e,t,n,r){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Mu++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=e=>{let t=e.data,n=this.hls;if(!(!n||!(t!=null&&t.event)||t.instanceNo!==this.instanceNo))switch(t.event){case`init`:{let e=this.workerContext?.objectURL;e&&self.URL.revokeObjectURL(e);break}case`transmuxComplete`:this.handleTransmuxComplete(t.data);break;case`flush`:this.onFlush(t.data);break;case`workerLog`:n.logger[t.data.logType]&&n.logger[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=this.frag,t.data.part=this.part,t.data.id=this.id,n.trigger(t.event,t.data);break}},this.onWorkerError=e=>{if(!this.hls)return;let t=Error(`${e.message} (${e.filename}:${e.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(B.ERROR,{type:R.OTHER_ERROR,details:z.INTERNAL_EXCEPTION,fatal:!1,event:`demuxerWorker`,error:t})};let i=e.config;this.hls=e,this.id=t,this.useWorker=!!i.enableWorker,this.onTransmuxComplete=n,this.onFlush=r;let a=(e,t)=>{t||={},t.frag=this.frag||void 0,e===B.ERROR&&(t=t,t.parent=this.id,t.part=this.part,this.error=t.error),this.hls.trigger(e,t)};this.observer=new Ac,this.observer.on(B.FRAG_DECRYPTED,a),this.observer.on(B.ERROR,a);let o=ya(i.preferManagedMediaSource);if(this.useWorker&&typeof Worker<`u`){let n=this.hls.logger;if(i.workerPath||Nc()){try{i.workerPath?(n.log(`loading Web Worker ${i.workerPath} for "${t}"`),this.workerContext=Fc(i.workerPath)):(n.log(`injecting Web Worker for "${t}"`),this.workerContext=Pc());let{worker:e}=this.workerContext;e.addEventListener(`message`,this.onWorkerMessage),e.addEventListener(`error`,this.onWorkerError),e.postMessage({instanceNo:this.instanceNo,cmd:`init`,typeSupported:o,id:t,config:Y(i)})}catch(r){n.warn(`Error setting up "${t}" Web Worker, fallback to inline`,r),this.terminateWorker(),this.error=null,this.transmuxer=new Eu(this.observer,o,i,``,t,e.logger)}return}}this.transmuxer=new Eu(this.observer,o,i,``,t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){let e=this.instanceNo;this.instanceNo=Mu++;let t=this.hls.config,n=ya(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:`reset`,resetNo:e,typeSupported:n,id:this.id,config:Y(t)})}}terminateWorker(){if(this.workerContext){let{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener(`message`,this.onWorkerMessage),e.removeEventListener(`error`,this.onWorkerError),Ic(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{let e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}let e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,n,r,i,a,o,s,c,l){c.transmuxing.start=self.performance.now();let{instanceNo:u,transmuxer:d}=this,f=a?a.start:i.start,p=i.decryptdata,m=this.frag,h=!(m&&i.cc===m.cc),g=!(m&&c.level===m.level),_=m?c.sn-m.sn:-1,v=this.part?c.part-this.part.index:-1,y=_===0&&c.id>1&&c.id===m?.stats.chunkCount,b=!g&&(_===1||_===0&&(v===1||y&&v<=0)),x=self.performance.now();(g||_||i.stats.parsing.start===0)&&(i.stats.parsing.start=x),a&&(v||!b)&&(a.stats.parsing.start=x);let S=!(m&&i.initSegment?.url===m.initSegment?.url),C=new ju(h,b,s,g,f,S);if(!b||h||S){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${i.type} sn: ${c.sn}${c.part>-1?` part: `+c.part:``} ${this.id===H.MAIN?`level`:`track`}: ${c.level} id: ${c.id}
18
+ discontinuity: ${h}
19
+ trackSwitch: ${g}
20
+ contiguous: ${b}
21
+ accurateTimeOffset: ${s}
22
+ timeOffset: ${f}
23
+ initSegmentChange: ${S}`);let e=new Au(n,r,t,o,l);this.configureTransmuxer(e)}if(this.frag=i,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:u,cmd:`demux`,data:e,decryptdata:p,chunkMeta:c,state:C},e instanceof ArrayBuffer?[e]:[]);else if(d){let t=d.push(e,p,c,C);ku(t)?t.then(e=>{this.handleTransmuxComplete(e)}).catch(e=>{this.transmuxerError(e,c,`transmuxer-interface push error`)}):this.handleTransmuxComplete(t)}}flush(e){e.transmuxing.start=self.performance.now();let{instanceNo:t,transmuxer:n}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:`flush`,chunkMeta:e});else if(n){let t=n.flush(e);ku(t)?t.then(t=>{this.handleFlushResult(t,e)}).catch(t=>{this.transmuxerError(t,e,`transmuxer-interface flush error`)}):this.handleFlushResult(t,e)}}transmuxerError(e,t,n){this.hls&&(this.error=e,this.hls.trigger(B.ERROR,{type:R.MEDIA_ERROR,details:z.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:n}))}handleFlushResult(e,t){e.forEach(e=>{this.handleTransmuxComplete(e)}),this.onFlush(t)}configureTransmuxer(e){let{instanceNo:t,transmuxer:n}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:`configure`,config:e}):n&&n.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}},Pu=100,Fu=class extends Cc{constructor(e,t,n){super(e,t,n,`audio-stream-controller`,H.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(B.LEVEL_LOADED,this.onLevelLoaded,this),e.on(B.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(B.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(B.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(B.BUFFER_RESET,this.onBufferReset,this),e.on(B.BUFFER_CREATED,this.onBufferCreated,this),e.on(B.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(B.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(B.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(B.FRAG_LOADING,this.onFragLoading,this),e.on(B.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){let{hls:e}=this;e&&(super.unregisterListeners(),e.off(B.LEVEL_LOADED,this.onLevelLoaded,this),e.off(B.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(B.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(B.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(B.BUFFER_RESET,this.onBufferReset,this),e.off(B.BUFFER_CREATED,this.onBufferCreated,this),e.off(B.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(B.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(B.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(B.FRAG_LOADING,this.onFragLoading,this),e.off(B.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:n,initPTS:r,timescale:i,trackId:a}){if(n===H.MAIN){let e=t.cc,n=this.fragCurrent;if(this.initPTS[e]={baseTime:r,timescale:i,trackId:a},this.log(`InitPTS for cc: ${e} found from main: ${r/i} (${r}/${i}) trackId: ${a}`),this.mainAnchor=t,this.state===Z.WAITING_INIT_PTS){let n=this.waitingData;(!n&&!this.loadingParts||n&&n.frag.cc!==e)&&this.syncWithAnchor(t,n?.frag)}else !this.hls.hasEnoughToStart&&n&&n.cc!==e?(n.abortRequests(),this.syncWithAnchor(t,n)):this.state===Z.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){let n=this.mainFragLoading?.frag||null;if(t&&n?.cc===t.cc)return;let r=(n||e).cc,i=uo(this.getLevelDetails(),r,this.getLoadPosition());i&&(this.log(`Syncing with main frag at ${i.start} cc ${i.cc}`),this.startFragRequested=!1,this.nextLoadPosition=i.start,this.resetLoadingState(),this.state===Z.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=Z.STOPPED;return}let n=this.lastCurrentTime;this.stopLoad(),this.setInterval(Pu),n>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${n.toFixed(3)}`),e=n,this.state=Z.IDLE):this.state=Z.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case Z.IDLE:this.doTickIdle();break;case Z.WAITING_TRACK:{let{levels:e,trackId:t}=this,n=e?.[t],r=n?.details;if(r&&!this.waitForLive(n)){if(this.waitForCdnTuneIn(r))break;this.state=Z.WAITING_INIT_PTS}break}case Z.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break;case Z.WAITING_INIT_PTS:{let e=this.waitingData;if(e){let{frag:t,part:n,cache:r,complete:i}=e,a=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=Z.FRAG_LOADING;let e={frag:t,part:n,payload:r.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(e),i&&super._handleFragmentLoadComplete(e)}else a&&a.cc!==e.frag.cc&&this.syncWithAnchor(a,e.frag)}else this.state=Z.IDLE}}this.onTickEnd()}resetLoadingState(){let e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){let{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){let{hls:e,levels:t,media:n,trackId:r}=this,i=e.config;if(!this.buffering||!n&&!this.primaryPrefetch&&(this.startFragRequested||!i.startFragPrefetch)||!(t!=null&&t[r]))return;let a=t[r],o=a.details;if(!o||this.waitForLive(a)||this.waitForCdnTuneIn(o)){this.state=Z.WAITING_TRACK,this.startFragRequested=!1;return}let s=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&s&&(this.bufferFlushed=!1,this.afterBufferFlushed(s,K.AUDIO,H.AUDIO));let c=this.getFwdBufferInfo(s,H.AUDIO);if(c===null)return;if(!this.switchingTrack&&this._streamEnded(c,o)){e.trigger(B.BUFFER_EOS,{type:`audio`}),this.state=Z.ENDED;return}let l=c.len,u=e.maxBufferLength,d=o.fragments,f=d[0].start,p=this.getLoadPosition(),m=this.flushing?p:c.end;if(this.switchingTrack&&n){let e=p;o.PTSKnown&&e<f&&(c.end>f||c.nextStart)&&(this.log(`Alt audio track ahead of main track, seek to start of alt audio track`),n.currentTime=f+.05)}if(l>=u&&!this.switchingTrack&&m<d[d.length-1].start)return;let h=this.getNextFragment(m,o);if(h&&this.isLoopLoading(h,m)&&(h=this.getNextFragmentLoopLoading(h,o,c,H.MAIN,u)),!h){this.bufferFlushed=!0;return}let g=this.mainFragLoading?.frag||null;if(!this.audioOnly&&this.startFragRequested&&g&&vi(h)&&!h.endList&&(!o.live||!this.loadingParts&&m<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(g)===To.OK&&(this.mainFragLoading=g=null),g&&vi(g))){if(h.start>g.end){let e=this.fragmentTracker.getFragAtPos(m,H.MAIN);e&&e.end>g.end&&(g=e,this.mainFragLoading={frag:e,targetBufferTime:null})}if(h.start>g.end)return}this.loadFragment(h,a,m)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(e=>new za(e))}onAudioTrackSwitching(e,t){let n=!!t.url;this.trackId=t.id;let{fragCurrent:r}=this;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),n?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==Z.STOPPED&&(this.setInterval(Pu),this.state=Z.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;let n=this.cachedTrackLoadedData;n&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(B.AUDIO_TRACK_LOADED,n))}onAudioTrackLoaded(e,t){var n;let{levels:r}=this,{details:i,id:a,groupId:o,track:s}=t;if(!r){this.warn(`Audio tracks reset while loading track ${a} "${s.name}" of "${o}"`);return}let c=this.mainDetails;if(!c||i.endCC>c.endCC||c.expired){this.cachedTrackLoadedData=t,this.state!==Z.STOPPED&&(this.state=Z.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${a} "${s.name}" of "${o}" loaded [${i.startSN},${i.endSN}]${i.lastPartSn?`[part-${i.lastPartSn}-${i.lastPartIndex}]`:``},duration:${i.totalduration}`);let l=r[a],u=0;if(i.live||(n=l.details)!=null&&n.live){if(this.checkLiveUpdate(i),i.deltaUpdateFailed)return;l.details&&(u=this.alignPlaylists(i,l.details,this.levelLastLoaded?.details)),i.alignedSliding||(vc(i,c),i.alignedSliding||yc(i,c),u=i.fragmentStart)}l.details=i,this.levelLastLoaded=l,this.startFragRequested||this.setStartPosition(c,u),this.hls.trigger(B.AUDIO_TRACK_UPDATED,{details:i,id:a,groupId:t.groupId}),this.state===Z.WAITING_TRACK&&!this.waitForCdnTuneIn(i)&&(this.state=Z.IDLE),this.tick()}_handleFragmentLoadProgress(e){let t=e.frag,{part:n,payload:r}=e,{config:i,trackId:a,levels:o}=this;if(!o){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${t.sn} of level ${t.level} will not be buffered`);return}let s=o[a];if(!s){this.warn(`Audio track is undefined on fragment load progress`);return}let c=s.details;if(!c){this.warn(`Audio track details undefined on fragment load progress`),this.removeUnbufferedFrags(t.start);return}let l=i.defaultAudioCodec||s.audioCodec||`mp4a.40.2`,u=this.transmuxer;u||=this.transmuxer=new Nu(this.hls,H.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this));let d=this.initPTS[t.cc],f=t.initSegment?.data;if(d!==void 0){let e=n?n.index:-1,i=e!==-1,a=new Go(t.level,t.sn,t.stats.chunkCount,r.byteLength,e,i);u.push(r,f,l,``,t,n,c.totalduration,!1,a,d)}else{this.log(`Unknown video PTS for cc ${t.cc}, waiting for video PTS before demuxing audio frag ${t.sn} of [${c.startSN} ,${c.endSN}],track ${a}`);let{cache:e}=this.waitingData=this.waitingData||{frag:t,part:n,cache:new Tc,complete:!1};e.push(new Uint8Array(r)),this.state!==Z.STOPPED&&(this.state=Z.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;let n=t.tracks.audio;n&&(this.mediaBuffer=n.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===H.MAIN&&vi(t.frag)&&(this.mainFragLoading=t,this.state===Z.IDLE&&this.tick())}onFragBuffered(e,t){let{frag:n,part:r}=t;if(n.type!==H.AUDIO){!this.audioOnly&&n.type===H.MAIN&&!n.elementaryStreams.video&&!n.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(n)){this.warn(`Fragment ${n.sn}${r?` p: `+r.index:``} of level ${n.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:`false`}`);return}if(vi(n)){this.fragPrevious=n;let e=this.switchingTrack;e&&(this.bufferedTrack=e,this.switchingTrack=null,this.hls.trigger(B.AUDIO_TRACK_SWITCHED,W({},e)))}this.fragBufferedComplete(n,r),this.media&&this.tick()}onError(e,t){if(t.fatal){this.state=Z.ERROR;return}switch(t.details){case z.FRAG_GAP:case z.FRAG_PARSING_ERROR:case z.FRAG_DECRYPT_ERROR:case z.FRAG_LOAD_ERROR:case z.FRAG_LOAD_TIMEOUT:case z.KEY_LOAD_ERROR:case z.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(H.AUDIO,t);break;case z.AUDIO_TRACK_LOAD_ERROR:case z.AUDIO_TRACK_LOAD_TIMEOUT:case z.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===Z.WAITING_TRACK&&t.context?.type===V.AUDIO_TRACK&&(this.state=Z.IDLE);break;case z.BUFFER_ADD_CODEC_ERROR:case z.BUFFER_APPEND_ERROR:if(t.parent!==`audio`)return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case z.BUFFER_FULL_ERROR:if(t.parent!==`audio`)return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,1/0,`audio`));break;case z.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==K.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==K.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===Z.ENDED&&(this.state=Z.IDLE);let e=this.mediaBuffer||this.media;e&&(this.afterBufferFlushed(e,t,H.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;let n=`audio`,{hls:r}=this,{remuxResult:i,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}let{frag:s,part:c,level:l}=o,{details:u}=l,{audio:d,text:f,id3:p,initSegment:m}=i;if(this.fragContextChanged(s)||!u){this.fragmentTracker.removeFragment(s);return}if(this.state=Z.PARSING,this.switchingTrack&&d&&this.completeAudioSwitch(this.switchingTrack),m!=null&&m.tracks){let e=s.initSegment||s;if(this.unhandledEncryptionError(m,s))return;this._bufferInitSegment(l,m.tracks,e,a),r.trigger(B.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:n,tracks:m.tracks})}if(d){let{startPTS:e,endPTS:t,startDTS:n,endDTS:r}=d;c&&(c.elementaryStreams[K.AUDIO]={startPTS:e,endPTS:t,startDTS:n,endDTS:r}),s.setElementaryStreamInfo(K.AUDIO,e,t,n,r),this.bufferFragmentData(d,s,c,a)}if(p!=null&&(t=p.samples)!=null&&t.length){let e=U({id:n,frag:s,details:u},p);r.trigger(B.FRAG_PARSING_METADATA,e)}if(f){let e=U({id:n,frag:s,details:u},f);r.trigger(B.FRAG_PARSING_USERDATA,e)}}_bufferInitSegment(e,t,n,r){if(this.state!==Z.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;let i=t.audio;i.id=H.AUDIO;let a=e.audioCodec;this.log(`Init audio buffer, container:${i.container}, codecs[level/parsed]=[${a}/${i.codec}]`),a&&a.split(`,`).length===1&&(i.levelCodec=a),this.hls.trigger(B.BUFFER_CODECS,t);let o=i.initSegment;if(o!=null&&o.byteLength){let e={type:`audio`,frag:n,part:null,chunkMeta:r,parent:n.type,data:o};this.hls.trigger(B.BUFFER_APPENDING,e)}this.tickImmediate()}loadFragment(e,t,n){let r=this.fragmentTracker.getState(e);if(this.switchingTrack||r===To.NOT_LOADED||r===To.PARTIAL){var i;if(!vi(e))this._loadInitSegment(e,t);else if((i=t.details)!=null&&i.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=Z.WAITING_INIT_PTS;let n=this.mainDetails;n&&n.fragmentStart!==t.details.fragmentStart&&yc(t.details,n)}else super.loadFragment(e,t,n)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){let{name:t,lang:n,assocLang:r,characteristics:i,audioCodec:a,channels:o}=this.bufferedTrack;Xa({name:t,lang:n,assocLang:r,characteristics:i,audioCodec:a,channels:o},e,$a)||(no(e.url,this.hls)?(this.log(`Switching audio track : flushing all audio`),super.flushMainBuffer(0,1/0,`audio`),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){let{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(B.AUDIO_TRACK_SWITCHED,W({},e))}},Iu=class extends Zr{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,n){let r=t?.renditionReports;if(r){let i=-1;for(let n=0;n<r.length;n++){let a=r[n],o;try{o=new self.URL(a.URI,t.url).href}catch(e){this.warn(`Could not construct new URL for Rendition Report: ${e}`),o=a.URI||``}if(o===e){i=n;break}else o===e.substring(0,o.length)&&(i=n)}if(i!==-1){let e=r[i],a=parseInt(e[`LAST-MSN`])||t.lastPartSn,o=parseInt(e[`LAST-PART`])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){let e=Math.min(t.age-t.partTarget,t.targetduration);o>=0&&e>t.partTarget&&(o+=1)}let s=n&&La(n);return new Ra(a,o>=0?o:void 0,s)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}return e}playlistLoaded(e,t,n){let{details:r,stats:i}=t,a=self.performance.now(),o=i.loading.first?Math.max(0,a-i.loading.first):0;r.advancedDateTime=Date.now()-o;let s=this.hls.config.timelineOffset;if(s!==r.appliedTimelineOffset){let e=Math.max(s||0,0);r.appliedTimelineOffset=e,r.fragments.forEach(t=>{t.setStart(t.playlistOffset+e)})}if(r.live||n!=null&&n.live){let s=`levelInfo`in t?t.levelInfo:t.track;if(r.reloaded(n),n&&r.fragments.length>0){$s(n,r,this);let e=r.playlistParsingError;if(e){this.warn(e);let n=this.hls;if(!n.config.ignorePlaylistParsingErrors){let{networkDetails:a}=t;n.trigger(B.ERROR,{type:R.NETWORK_ERROR,details:z.LEVEL_PARSING_ERROR,fatal:!1,url:r.url,error:e,reason:e.message,level:t.level||void 0,parent:r.fragments[0]?.type,networkDetails:a,stats:i});return}r.playlistParsingError=null}}r.requestScheduled===-1&&(r.requestScheduled=i.loading.start);let c=this.hls.mainForwardBufferInfo,l=c?c.end-c.len:0,u=oc(r,(r.edge-l)*1e3);if(r.requestScheduled+u<a?r.requestScheduled=a:r.requestScheduled+=u,this.log(`live playlist ${e} ${r.advanced?`REFRESHED `+r.lastPartSn+`-`+r.lastPartIndex:r.updated?`UPDATED`:`MISSED`}`),!this.canLoad||!r.live)return;let d,f,p;if(r.canBlockReload&&r.endSN&&r.advanced){let e=this.hls.config.lowLatencyMode,i=r.lastPartSn,o=r.endSN,c=r.lastPartIndex,l=c!==-1,u=i===o;l?u?(f=o+1,p=e?0:c):(f=i,p=e?c+1:r.maxPartIndex):f=o+1;let m=r.age,h=m+r.ageHeader,g=Math.min(h-r.partTarget,r.targetduration*1.5);if(g>0){if(h>r.targetduration*3)this.log(`Playlist last advanced ${m.toFixed(2)}s ago. Omitting segment and part directives.`),f=void 0,p=void 0;else if(n!=null&&n.tuneInGoal&&h-r.partTarget>n.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${n.tuneInGoal} to: ${g} with playlist age: ${r.age}`),g=0;else{let e=Math.floor(g/r.targetduration);if(f+=e,p!==void 0){let e=Math.round(g%r.targetduration/r.partTarget);p+=e}this.log(`CDN Tune-in age: ${r.ageHeader}s last advanced ${m.toFixed(2)}s goal: ${g} skip sn ${e} to part ${p}`)}r.tuneInGoal=g}if(d=this.getDeliveryDirectives(r,t.deliveryDirectives,f,p),e||!u){r.requestScheduled=a,this.loadingPlaylist(s,d);return}}else (r.canBlockReload||r.canSkipUntil)&&(d=this.getDeliveryDirectives(r,t.deliveryDirectives,f,p));d&&f!==void 0&&r.canBlockReload&&(r.requestScheduled=i.loading.first+Math.max(u-o*2,u/2)),this.scheduleLoading(s,d,r)}else this.clearTimer()}scheduleLoading(e,t,n){let r=n||e.details;if(!r){this.loadingPlaylist(e,t);return}let i=self.performance.now(),a=r.requestScheduled;if(i>=a){this.loadingPlaylist(e,t);return}let o=a-i;this.log(`reload live playlist ${e.name||e.bitrate+`bps`} in ${Math.round(o)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),o)}getDeliveryDirectives(e,t,n,r){let i=La(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(n=t.msn,r=t.part,i=Ia.No),new Ra(n,r,i)}checkRetry(e){let t=e.details,n=fo(e),r=e.errorAction,{action:i,retryCount:a=0,retryConfig:o}=r||{},s=!!r&&!!o&&(i===xo.RetryRequest||!r.resolved&&i===xo.SendAlternateToPenaltyBox);if(s){var c;if(a>=o.maxNumRetry)return!1;if(n&&(c=e.context)!=null&&c.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{let e=go(o,a);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),e),this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" in ${e}ms`)}e.levelRetry=!0,r.resolved=!0}return s}};function Lu(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!Ru(e[n].attrs,t[n].attrs))return!1;return!0}function Ru(e,t,n){let r=e[`STABLE-RENDITION-ID`];return r&&!n?r===t[`STABLE-RENDITION-ID`]:!(n||[`LANGUAGE`,`NAME`,`CHARACTERISTICS`,`AUTOSELECT`,`DEFAULT`,`FORCED`,`ASSOC-LANGUAGE`]).some(n=>e[n]!==t[n])}function zu(e,t){return t.label.toLowerCase()===e.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(e.lang||``).toLowerCase())}var Bu=class extends Iu{constructor(e){super(e,`audio-track-controller`),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){let{hls:e}=this;e.on(B.MANIFEST_LOADING,this.onManifestLoading,this),e.on(B.MANIFEST_PARSED,this.onManifestParsed,this),e.on(B.LEVEL_LOADING,this.onLevelLoading,this),e.on(B.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(B.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(B.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(B.MANIFEST_LOADING,this.onManifestLoading,this),e.off(B.MANIFEST_PARSED,this.onManifestParsed,this),e.off(B.LEVEL_LOADING,this.onLevelLoading,this),e.off(B.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(B.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(B.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){let{id:n,groupId:r,details:i}=t,a=this.tracksInGroup[n];if(!a||a.groupId!==r){this.warn(`Audio track with id:${n} and group:${r} not found in active group ${a?.groupId}`);return}let o=a.details;a.details=t.details,this.log(`Audio track ${n} "${a.name}" lang:${a.lang} group:${r} loaded [${i.startSN}-${i.endSN}]`),n===this.trackId&&this.playlistLoaded(n,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){let t=this.hls.levels[e];if(!t)return;let n=t.audioGroups||null,r=this.groupIds,i=this.currentTrack;if(!n||r?.length!==n?.length||n!=null&&n.some(e=>r?.indexOf(e)===-1)){this.groupIds=n,this.trackId=-1,this.currentTrack=null;let e=this.tracks.filter(e=>!n||n.indexOf(e.groupId)!==-1);if(e.length)this.selectDefaultTrack&&!e.some(e=>e.default)&&(this.selectDefaultTrack=!1),e.forEach((e,t)=>{e.id=t});else if(!i&&!this.tracksInGroup.length)return;this.tracksInGroup=e;let t=this.hls.config.audioPreference;if(!i&&t){let n=Ya(t,e,$a);if(n>-1)i=e[n];else{let e=Ya(t,this.tracks);i=this.tracks[e]}}let r=this.findTrackId(i);r===-1&&i&&(r=this.findTrackId(null));let a={audioTracks:e};this.log(`Updating audio tracks, ${e.length} track(s) found in group(s): ${n?.join(`,`)}`),this.hls.trigger(B.AUDIO_TRACKS_UPDATED,a);let o=this.trackId;if(r!==-1&&o===-1)this.setAudioTrack(r);else if(e.length&&o===-1){let t=Error(`No audio track selected for current audio group-ID(s): ${this.groupIds?.join(`,`)} track count: ${e.length}`);this.warn(t.message),this.hls.trigger(B.ERROR,{type:R.MEDIA_ERROR,details:z.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:t})}}}onError(e,t){t.fatal||!t.context||t.context.type===V.AUDIO_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){let t=this.hls;if(t.config.audioPreference=e,e){let n=this.allAudioTracks;if(this.selectDefaultTrack=!1,n.length){let r=this.currentTrack;if(r&&Xa(e,r,$a))return r;let i=Ya(e,this.tracksInGroup,$a);if(i>-1){let e=this.tracksInGroup[i];return this.setAudioTrack(i),e}else if(r){let r=t.loadLevel;r===-1&&(r=t.firstAutoLevel);let i=eo(e,t.levels,n,r,$a);if(i===-1)return null;t.nextLoadLevel=i}if(e.channels||e.audioCodec){let t=Ya(e,n);if(t>-1)return n[t]}}}return null}setAudioTrack(e){let t=this.tracksInGroup;if(e<0||e>=t.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;let n=this.currentTrack,r=t[e],i=r.details&&!r.details.live;if(e===this.trackId&&r===n&&i||(this.log(`Switching to audio-track ${e} "${r.name}" lang:${r.lang} group:${r.groupId} channels:${r.channels}`),this.trackId=e,this.currentTrack=r,this.hls.trigger(B.AUDIO_TRACK_SWITCHING,W({},r)),i))return;let a=this.switchParams(r.url,n?.details,r.details);this.loadPlaylist(a)}findTrackId(e){let t=this.tracksInGroup;for(let n=0;n<t.length;n++){let r=t[n];if(!(this.selectDefaultTrack&&!r.default)&&(!e||Xa(e,r,$a)))return n}if(e){let{name:n,lang:r,assocLang:i,characteristics:a,audioCodec:o,channels:s}=e;for(let e=0;e<t.length;e++){let c=t[e];if(Xa({name:n,lang:r,assocLang:i,characteristics:a,audioCodec:o,channels:s},c,$a))return e}for(let n=0;n<t.length;n++){let r=t[n];if(Ru(e.attrs,r.attrs,[`LANGUAGE`,`ASSOC-LANGUAGE`,`CHARACTERISTICS`]))return n}for(let n=0;n<t.length;n++){let r=t[n];if(Ru(e.attrs,r.attrs,[`LANGUAGE`]))return n}}return-1}loadPlaylist(e){super.loadPlaylist();let t=this.currentTrack;this.shouldLoadPlaylist(t)&&no(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let n=e.id,r=e.groupId,i=this.getUrlWithDirectives(e.url,t),a=e.details,o=a?.age;this.log(`Loading audio-track ${n} "${e.name}" lang:${e.lang} group:${r}${t?.msn===void 0?``:` at sn `+t.msn+` part `+t.part}${o&&a.live?` age `+o.toFixed(1)+(a.type&&` `+a.type||``):``} ${i}`),this.hls.trigger(B.AUDIO_TRACK_LOADING,{url:i,id:n,groupId:r,deliveryDirectives:t||null,track:e})}},Vu=class{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,n){if(this.queues===null||this.tracks===null)return;let r=this.queues[t];r.push(e),r.length===1&&!n&&this.executeNext(t)}appendBlocker(e){return new Promise(t=>{let n={label:`async-blocker`,execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(n,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){let n={label:`async-blocker-prepend`,execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(n)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{let t=e[0]?.label;(t===`async-blocker`||t===`async-blocker-prepend`)&&(e[0].execute(),e.splice(0,1))})}unblockAudio(e){this.queues!==null&&this.queues.audio[0]===e&&this.shiftAndExecuteNext(`audio`)}executeNext(e){if(this.queues===null||this.tracks===null)return;let t=this.queues[e];if(t.length){let n=t[0];try{n.execute()}catch(t){if(n.onError(t),this.queues===null||this.tracks===null)return;let r=this.tracks[e]?.buffer;r!=null&&r.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues!==null&&(this.queues[e].shift(),this.executeNext(e))}current(e){return this.queues?.[e][0]||null}toString(){let{queues:e,tracks:t}=this;return e===null||t===null?`<destroyed>`:`
24
+ ${this.list(`video`)}
25
+ ${this.list(`audio`)}
26
+ ${this.list(`audiovideo`)}}`}list(e){var t,n;return(t=this.queues)!=null&&t[e]||(n=this.tracks)!=null&&n[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:``}listSbInfo(e){let t=this.tracks?.[e],n=t?.buffer;return n?`SourceBuffer${n.updating?` updating`:``}${t.ended?` ended`:``}${t.ending?` ending`:``}`:`none`}listOps(e){return this.queues?.[e].map(e=>e.label).join(`, `)||``}},Hu=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,Uu=`HlsJsTrackRemovedError`,Wu=class extends Error{constructor(e){super(e),this.name=Uu}},Gu=class extends Zr{constructor(e,t){super(`buffer-controller`,e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=e=>{this.hls&&this.mediaSource?.readyState===`open`&&this.hls.pauseBuffering()},this._onStartStreaming=e=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=e=>{let{media:t,mediaSource:n}=this;e&&this.log(`Media source opened`),!(!t||!n)&&(n.removeEventListener(`sourceopen`,this._onMediaSourceOpen),t.removeEventListener(`emptied`,this._onMediaEmptied),this.updateDuration(),this.hls.trigger(B.MEDIA_ATTACHED,{media:t,mediaSource:n}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log(`Media source closed`)},this._onMediaSourceEnded=()=>{this.log(`Media source ended`)},this._onMediaEmptied=()=>{let{mediaSrc:e,_objectUrl:t}=this;e!==t&&this.error(`Media element src was set while attaching MediaSource (${t} > ${e})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=oi(ai(e.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&=(this.operationQueue.destroy(),null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){let{hls:e}=this;e.on(B.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(B.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(B.MANIFEST_LOADING,this.onManifestLoading,this),e.on(B.MANIFEST_PARSED,this.onManifestParsed,this),e.on(B.BUFFER_RESET,this.onBufferReset,this),e.on(B.BUFFER_APPENDING,this.onBufferAppending,this),e.on(B.BUFFER_CODECS,this.onBufferCodecs,this),e.on(B.BUFFER_EOS,this.onBufferEos,this),e.on(B.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(B.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(B.FRAG_PARSED,this.onFragParsed,this),e.on(B.FRAG_CHANGED,this.onFragChanged,this),e.on(B.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(B.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(B.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(B.MANIFEST_LOADING,this.onManifestLoading,this),e.off(B.MANIFEST_PARSED,this.onManifestParsed,this),e.off(B.BUFFER_RESET,this.onBufferReset,this),e.off(B.BUFFER_APPENDING,this.onBufferAppending,this),e.off(B.BUFFER_CODECS,this.onBufferCodecs,this),e.off(B.BUFFER_EOS,this.onBufferEos,this),e.off(B.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(B.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(B.FRAG_PARSED,this.onFragParsed,this),e.off(B.FRAG_CHANGED,this.onFragChanged,this),e.off(B.ERROR,this.onError,this)}transferMedia(){let{media:e,mediaSource:t}=this;if(!e)return null;let n={};if(this.operationQueue){let e=this.isUpdating();e||this.operationQueue.removeBlockers();let t=this.isQueued();(e||t)&&this.warn(`Transfering MediaSource with${t?` operations in queue`:``}${e?` updating SourceBuffer(s)`:``} ${this.operationQueue}`),this.operationQueue.destroy()}let r=this.transferData;return!this.sourceBufferCount&&r&&r.mediaSource===t?U(n,r.tracks):this.sourceBuffers.forEach(e=>{let[t]=e;t&&(n[t]=U({},this.tracks[t]),this.removeBuffer(t)),e[0]=e[1]=null}),{media:e,mediaSource:t,tracks:n}}initTracks(){this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){var n;let r=2;(t.audio&&!t.video||!t.altAudio)&&(r=1),this.bufferCodecEventsTotal=r,this.log(`${r} bufferCodec event(s) expected.`),(n=this.transferData)!=null&&n.mediaSource&&this.sourceBufferCount&&r&&this.bufferCreated()}onMediaAttaching(e,t){let n=this.media=t.media;this.transferData=this.overrides=void 0;let r=ai(this.appendSource);if(r){let e=!!t.mediaSource;(e||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);let i=this.mediaSource=t.mediaSource||new r;if(this.assignMediaSource(i),e)this._objectUrl=n.src,this.attachTransferred();else{let e=this._objectUrl=self.URL.createObjectURL(i);if(this.appendSource)try{n.removeAttribute(`src`);let t=self.ManagedMediaSource;n.disableRemotePlayback=n.disableRemotePlayback||t&&i instanceof t,Ku(n),qu(n,e),n.load()}catch{n.src=e}else n.src=e}n.addEventListener(`emptied`,this._onMediaEmptied)}}assignMediaSource(e){this.log(`${this.transferData?.mediaSource===e?`transferred`:`created`} media source: ${e.constructor?.name}`),e.addEventListener(`sourceopen`,this._onMediaSourceOpen),e.addEventListener(`sourceended`,this._onMediaSourceEnded),e.addEventListener(`sourceclose`,this._onMediaSourceClose),this.appendSource&&(e.addEventListener(`startstreaming`,this._onStartStreaming),e.addEventListener(`endstreaming`,this._onEndStreaming))}attachTransferred(){let e=this.media,t=this.transferData;if(!t||!e)return;let n=this.tracks,r=t.tracks,i=r?Object.keys(r):null,a=i?i.length:0,o=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(r&&i&&a){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log(`attachTransferred: waiting for SourceBuffer track info`);return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
27
+ required tracks: ${Y(n,(e,t)=>e===`initSegment`?void 0:t)};
28
+ transfer tracks: ${Y(r,(e,t)=>e===`initSegment`?void 0:t)}}`),!si(r,n)){t.mediaSource=null,t.tracks=void 0;let i=e.currentTime,a=this.details,o=Math.max(i,a?.fragments[0].start||0);if(o-i>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${i} -> ${o}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(r)}"->"${Object.keys(n)}") start time: ${o} currentTime: ${i}`),this.onMediaDetaching(B.MEDIA_DETACHING,{}),this.onMediaAttaching(B.MEDIA_ATTACHING,t),e.currentTime=o;return}this.transferData=void 0,i.forEach(e=>{let t=e,n=r[t];if(n){let e=n.buffer;if(e){let r=this.fragmentTracker,i=n.id;if(r.hasFragments(i)||r.hasParts(i)){let n=X.getBuffered(e);r.detectEvictedFragments(t,n,i,null,!0)}let a=Ju(t),o=[t,e];this.sourceBuffers[a]=o,e.updating&&this.operationQueue&&this.operationQueue.prependBlocker(t),this.trackSourceBuffer(t,n)}}}),o(),this.bufferCreated()}else this.log(`attachTransferred: MediaSource w/o SourceBuffers`),o()}get mediaSourceOpenOrEnded(){let e=this.mediaSource?.readyState;return e===`open`||e===`ended`}onMediaDetaching(e,t){let n=!!t.transferMedia;this.transferData=this.overrides=void 0;let{media:r,mediaSource:i,_objectUrl:a}=this;if(i){if(this.log(`media source ${n?`transferring`:`detaching`}`),n)this.sourceBuffers.forEach(([e])=>{e&&this.removeBuffer(e)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){let e=i.readyState===`open`;try{let t=i.sourceBuffers;for(let n=t.length;n--;)e&&t[n].abort(),i.removeSourceBuffer(t[n]);e&&i.endOfStream()}catch(e){this.warn(`onMediaDetaching: ${e.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}i.removeEventListener(`sourceopen`,this._onMediaSourceOpen),i.removeEventListener(`sourceended`,this._onMediaSourceEnded),i.removeEventListener(`sourceclose`,this._onMediaSourceClose),this.appendSource&&(i.removeEventListener(`startstreaming`,this._onStartStreaming),i.removeEventListener(`endstreaming`,this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}r&&(r.removeEventListener(`emptied`,this._onMediaEmptied),n||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a?(r.removeAttribute(`src`),this.appendSource&&Ku(r),r.load()):this.warn(`media|source.src was changed by a third party - skip cleanup`)),this.media=null),this.hls.trigger(B.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){let t=this.tracks[e]?.buffer;if(this.removeBuffer(e),t)try{var n;(n=this.mediaSource)!=null&&n.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(t)}catch(t){this.warn(`onBufferReset ${e}`,t)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[Ju(e)]=[null,null];let t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new Vu(this.tracks)}onBufferCodecs(e,t){let n=this.tracks,r=Object.keys(t);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);let i=`audiovideo`in t&&(n.audio||n.video)||n.audiovideo&&(`audio`in t||`video`in t),a=!i&&this.sourceBufferCount&&this.media&&r.some(e=>!n[e]);if(i||a){this.warn(`Unsupported transition between "${Object.keys(n)}" and "${r}" SourceBuffers`);return}r.forEach(e=>{var r;let{id:i,codec:a,levelCodec:o,container:s,metadata:c,supplemental:l}=t[e],u=n[e],d=(r=this.transferData)==null||(r=r.tracks)==null?void 0:r[e],f=d!=null&&d.buffer?d:u,p=f?.pendingCodec||f?.codec,m=f?.levelCodec;u||=n[e]={buffer:void 0,listeners:[],codec:a,supplemental:l,container:s,levelCodec:o,metadata:c,id:i};let h=ha(p,m),g=h?.replace(Hu,`$1`),_=ha(a,o),v=_?.replace(Hu,`$1`);_&&h&&g!==v&&(e.slice(0,5)===`audio`&&(_=pa(_,this.appendSource)),this.log(`switching codec ${p} to ${_}`),_!==(u.pendingCodec||u.codec)&&(u.pendingCodec=_),u.container=s,this.appendChangeType(e,s,_))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&t.audio?.id===`main`&&(this.log(`Main audio-only`),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{let n=this.tracks[t];return e[t]={id:n.id,container:n.container,codec:n.codec,levelCodec:n.levelCodec},e},{})}appendChangeType(e,t,n){let r=`${t};codecs=${n}`,i={label:`change-type=${r}`,execute:()=>{let i=this.tracks[e];if(i){let a=i.buffer;a!=null&&a.changeType&&(this.log(`changing ${e} sourceBuffer type to ${r}`),a.changeType(r),i.codec=n,i.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn(`Failed to change ${e} SourceBuffer type`,t)}};this.append(i,e,this.isPending(this.tracks[e]))}blockAudio(e){let t=e.start,n=t+e.duration*.05;if(this.fragmentTracker.getAppendedFrag(t,H.MAIN)?.gap===!0)return;let r={label:`block-audio`,execute:()=>{let e=this.tracks.video;(this.lastVideoAppendEnd>n||e!=null&&e.buffer&&X.isBuffered(e.buffer,n)||this.fragmentTracker.getAppendedFrag(n,H.MAIN)?.gap===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext(`audio`))},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn(`Error executing block-audio operation`,e)}};this.blockedAudioAppend={op:r,frag:e},this.append(r,`audio`,!0)}unblockAudio(){let{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){let{tracks:n}=this,{data:r,type:i,parent:a,frag:o,part:s,chunkMeta:c,offset:l}=t,u=c.buffering[i],{sn:d,cc:f}=o,p=self.performance.now();u.start=p;let m=o.stats.buffering,h=s?s.stats.buffering:null;m.start===0&&(m.start=p),h&&h.start===0&&(h.start=p);let g=n.audio,_=!1;i===`audio`&&g?.container===`audio/mpeg`&&(_=!this.lastMpegAudioChunk||c.id===1||this.lastMpegAudioChunk.sn!==c.sn,this.lastMpegAudioChunk=c);let v=n.video,y=v?.buffer;if(y&&d!==`initSegment`){let e=s||o,t=this.blockedAudioAppend;if(i===`audio`&&a!==`main`&&!this.blockedAudioAppend&&!(v.ending||v.ended)){let t=e.start+e.duration*.05,n=y.buffered,r=this.currentOp(`video`);(!n.length&&!r||!r&&!X.isBuffered(y,t)&&this.lastVideoAppendEnd<t)&&this.blockAudio(e)}else if(i===`video`){let n=e.end;if(t){let e=t.frag.start;(n>e||n<this.lastVideoAppendEnd||X.isBuffered(y,e))&&this.unblockAudio()}this.lastVideoAppendEnd=n}}let b=(s||o).start,x={label:`append-${i}`,execute:()=>{u.executeStart=self.performance.now();let e=this.tracks[i]?.buffer;e&&(_?this.updateTimestampOffset(e,b,.1,i,d,f):l!==void 0&&L(l)&&this.updateTimestampOffset(e,l,1e-6,i,d,f)),this.appendExecutor(r,i)},onStart:()=>{},onComplete:()=>{let e=self.performance.now();u.executeEnd=u.end=e,m.first===0&&(m.first=e),h&&h.first===0&&(h.first=e);let t={};this.sourceBuffers.forEach(([e,n])=>{e&&(t[e]=X.getBuffered(n))}),this.appendErrors[i]=0,i===`audio`||i===`video`?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(B.BUFFER_APPENDED,{type:i,frag:o,part:s,chunkMeta:c,parent:o.type,timeRanges:t})},onError:e=>{let t={type:R.MEDIA_ERROR,parent:o.type,details:z.BUFFER_APPEND_ERROR,sourceBufferName:i,frag:o,part:s,chunkMeta:c,error:e,err:e,fatal:!1},n=this.media?.error;if(e.code===DOMException.QUOTA_EXCEEDED_ERR||e.name==`QuotaExceededError`||`quota`in e)t.details=z.BUFFER_FULL_ERROR;else if(e.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!n)t.errorAction=wo(!0);else if(e.name===Uu&&this.sourceBufferCount===0)t.errorAction=wo(!0);else{let e=++this.appendErrors[i];this.warn(`Failed ${e}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${i}" sourceBuffer (${n||`no media error`})`),(e>=this.hls.config.appendErrorMaxRetry||n)&&(t.fatal=!0)}this.hls.trigger(B.ERROR,t)}};this.log(`queuing "${i}" append sn: ${d}${s?` p: `+s.index:``} of ${o.type===H.MAIN?`level`:`track`} ${o.level} cc: ${f}`),this.append(x,i,this.isPending(this.tracks[i]))}getFlushOp(e,t,n){return this.log(`queuing "${e}" remove ${t}-${n}`),{label:`remove`,execute:()=>{this.removeExecutor(e,t,n)},onStart:()=>{},onComplete:()=>{this.hls.trigger(B.BUFFER_FLUSHED,{type:e})},onError:r=>{this.warn(`Failed to remove ${t}-${n} from "${e}" SourceBuffer`,r)}}}onBufferFlushing(e,t){let{type:n,startOffset:r,endOffset:i}=t;n?this.append(this.getFlushOp(n,r,i),n):this.sourceBuffers.forEach(([e])=>{e&&this.append(this.getFlushOp(e,r,i),e)})}onFragParsed(e,t){let{frag:n,part:r}=t,i=[],a=r?r.elementaryStreams:n.elementaryStreams;a[K.AUDIOVIDEO]?i.push(`audiovideo`):(a[K.AUDIO]&&i.push(`audio`),a[K.VIDEO]&&i.push(`video`)),i.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${n.type} level: ${n.level} sn: ${n.sn}`),this.blockBuffers(()=>{let e=self.performance.now();n.stats.buffering.end=e,r&&(r.stats.buffering.end=e);let t=r?r.stats:n.stats;this.hls.trigger(B.FRAG_BUFFERED,{frag:n,part:r,stats:t,id:n.type})},i).catch(e=>{this.warn(`Fragment buffered callback ${e}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){let t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){this.sourceBuffers.forEach(([e])=>{if(e){let n=this.tracks[e];(!t.type||t.type===e)&&(n.ending=!0,n.ended||(n.ended=!0,this.log(`${e} buffer reached EOS`)))}});let n=this.overrides?.endOfStream!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{var t;return e&&!((t=this.tracks[e])!=null&&t.ended)})?n?(this.log(`Queueing EOS`),this.blockUntilOpen(()=>{this.tracksEnded();let{mediaSource:e}=this;if(!e||e.readyState!==`open`){e&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${e.readyState}`);return}this.log(`Calling mediaSource.endOfStream()`),e.endOfStream(),this.hls.trigger(B.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(B.BUFFERED_TO_END,void 0)):t.type===`video`&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){let t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{let e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===z.BUFFER_APPEND_ERROR&&t.frag){let e=t.errorAction?.nextAutoLevel;L(e)&&e!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){let{hls:e,details:t,media:n}=this;if(!n||t===null||!this.sourceBufferCount)return;let r=e.config,i=n.currentTime,a=t.levelTargetDuration,o=t.live&&r.liveBackBufferLength!==null?r.liveBackBufferLength:r.backBufferLength;if(L(o)&&o>=0){let e=Math.max(o,a),t=Math.floor(i/a)*a-e;this.flushBackBuffer(i,a,t)}let s=r.frontBufferFlushThreshold;if(L(s)&&s>0){let e=Math.max(r.maxBufferLength,s),t=Math.max(e,a),n=Math.floor(i/a)*a+t;this.flushFrontBuffer(i,a,n)}}flushBackBuffer(e,t,n){this.sourceBuffers.forEach(([e,t])=>{if(t){let i=X.getBuffered(t);if(i.length>0&&n>i.start(0)){var r;this.hls.trigger(B.BACK_BUFFER_REACHED,{bufferEnd:n});let t=this.tracks[e];if((r=this.details)!=null&&r.live)this.hls.trigger(B.LIVE_BACK_BUFFER_REACHED,{bufferEnd:n});else if(t!=null&&t.ended){this.log(`Cannot flush ${e} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(B.BUFFER_FLUSHING,{startOffset:0,endOffset:n,type:e})}}})}flushFrontBuffer(e,t,n){this.sourceBuffers.forEach(([t,r])=>{if(r){let i=X.getBuffered(r),a=i.length;if(a<2)return;let o=i.start(a-1),s=i.end(a-1);if(n>o||e>=o&&e<=s)return;this.hls.trigger(B.BUFFER_FLUSHING,{startOffset:o,endOffset:1/0,type:t})}})}getDurationAndRange(){let{details:e,mediaSource:t}=this;if(!e||!this.media||t?.readyState!==`open`)return null;let n=e.edge;if(e.live&&this.hls.config.liveDurationInfinity){if(e.fragments.length&&t.setLiveSeekableRange){let t=Math.max(0,e.fragmentStart);return{duration:1/0,start:t,end:Math.max(t,n)}}return{duration:1/0}}let r=this.overrides?.duration;if(r)return L(r)?{duration:r}:null;let i=this.media.duration;return n>(L(t.duration)?t.duration:0)&&n>i||!L(i)?{duration:n}:null}updateMediaSource({duration:e,start:t,end:n}){let r=this.mediaSource;!this.media||!r||r.readyState!==`open`||(r.duration!==e&&(L(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),r.duration=e),t!==void 0&&n!==void 0&&(this.log(`MediaSource duration is set to ${r.duration}. Setting seekable range to ${t}-${n}.`),r.setLiveSeekableRange(t,n)))}get tracksReady(){let e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){let{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:n}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${Y(n)}`),this.tracksReady){let e=this.transferData?.tracks;e&&Object.keys(e).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){let e={};this.sourceBuffers.forEach(([t,n])=>{if(t){let r=this.tracks[t];e[t]={buffer:n,container:r.container,codec:r.codec,supplemental:r.supplemental,levelCodec:r.levelCodec,id:r.id,metadata:r.metadata}}}),this.hls.trigger(B.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([e])=>{this.executeNext(e)})}else{let e=Error(`could not create source buffer for media codec(s)`);this.hls.trigger(B.ERROR,{type:R.MEDIA_ERROR,details:z.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){let{tracks:e,sourceBuffers:t,mediaSource:n}=this;if(!n)throw Error(`createSourceBuffers called when mediaSource was null`);for(let i in e){let a=i,o=e[a];if(this.isPending(o)){let e=this.getTrackCodec(o,a),i=`${o.container};codecs=${e}`;o.codec=e,this.log(`creating sourceBuffer(${i})${this.currentOp(a)?` Queued`:``} ${Y(o)}`);try{let e=n.addSourceBuffer(i),r=Ju(a);t[r]=[a,e],o.buffer=e}catch(e){var r;this.error(`error while trying to add sourceBuffer: ${e.message}`),this.shiftAndExecuteNext(a),(r=this.operationQueue)==null||r.removeBlockers(),delete this.tracks[a],this.hls.trigger(B.ERROR,{type:R.MEDIA_ERROR,details:z.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,sourceBufferName:a,mimeType:i,parent:o.id});return}this.trackSourceBuffer(a,o)}}this.bufferCreated()}getTrackCodec(e,t){let n=e.supplemental,r=e.codec;n&&(t===`video`||t===`audiovideo`)&&aa(n,`video`)&&(r=ma(r,n));let i=ha(r,e.levelCodec);return i?t.slice(0,5)===`audio`?pa(i,this.appendSource):i:``}trackSourceBuffer(e,t){let n=t.buffer;if(!n)return;let r=this.getTrackCodec(t,e);this.tracks[e]={buffer:n,codec:r,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,`updatestart`,this.onSBUpdateStart),this.addBufferListener(e,`updateend`,this.onSBUpdateEnd),this.addBufferListener(e,`error`,this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,`bufferedchange`,(e,t)=>{let n=t.removedRanges;n!=null&&n.length&&this.hls.trigger(B.BUFFER_FLUSHED,{type:e})})}get mediaSrc(){var e,t;return(((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,`source`))||this.media)?.src}onSBUpdateStart(e){let t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){if(this.mediaSource?.readyState===`closed`){this.resetBuffer(e);return}let t=this.currentOp(e);t&&(t.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){let n=Error(`${e} SourceBuffer error. MediaSource readyState: ${this.mediaSource?.readyState}`);this.error(`${n}`,t),this.hls.trigger(B.ERROR,{type:R.MEDIA_ERROR,details:z.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:n,fatal:!1});let r=this.currentOp(e);r&&r.onError(n)}updateTimestampOffset(e,t,n,r,i,a){let o=t-e.timestampOffset;Math.abs(o)>=n&&(this.log(`Updating ${r} SourceBuffer timestampOffset to ${t} (sn: ${i} cc: ${a})`),e.timestampOffset=t)}removeExecutor(e,t,n){let{media:r,mediaSource:i}=this,a=this.tracks[e],o=a?.buffer;if(!r||!i||!o){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}let s=L(r.duration)?r.duration:1/0,c=L(i.duration)?i.duration:1/0,l=Math.max(0,t),u=Math.min(n,s,c);u>l&&(!a.ending||a.ended)?(a.ended=!1,this.log(`Removing [${l},${u}] from the ${e} SourceBuffer`),o.remove(l,u)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){let n=this.tracks[t],r=n?.buffer;if(!r)throw new Wu(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);n.ending=!1,n.ended=!1,r.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(e=>{this.warn(`SourceBuffer blocked callback ${e}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(e){this.warn(`Callback run without blocking ${this.operationQueue} ${e}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log(`Blocking operation requested, but no SourceBuffers exist`),Promise.resolve().then(e);let{operationQueue:n}=this,r=t.map(e=>this.appendBlocker(e));return t.length>1&&this.blockedAudioAppend&&this.unblockAudio(),Promise.all(r).then(t=>{n===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(e=>{let t=this.tracks[e]?.buffer;!t||t.updating||this.shiftAndExecuteNext(e)})}append(e,t,n){this.operationQueue&&this.operationQueue.append(e,t,n)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,n){let r=this.tracks[e];if(!r)return;let i=r.buffer;if(!i)return;let a=n.bind(this,e);r.listeners.push({event:t,listener:a}),i.addEventListener(t,a)}removeBufferListeners(e){let t=this.tracks[e];if(!t)return;let n=t.buffer;n&&(t.listeners.forEach(e=>{n.removeEventListener(e.event,e.listener)}),t.listeners.length=0)}};function Ku(e){let t=e.querySelectorAll(`source`);[].slice.call(t).forEach(t=>{e.removeChild(t)})}function qu(e,t){let n=self.document.createElement(`source`);n.type=`video/mp4`,n.src=t,e.appendChild(n)}function Ju(e){return e===`audio`?1:0}var Yu=class e{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=1/0,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){let{hls:e}=this;e.on(B.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(B.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(B.MANIFEST_PARSED,this.onManifestParsed,this),e.on(B.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(B.BUFFER_CODECS,this.onBufferCodecs,this),e.on(B.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){let{hls:e}=this;e.off(B.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(B.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(B.MANIFEST_PARSED,this.onManifestParsed,this),e.off(B.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(B.BUFFER_CODECS,this.onBufferCodecs,this),e.off(B.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){let n=this.hls.levels[t.droppedLevel];this.isLevelAllowed(n)&&this.restrictedLevels.push({bitrate:n.bitrate,height:n.height,width:n.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){let n=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,n.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&L(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}let e=this.hls.levels;if(e.length){let t=this.hls,n=this.getMaxLevel(e.length-1);n!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${n}: ${e[n].height}p@${e[n].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=n,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(t){let n=this.hls.levels;if(!n.length)return-1;let r=n.filter((e,n)=>this.isLevelAllowed(e)&&n<=t);return this.clientRect=null,e.getMaxLevelByMediaSize(r,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=1/0,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=1/0,this.timer&&=(self.clearInterval(this.timer),void 0)}getDimensions(){if(this.clientRect)return this.clientRect;let e=this.media,t={width:0,height:0};if(e){let n=e.getBoundingClientRect();t.width=n.width,t.height=n.height,!t.width&&!t.height&&(t.width=n.right-n.left||e.width||0,t.height=n.bottom-n.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch{}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some(t=>e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height)}static getMaxLevelByMediaSize(e,t,n){if(!(e!=null&&e.length))return-1;let r=(e,t)=>t?e.width!==t.width||e.height!==t.height:!0,i=e.length-1,a=Math.max(t,n);for(let t=0;t<e.length;t+=1){let n=e[t];if((n.width>=a||n.height>=a)&&r(n,e[t+1])){i=t;break}}return i}},Xu={MANIFEST:`m`,AUDIO:`a`,VIDEO:`v`,MUXED:`av`,INIT:`i`,CAPTION:`c`,TIMED_TEXT:`tt`,KEY:`k`,OTHER:`o`},Zu={HLS:`h`},Qu=class e{constructor(t,n){Array.isArray(t)&&(t=t.map(t=>t instanceof e?t:new e(t))),this.value=t,this.params=n}},$u=`Dict`;function ed(e){return Array.isArray(e)?JSON.stringify(e):e instanceof Map?`Map{}`:e instanceof Set?`Set{}`:typeof e==`object`?JSON.stringify(e):String(e)}function td(e,t,n,r){return Error(`failed to ${e} "${ed(t)}" as ${n}`,{cause:r})}function nd(e,t,n){return td(`serialize`,e,t,n)}var rd=class{constructor(e){this.description=e}},id=`Bare Item`,ad=`Boolean`;function od(e){if(typeof e!=`boolean`)throw nd(e,ad);return e?`?1`:`?0`}function sd(e){return btoa(String.fromCharCode(...e))}var cd=`Byte Sequence`;function ld(e){if(ArrayBuffer.isView(e)===!1)throw nd(e,cd);return`:${sd(e)}:`}var ud=`Integer`;function dd(e){return e<-999999999999999||999999999999999<e}function fd(e){if(dd(e))throw nd(e,ud);return e.toString()}function pd(e){return`@${fd(e.getTime()/1e3)}`}function md(e,t){if(e<0)return-md(-e,t);let n=10**t;if(Math.abs(e*n%1-.5)<2**-52){let t=Math.floor(e*n);return(t%2==0?t:t+1)/n}else return Math.round(e*n)/n}var hd=`Decimal`;function gd(e){let t=md(e,3);if(Math.floor(Math.abs(t)).toString().length>12)throw nd(e,hd);let n=t.toString();return n.includes(`.`)?n:`${n}.0`}var _d=`String`,vd=/[\x00-\x1f\x7f]+/;function yd(e){if(vd.test(e))throw nd(e,_d);return`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`}function bd(e){return e.description||e.toString().slice(7,-1)}var xd=`Token`;function Sd(e){let t=bd(e);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t)===!1)throw nd(t,xd);return t}function Cd(e){switch(typeof e){case`number`:if(!L(e))throw nd(e,id);return Number.isInteger(e)?fd(e):gd(e);case`string`:return yd(e);case`symbol`:return Sd(e);case`boolean`:return od(e);case`object`:if(e instanceof Date)return pd(e);if(e instanceof Uint8Array)return ld(e);if(e instanceof rd)return Sd(e);default:throw nd(e,id)}}var wd=`Key`;function Td(e){if(/^[a-z*][a-z0-9\-_.*]*$/.test(e)===!1)throw nd(e,wd);return e}function Ed(e){return e==null?``:Object.entries(e).map(([e,t])=>t===!0?`;${Td(e)}`:`;${Td(e)}=${Cd(t)}`).join(``)}function Dd(e){return e instanceof Qu?`${Cd(e.value)}${Ed(e.params)}`:Cd(e)}function Od(e){return`(${e.value.map(Dd).join(` `)})${Ed(e.params)}`}function kd(e,t={whitespace:!0}){if(typeof e!=`object`||!e)throw nd(e,$u);let n=e instanceof Map?e.entries():Object.entries(e),r=t?.whitespace?` `:``;return Array.from(n).map(([e,t])=>{t instanceof Qu||(t=new Qu(t));let n=Td(e);return t.value===!0?n+=Ed(t.params):(n+=`=`,Array.isArray(t.value)?n+=Od(t):n+=Dd(t)),n}).join(`,${r}`)}function Ad(e,t){return kd(e,t)}var jd=`CMCD-Object`,Md=`CMCD-Request`,Nd=`CMCD-Session`,Pd=`CMCD-Status`,Fd={br:jd,ab:jd,d:jd,ot:jd,tb:jd,tpb:jd,lb:jd,tab:jd,lab:jd,url:jd,pb:Md,bl:Md,tbl:Md,dl:Md,ltc:Md,mtp:Md,nor:Md,nrr:Md,rc:Md,sn:Md,sta:Md,su:Md,ttfb:Md,ttfbb:Md,ttlb:Md,cmsdd:Md,cmsds:Md,smrt:Md,df:Md,cs:Md,ts:Md,cid:Nd,pr:Nd,sf:Nd,sid:Nd,st:Nd,v:Nd,msd:Nd,bs:Pd,bsd:Pd,cdn:Pd,rtp:Pd,bg:Pd,pt:Pd,ec:Pd,e:Pd},Id={REQUEST:Md};function Ld(e){return Object.keys(e).reduce((t,n)=>{var r;return(r=e[n])==null||r.forEach(e=>t[e]=n),t},{})}function Rd(e,t){let n={};if(!e)return n;let r=Object.keys(e),i=t?Ld(t):{};return r.reduce((t,n)=>{let r=Fd[n]||i[n]||Id.REQUEST,a=t[r]??(t[r]={});return a[n]=e[n],t},n)}function zd(e){return[`ot`,`sf`,`st`,`e`,`sta`].includes(e)}function Bd(e){return typeof e==`number`?L(e):e!=null&&e!==``&&e!==!1}var Vd=`event`;function Hd(e,t){let n=new URL(e),r=new URL(t);if(n.origin!==r.origin)return e;let i=n.pathname.split(`/`).slice(1),a=r.pathname.split(`/`).slice(1,-1);for(;i[0]===a[0];)i.shift(),a.shift();for(;a.length;)a.shift(),i.unshift(`..`);return i.join(`/`)+n.search+n.hash}var Ud=e=>Math.round(e),Wd=(e,t)=>Array.isArray(e)?e.map(e=>Wd(e,t)):e instanceof Qu&&typeof e.value==`string`?new Qu(Wd(e.value,t),e.params):(t.baseUrl&&(e=Hd(e,t.baseUrl)),t.version===1?encodeURIComponent(e):e),Gd=e=>Ud(e/100)*100,Kd={br:Ud,d:Ud,bl:Gd,dl:Gd,mtp:Gd,nor:(e,t)=>{let n=e;return t.version>=2&&(e instanceof Qu&&typeof e.value==`string`?n=new Qu([e]):typeof e==`string`&&(n=[e])),Wd(n,t)},rtp:Gd,tb:Ud},qd=`request`,Jd=`response`,Yd=`ab.bg.bl.br.bs.bsd.cdn.cid.cs.df.ec.lab.lb.ltc.msd.mtp.pb.pr.pt.sf.sid.sn.st.sta.tab.tb.tbl.tpb.ts.v`.split(`.`),Xd=[`e`],Zd=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function Qd(e){return Zd.test(e)}function $d(e){return Yd.includes(e)||Xd.includes(e)||Qd(e)}var ef=[`d`,`dl`,`nor`,`ot`,`rtp`,`su`];function tf(e){return Yd.includes(e)||ef.includes(e)||Qd(e)}var nf=[`cmsdd`,`cmsds`,`rc`,`smrt`,`ttfb`,`ttfbb`,`ttlb`,`url`];function rf(e){return Yd.includes(e)||ef.includes(e)||nf.includes(e)||Qd(e)}var af=[`bl`,`br`,`bs`,`cid`,`d`,`dl`,`mtp`,`nor`,`nrr`,`ot`,`pr`,`rtp`,`sf`,`sid`,`st`,`su`,`tb`,`v`];function of(e){return af.includes(e)||Qd(e)}var sf={[Jd]:rf,[Vd]:$d,[qd]:tf};function cf(e,t={}){let n={};if(typeof e!=`object`||!e)return n;let r=t.version||e.v||1,i=t.reportingMode||qd,a=r===1?of:sf[i],o=Object.keys(e).filter(a),s=t.filter;typeof s==`function`&&(o=o.filter(s));let c=i===Jd||i===Vd;c&&!o.includes(`ts`)&&o.push(`ts`),r>1&&!o.includes(`v`)&&o.push(`v`);let l=U({},Kd,t.formatters),u={version:r,reportingMode:i,baseUrl:t.baseUrl};return o.sort().forEach(t=>{let i=e[t],a=l[t];if(typeof a==`function`&&(i=a(i,u)),t===`v`){if(r===1)return;i=r}t==`pr`&&i===1||(c&&t===`ts`&&!L(i)&&(i=Date.now()),Bd(i)&&(zd(t)&&typeof i==`string`&&(i=new rd(i)),n[t]=i))}),n}function lf(e,t={}){let n={};if(!e)return n;let r=Rd(cf(e,t),t?.customHeaderMap);return Object.entries(r).reduce((e,[t,n])=>{let r=Ad(n,{whitespace:!1});return r&&(e[t]=r),e},n)}function uf(e,t,n){return U(e,lf(t,n))}var df=`CMCD`;function ff(e,t={}){return e?Ad(cf(e,t),{whitespace:!1}):``}function pf(e,t={}){if(!e)return``;let n=ff(e,t);return encodeURIComponent(n)}function mf(e,t={}){return e?`${df}=${pf(e,t)}`:``}var hf=/CMCD=[^&#]+/;function gf(e,t,n){let r=mf(t,n);return r?hf.test(e)?e.replace(hf,r):`${e}${e.includes(`?`)?`&`:`?`}${r}`:e}var _f=class{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||=!0,this.buffering=!1},this.applyPlaylistData=e=>{try{this.apply(e,{ot:Xu.MANIFEST,su:!this.initialized})}catch(e){this.hls.logger.warn(`Could not generate manifest CMCD data.`,e)}},this.applyFragmentData=e=>{try{let{frag:t,part:n}=e,r=this.hls.levels[t.level],i=this.getObjectType(t),a={d:(n||t).duration*1e3,ot:i};(i===Xu.VIDEO||i===Xu.AUDIO||i==Xu.MUXED)&&(a.br=r.bitrate/1e3,a.tb=this.getTopBandwidth(i)/1e3,a.bl=this.getBufferLength(i));let o=n?this.getNextPart(n):this.getNextFrag(t);o!=null&&o.url&&o.url!==t.url&&(a.nor=o.url),this.apply(e,a)}catch(e){this.hls.logger.warn(`Could not generate segment CMCD data.`,e)}},this.hls=e;let t=this.config=e.config,{cmcd:n}=t;n!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=n.sessionId||e.sessionId,this.cid=n.contentId,this.useHeaders=n.useHeaders===!0,this.includeKeys=n.includeKeys,this.registerListeners())}registerListeners(){let e=this.hls;e.on(B.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(B.MEDIA_DETACHED,this.onMediaDetached,this),e.on(B.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){let e=this.hls;e.off(B.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(B.MEDIA_DETACHED,this.onMediaDetached,this),e.off(B.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener(`waiting`,this.onWaiting),this.media.addEventListener(`playing`,this.onPlaying)}onMediaDetached(){this.media&&=(this.media.removeEventListener(`waiting`,this.onWaiting),this.media.removeEventListener(`playing`,this.onPlaying),null)}onBufferCreated(e,t){this.audioBuffer=t.tracks.audio?.buffer,this.videoBuffer=t.tracks.video?.buffer}createData(){return{v:1,sf:Zu.HLS,sid:this.sid,cid:this.cid,pr:this.media?.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){U(t,this.createData());let n=t.ot===Xu.INIT||t.ot===Xu.VIDEO||t.ot===Xu.MUXED;this.starved&&n&&(t.bs=!0,t.su=!0,this.starved=!1),t.su??=this.buffering;let{includeKeys:r}=this;r&&(t=Object.keys(t).reduce((e,n)=>(r.includes(n)&&(e[n]=t[n]),e),{}));let i={baseUrl:e.url};this.useHeaders?(e.headers||={},uf(e.headers,t,i)):e.url=gf(e.url,t,i)}getNextFrag(e){let t=this.hls.levels[e.level]?.details;if(t){let n=e.sn-t.startSN;return t.fragments[n+1]}}getNextPart(e){var t;let{index:n,fragment:r}=e,i=(t=this.hls.levels[r.level])==null||(t=t.details)==null?void 0:t.partList;if(i){let{sn:e}=r;for(let t=i.length-1;t>=0;t--){let r=i[t];if(r.index===n&&r.fragment.sn===e)return i[t+1]}}}getObjectType(e){let{type:t}=e;if(t===`subtitle`)return Xu.TIMED_TEXT;if(e.sn===`initSegment`)return Xu.INIT;if(t===`audio`)return Xu.AUDIO;if(t===`main`)return this.hls.audioTracks.length?Xu.VIDEO:Xu.MUXED}getTopBandwidth(e){let t=0,n,r=this.hls;if(e===Xu.AUDIO)n=r.audioTracks;else{let e=r.maxAutoLevel,t=e>-1?e+1:r.levels.length;n=r.levels.slice(0,t)}return n.forEach(e=>{e.bitrate>t&&(t=e.bitrate)}),t>0?t:NaN}getBufferLength(e){let t=this.media,n=e===Xu.AUDIO?this.audioBuffer:this.videoBuffer;return!n||!t?NaN:X.bufferInfo(n,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){let{pLoader:e}=this.config,t=this.applyPlaylistData,n=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new n(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,n,r){t(e),this.loader.load(e,n,r)}}}createFragmentLoader(){let{fLoader:e}=this.config,t=this.applyFragmentData,n=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new n(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,n,r){t(e),this.loader.load(e,n,r)}}}},vf=3e5,yf=class extends Zr{constructor(e){super(`content-steering`,e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=`.`,this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){let e=this.hls;e.on(B.MANIFEST_LOADING,this.onManifestLoading,this),e.on(B.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(B.MANIFEST_PARSED,this.onManifestParsed,this),e.on(B.ERROR,this.onError,this)}unregisterListeners(){let e=this.hls;e&&(e.off(B.MANIFEST_LOADING,this.onManifestLoading,this),e.off(B.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(B.MANIFEST_PARSED,this.onManifestParsed,this),e.off(B.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(e.indexOf(t.pathwayId)===-1&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){let e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&=(this.loader.destroy(),null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){let t=this.levels;t&&(this.levels=t.filter(t=>t!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=`.`,this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){let{contentSteering:n}=t;n!==null&&(this.pathwayId=n.pathwayId,this.uri=n.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){let{errorAction:n}=t;if(n?.action===xo.SendAlternateToPenaltyBox&&n.flags===So.MoveAllAlternatesMatchingHost){let e=this.levels,r=this._pathwayPriority,i=this.pathwayId;if(t.context){let{groupId:n,pathwayId:r,type:a}=t.context;n&&e?i=this.getPathwayForGroupId(n,a,i):r&&(i=r)}i in this.penalizedPathways||(this.penalizedPathways[i]=performance.now()),!r&&e&&(r=this.pathways()),r&&r.length>1&&(this.updatePathwayPriority(r),n.resolved=this.pathwayId!==i),t.details===z.BUFFER_APPEND_ERROR&&!t.fatal?n.resolved=!0:n.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${i} levels: ${e&&e.length} priorities: ${Y(r)} penalized: ${Y(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){let n=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${n}"`),t=this.getLevelsForPathway(n),this.pathwayId=n}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let t,n=this.penalizedPathways,r=performance.now();Object.keys(n).forEach(e=>{r-n[e]>vf&&delete n[e]});for(let r=0;r<e.length;r++){let i=e[r];if(i in n)continue;if(i===this.pathwayId)return;let a=this.hls.nextLoadLevel,o=this.hls.levels[a];if(t=this.getLevelsForPathway(i),t.length>0){this.log(`Setting Pathway to "${i}"`),this.pathwayId=i,uc(t),this.hls.trigger(B.LEVELS_UPDATED,{levels:t});let e=this.hls.levels[a];o&&e&&this.levels&&(e.attrs[`STABLE-VARIANT-ID`]!==o.attrs[`STABLE-VARIANT-ID`]&&e.bitrate!==o.bitrate&&this.log(`Unstable Pathways change from bitrate ${o.bitrate} to ${e.bitrate}`),this.hls.nextLoadLevel=a);break}}}getPathwayForGroupId(e,t,n){let r=this.getLevelsForPathway(n).concat(this.levels||[]);for(let n=0;n<r.length;n++)if(t===V.AUDIO_TRACK&&r[n].hasAudioGroup(e)||t===V.SUBTITLE_TRACK&&r[n].hasSubtitleGroup(e))return r[n].pathwayId;return n}clonePathways(e){let t=this.levels;if(!t)return;let n={},r={};e.forEach(e=>{let{ID:i,"BASE-ID":a,"URI-REPLACEMENT":o}=e;if(t.some(e=>e.pathwayId===i))return;let s=this.getLevelsForPathway(a).map(e=>{let t=new ts(e.attrs);t[`PATHWAY-ID`]=i;let a=t.AUDIO&&`${t.AUDIO}_clone_${i}`,s=t.SUBTITLES&&`${t.SUBTITLES}_clone_${i}`;a&&(n[t.AUDIO]=a,t.AUDIO=a),s&&(r[t.SUBTITLES]=s,t.SUBTITLES=s);let c=xf(e.uri,t[`STABLE-VARIANT-ID`],`PER-VARIANT-URIS`,o),l=new za({attrs:t,audioCodec:e.audioCodec,bitrate:e.bitrate,height:e.height,name:e.name,url:c,videoCodec:e.videoCodec,width:e.width});if(e.audioGroups)for(let t=1;t<e.audioGroups.length;t++)l.addGroupId(`audio`,`${e.audioGroups[t]}_clone_${i}`);if(e.subtitleGroups)for(let t=1;t<e.subtitleGroups.length;t++)l.addGroupId(`text`,`${e.subtitleGroups[t]}_clone_${i}`);return l});t.push(...s),bf(this.audioTracks,n,o,i),bf(this.subtitleTracks,r,o,i)})}loadSteeringManifest(e){let t=this.hls.config,n=t.loader;this.loader&&this.loader.destroy(),this.loader=new n(t);let r;try{r=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(r.protocol!==`data:`){let e=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;r.searchParams.set(`_HLS_pathway`,this.pathwayId),r.searchParams.set(`_HLS_throughput`,``+e)}let i={responseType:`json`,url:r.href},a=t.steeringManifestLoadPolicy.default,o=a.errorRetry||a.timeoutRetry||{},s={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0};this.log(`Requesting steering manifest: ${r}`),this.loader.load(i,s,{onSuccess:(e,t,n,i)=>{this.log(`Loaded steering manifest: "${r}"`);let a=e.data;if(a?.VERSION!==1){this.log(`Steering VERSION ${a.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=a.TTL;let{"RELOAD-URI":o,"PATHWAY-CLONES":s,"PATHWAY-PRIORITY":c}=a;if(o)try{this.uri=new self.URL(o,r).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${o}`);return}this.scheduleRefresh(this.uri||n.url),s&&this.clonePathways(s);let l={steeringManifest:a,url:r.toString()};this.hls.trigger(B.STEERING_MANIFEST_LOADED,l),c&&this.updatePathwayPriority(c)},onError:(e,t,n,r)=>{if(this.log(`Error loading steering manifest: ${e.code} ${e.text} (${t.url})`),this.stopLoad(),e.code===410){this.enabled=!1,this.log(`Steering manifest ${t.url} no longer available`);return}let i=this.timeToLoad*1e3;if(e.code===429){let e=this.loader;if(typeof e?.getResponseHeader==`function`){let t=e.getResponseHeader(`Retry-After`);t&&(i=parseFloat(t)*1e3)}this.log(`Steering manifest ${t.url} rate limited`);return}this.scheduleRefresh(this.uri||t.url,i)},onTimeout:(e,t,n)=>{this.log(`Timeout loading steering manifest (${t.url})`),this.scheduleRefresh(this.uri||t.url)}})}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{let t=this.hls?.media;if(t&&!t.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}};function bf(e,t,n,r){e&&Object.keys(t).forEach(i=>{let a=e.filter(e=>e.groupId===i).map(e=>{let a=U({},e);return a.details=void 0,a.attrs=new ts(a.attrs),a.url=a.attrs.URI=xf(e.url,e.attrs[`STABLE-RENDITION-ID`],`PER-RENDITION-URIS`,n),a.groupId=a.attrs[`GROUP-ID`]=t[i],a.attrs[`PATHWAY-ID`]=r,a});e.push(...a)})}function xf(e,t,n,r){let{HOST:i,PARAMS:a,[n]:o}=r,s;t&&(s=o?.[t],s&&(e=s));let c=new self.URL(e);return i&&!s&&(c.host=i),a&&Object.keys(a).sort().forEach(e=>{e&&c.searchParams.set(e,a[e])}),c.href}var Sf=class e extends Zr{constructor(t){super(`eme`,t.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=e.CDMCleanupPromise?[e.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=e=>{let{initDataType:t,initData:n}=e,r=`"${e.type}" event: init data type: "${t}"`;if(this.debug(r),n!==null){if(!this.keyFormatPromise){let e=Object.keys(this.keySystemAccessPromises);e.length||(e=Ss(this.config));let t=e.map(xs).filter(e=>!!e);this.keyFormatPromise=this.getKeyFormatPromise(t)}this.keyFormatPromise.then(i=>{let a=bs(i);if(t!==`sinf`||a!==vs.FAIRPLAY){this.log(`Ignoring "${e.type}" event with init data type: "${t}" for selected key-system ${a}`);return}let o;try{let e=Ei(new Uint8Array(n)),t=Hi(fs(JSON.parse(e).sinf));if(!t)throw Error(`'schm' box missing or not cbcs/cenc with schi > tenc`);o=new Uint8Array(t.subarray(8,24))}catch(e){this.warn(`${r} Failed to parse sinf: ${e}`);return}let s=li(o),{keyIdToKeySessionPromise:c,mediaKeySessions:l}=this,u=c[s];for(let e=0;e<l.length;e++){let r=l[e],i=r.decryptdata;if(!i.keyId)continue;let a=li(i.keyId);if(cs(o,i.keyId)||i.uri.replace(/-/g,``).indexOf(s)!==-1){if(u=c[a],!u)continue;if(i.pssh)break;delete c[a],i.pssh=new Uint8Array(n),i.keyId=o,u=c[s]=u.then(()=>this.generateRequestWithPreferredKeySession(r,t,n,`encrypted-event-key-match`)),u.catch(e=>this.handleError(e));break}}u||this.handleError(Error(`Key ID ${s} not encountered in playlist. Key-system sessions ${l.length}.`))}).catch(e=>this.handleError(e))}},this.onWaitingForKey=e=>{this.log(`"${e.type}" event`)},this.hls=t,this.config=t.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();let e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(B.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(B.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(B.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(B.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(B.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(B.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(B.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(B.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(B.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(B.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(e){let{drmSystems:t,widevineLicenseUrl:n}=this.config,r=t?.[e];if(r)return r.licenseUrl;if(e===vs.WIDEVINE&&n)return n}getLicenseServerUrlOrThrow(e){let t=this.getLicenseServerUrl(e);if(t===void 0)throw Error(`no license server URL configured for key-system "${e}"`);return t}getServerCertificateUrl(e){let{drmSystems:t}=this.config,n=t?.[e];if(n)return n.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){let t=this.hls.levels,n=(e,t,n)=>!!e&&n.indexOf(e)===t,r=t.map(e=>e.audioCodec).filter(n),i=t.map(e=>e.videoCodec).filter(n);return r.length+i.length===0&&i.push(`avc1.42e01e`),new Promise((t,n)=>{let a=e=>{let o=e.shift();this.getMediaKeysPromise(o,r,i).then(e=>t({keySystem:o,mediaKeys:e})).catch(t=>{e.length?a(e):t instanceof Tf?n(t):n(new Tf({type:R.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_NO_ACCESS,error:t,fatal:!0},t.message))})};a(e)})}requestMediaKeySystemAccess(e,t){let{requestMediaKeySystemAccessFunc:n}=this.config;if(typeof n!=`function`){let e=`Configured requestMediaKeySystemAccess is not a function ${n}`;return Cs===null&&self.location.protocol===`http:`&&(e=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(Error(e))}return n(e,t)}getMediaKeysPromise(e,t,n){let r=ws(e,t,n,this.config.drmSystemOptions||{}),i=this.keySystemAccessPromises[e],a=i?.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${e}" key-system access with config: ${Y(r)}`),a=this.requestMediaKeySystemAccess(e,r);let t=i=this.keySystemAccessPromises[e]={keySystemAccess:a};return a.catch(t=>{this.log(`Failed to obtain access to key-system "${e}": ${t}`)}),a.then(n=>{this.log(`Access for key-system "${n.keySystem}" obtained`);let r=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);let i=t.mediaKeys=n.createMediaKeys().then(n=>(this.log(`Media-keys created for "${e}"`),t.hasMediaKeys=!0,r.then(t=>t?this.setMediaKeysServerCertificate(n,e,t):n)));return i.catch(t=>{this.error(`Failed to create media-keys for "${e}"}: ${t}`)}),i})}return a.then(()=>i.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:n}){this.log(`Creating key-system session "${t}" keyId: ${li(e.keyId||[])} keyUri: ${e.uri}`);let r={decryptdata:e,keySystem:t,mediaKeys:n,mediaKeysSession:n.createSession(),keyStatus:`status-pending`};return this.mediaKeySessions.push(r),r}renewKeySession(e){let t=e.decryptdata;if(t.pssh){let n=this.createMediaKeySessionContext(e),r=Cf(t);this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(n,`cenc`,t.pssh.buffer,`expired`)}else this.warn(`Could not renew expired session. Missing pssh initData.`);this.removeSession(e)}updateKeySession(e,t){let n=e.mediaKeysSession;return this.log(`Updating key-session "${n.sessionId}" for keyId ${li(e.decryptdata.keyId||[])}
29
+ } (data length: ${t.byteLength})`),n.update(t)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>xs(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:e,mediaKeys:t})=>this.attemptSetMediaKeys(e,t))}selectKeySystem(e){return new Promise((t,n)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:e})=>{let r=xs(e);r?t(r):n(Error(`Unable to find format for key-system "${e}"`))}).catch(n)})}selectKeySystemFormat(e){let t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||=(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(`, `)}`),this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){let t=Ss(this.config),n=e.map(bs).filter(e=>!!e&&t.indexOf(e)!==-1);return this.selectKeySystem(n)}getKeyStatus(e){let{mediaKeySessions:t}=this;for(let n=0;n<t.length;n++){let r=wf(e,t[n]);if(r)return r}}loadKey(e){let t=e.keyInfo.decryptdata,n=Cf(t),r=this.bannedKeyIds[n];if(r||this.getKeyStatus(t)===`internal-error`){let n=Ef(r||`internal-error`,t);return this.handleError(n,e.frag),Promise.reject(n)}let i=`(keyId: ${n} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${i}`);let a=this.keyIdToKeySessionPromise[n];if(!a){let r=this.getKeySystemForKeyPromise(t).then(({keySystem:n,mediaKeys:r})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${i}`),this.attemptSetMediaKeys(n,r).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:n,mediaKeys:r,decryptdata:t}))))).then(e=>{let n=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(e,`cenc`,n,`playlist-key`)});return r.catch(t=>this.handleError(t,e.frag)),this.keyIdToKeySessionPromise[n]=r,r}return a.catch(n=>{if(n instanceof Tf){let r=W({},n.data);this.getKeyStatus(t)===`internal-error`&&(r.decryptdata=t);let i=new Tf(r,n.message);this.handleError(i,e.frag)}}),a}throwIfDestroyed(e=`Invalid state`){if(!this.hls)throw Error(`invalid state`)}handleError(e,t){if(this.hls)if(e instanceof Tf){t&&(e.data.frag=t);let n=e.data.decryptdata;this.error(`${e.message}${n?` (${li(n.keyId||[])})`:``}`),this.hls.trigger(B.ERROR,e.data)}else this.error(e.message),this.hls.trigger(B.ERROR,{type:R.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){let t=Cf(e),n=this.keyIdToKeySessionPromise[t];if(!n){let t=bs(e.keyFormat),n=t?[t]:Ss(this.config);return this.attemptKeySystemAccess(n)}return n}getKeySystemSelectionPromise(e){if(e.length||(e=Ss(this.config)),e.length===0)throw new Tf({type:R.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${Y({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();let n=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);let r=Promise.all(n).then(()=>this.media?this.media.setMediaKeys(t):new Promise((e,n)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return n(Error(`Attempted to set mediaKeys without media element attached`));this.mediaKeys=t,this.media.setMediaKeys(t).then(e).catch(n)}}));return this.mediaKeys=t,this.setMediaKeysQueue.push(r),r.then(()=>{this.log(`Media-keys set for "${e}"`),n.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(e=>n.indexOf(e)===-1)})}generateRequestWithPreferredKeySession(e,t,n,r){var i;let a=(i=this.config.drmSystems)==null||(i=i[e.keySystem])==null?void 0:i.generateRequest;if(a)try{let r=a.call(this.hls,t,n,e);if(!r)throw Error(`Invalid response from configured generateRequest filter`);t=r.initDataType,n=r.initData?r.initData:null,e.decryptdata.pssh=n?new Uint8Array(n):null}catch(e){if(this.warn(e.message),this.hls&&this.hls.config.debug)throw e}if(n===null)return this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(e);let o=Cf(e.decryptdata),s=e.decryptdata.uri;this.log(`Generating key-session request for "${r}" keyId: ${o} URI: ${s} (init data type: ${t} length: ${n.byteLength})`);let c=new Ac,l=e._onmessage=t=>{let n=e.mediaKeysSession;if(!n){c.emit(`error`,Error(`invalid state`));return}let{messageType:r,message:i}=t;this.log(`"${r}" message event for session "${n.sessionId}" message size: ${i.byteLength}`),r===`license-request`||r===`license-renewal`?this.renewLicense(e,i).catch(e=>{c.eventNames().length?c.emit(`error`,e):this.handleError(e)}):r===`license-release`?e.keySystem===vs.FAIRPLAY&&this.updateKeySession(e,ps(`acknowledged`)).then(()=>this.removeSession(e)).catch(e=>this.handleError(e)):this.warn(`unhandled media key message type "${r}"`)},u=(e,t)=>{t.keyStatus=e;let n;e.startsWith(`usable`)?c.emit(`resolved`):e===`internal-error`||e===`output-restricted`||e===`output-downscaled`?n=Ef(e,t.decryptdata):e===`expired`?n=Error(`key expired (keyId: ${o})`):e===`released`?n=Error(`key released`):e===`status-pending`||this.warn(`unhandled key status change "${e}" (keyId: ${o})`),n&&(c.eventNames().length?c.emit(`error`,n):this.handleError(n))},d=e._onkeystatuseschange=t=>{if(!e.mediaKeysSession){c.emit(`error`,Error(`invalid state`));return}let n=this.getKeyStatuses(e);if(!Object.keys(n).some(e=>n[e]!==`status-pending`))return;if(n[o]===`expired`){this.log(`Expired key ${Y(n)} in key-session "${e.mediaKeysSession.sessionId}"`),this.renewKeySession(e);return}let r=n[o];if(r)u(r,e);else{var i;let t=1e3;e.keyStatusTimeouts||={},(i=e.keyStatusTimeouts)[o]||(i[o]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;let n=this.getKeyStatus(e.decryptdata);if(n&&n!==`status-pending`)return this.log(`No status for keyId ${o} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${n} from other session.`),u(n,e);this.log(`key status for ${o} in key-session "${e.mediaKeysSession.sessionId}" timed out after ${t}ms`),r=`internal-error`,u(r,e)},t)),this.log(`No status for keyId ${o} (${Y(n)}).`)}};bc(e.mediaKeysSession,`message`,l),bc(e.mediaKeysSession,`keystatuseschange`,d);let f=new Promise((e,t)=>{c.on(`error`,t),c.on(`resolved`,e)});return e.mediaKeysSession.generateRequest(t,n).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${o} URI: ${s}`)}).catch(t=>{throw new Tf({type:R.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_NO_SESSION,error:t,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${t}`)}).then(()=>f).catch(t=>(c.removeAllListeners(),this.removeSession(e).then(()=>{throw t}))).then(()=>(c.removeAllListeners(),e))}getKeyStatuses(e){let t={};return e.mediaKeysSession.keyStatuses.forEach((n,r)=>{if(typeof r==`string`&&typeof n==`object`){let e=r;r=n,n=e}let i=`buffer`in r?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r);if(e.keySystem===vs.PLAYREADY&&i.length===16){let e=li(i);t[e]=n,hs(i)}let a=li(i);n===`internal-error`&&(this.bannedKeyIds[a]=n),this.log(`key status change "${n}" for keyStatuses keyId: ${a} key-session "${e.mediaKeysSession.sessionId}"`),t[a]=n}),t}fetchServerCertificate(e){let t=this.config,n=t.loader,r=new n(t),i=this.getServerCertificateUrl(e);return i?(this.log(`Fetching server certificate for "${e}"`),new Promise((n,a)=>{let o={responseType:`arraybuffer`,url:i},s=t.certLoadPolicy.default,c={loadPolicy:s,timeout:s.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};r.load(o,c,{onSuccess:(e,t,r,i)=>{n(e.data)},onError:(t,n,r,s)=>{a(new Tf({type:R.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:W({url:o.url,data:void 0},t)},`"${e}" certificate request failed (${i}). Status: ${t.code} (${t.text})`))},onTimeout:(t,n,r)=>{a(new Tf({type:R.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:{url:o.url,data:void 0}},`"${e}" certificate request timed out (${i})`))},onAbort:(e,t,n)=>{a(Error(`aborted`))}})})):Promise.resolve()}setMediaKeysServerCertificate(e,t,n){return new Promise((r,i)=>{e.setServerCertificate(n).then(i=>{this.log(`setServerCertificate ${i?`success`:`not supported by CDM`} (${n.byteLength}) on "${t}"`),r(e)}).catch(e=>{i(new Tf({type:R.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:e,fatal:!0},e.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(t=>this.updateKeySession(e,new Uint8Array(t)).catch(t=>{throw new Tf({type:R.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:t,fatal:!1},t.message)}))}unpackPlayReadyKeyMessage(e,t){let n=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!n.includes(`PlayReadyKeyMessage`))return e.setRequestHeader(`Content-Type`,`text/xml; charset=utf-8`),t;let r=new DOMParser().parseFromString(n,`application/xml`),i=r.querySelectorAll(`HttpHeader`);if(i.length>0){let t;for(let n=0,r=i.length;n<r;n++){t=i[n];let r=t.querySelector(`name`)?.textContent,a=t.querySelector(`value`)?.textContent;r&&a&&e.setRequestHeader(r,a)}}let a=r.querySelector(`Challenge`)?.textContent;if(!a)throw Error(`Cannot find <Challenge> in key message`);return ps(atob(a))}setupLicenseXHR(e,t,n,r){let i=this.config.licenseXhrSetup;return i?Promise.resolve().then(()=>{if(!n.decryptdata)throw Error(`Key removed`);return i.call(this.hls,e,t,n,r)}).catch(a=>{if(!n.decryptdata)throw a;return e.open(`POST`,t,!0),i.call(this.hls,e,t,n,r)}).then(n=>(e.readyState||e.open(`POST`,t,!0),{xhr:e,licenseChallenge:n||r})):(e.open(`POST`,t,!0),Promise.resolve({xhr:e,licenseChallenge:r}))}requestLicense(e,t){let n=this.config.keyLoadPolicy.default;return new Promise((r,i)=>{let a=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${a}`);let o=new XMLHttpRequest;o.responseType=`arraybuffer`,o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return i(Error(`invalid state`));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let t=o.response;this.log(`License received ${t instanceof ArrayBuffer?t.byteLength:t}`);let n=this.config.licenseResponseCallback;if(n)try{t=n.call(this.hls,o,a,e)}catch(e){this.error(e)}r(t)}else{let s=n.errorRetry,c=s?s.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>c||o.status>=400&&o.status<500)i(new Tf({type:R.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:o,response:{url:a,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${a}). Status: ${o.status} (${o.statusText})`));else{let n=c-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${n} attempts left`),this.requestLicense(e,t).then(r,i)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,a,e,t).then(({xhr:t,licenseChallenge:n})=>{e.keySystem==vs.PLAYREADY&&(n=this.unpackPlayReadyKeyMessage(t,n)),t.send(n)}).catch(i)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;let n=t.media;this.media=n,bc(n,`encrypted`,this.onMediaEncrypted),bc(n,`waitingforkey`,this.onWaitingForKey);let r=this.mediaResolved;r?r():this.mediaKeys=n.mediaKeys}onMediaDetached(){let e=this.media;e&&(xc(e,`encrypted`,this.onMediaEncrypted),xc(e,`waitingforkey`,this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var t;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};let n=this.mediaResolved;if(n&&n(),!this.mediaKeys&&!this.mediaKeySessions.length)return;let r=this.media,i=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,ks.clearKeyUriToKeyIdMap();let a=i.length;e.CDMCleanupPromise=Promise.all(i.map(e=>this.removeSession(e)).concat((r==null||(t=r.setMediaKeys(null))==null?void 0:t.catch(e=>{this.log(`Could not clear media keys: ${e}`),this.hls&&this.hls.trigger(B.ERROR,{type:R.OTHER_ERROR,details:z.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:Error(`Could not clear media keys: ${e}`)})}))||Promise.resolve())).catch(e=>{this.log(`Could not close sessions and clear media keys: ${e}`),this.hls&&this.hls.trigger(B.ERROR,{type:R.OTHER_ERROR,details:z.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:Error(`Could not close sessions and clear media keys: ${e}`)})}).then(()=>{a&&this.log(`finished closing key sessions and clearing media keys`)})}onManifestLoading(){this._clear()}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){let e=t.reduce((e,t)=>(e.indexOf(t.keyFormat)===-1&&e.push(t.keyFormat),e),[]);this.log(`Selecting key-system from session-keys ${e.join(`, `)}`),this.keyFormatPromise=this.getKeyFormatPromise(e)}}removeSession(e){let{mediaKeysSession:t,licenseXhr:n,decryptdata:r}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${li(r?.keyId||[])}`),e._onmessage&&=(t.removeEventListener(`message`,e._onmessage),void 0),e._onkeystatuseschange&&=(t.removeEventListener(`keystatuseschange`,e._onkeystatuseschange),void 0),n&&n.readyState!==XMLHttpRequest.DONE&&n.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;let i=this.mediaKeySessions.indexOf(e);i>-1&&this.mediaKeySessions.splice(i,1);let{keyStatusTimeouts:a}=e;a&&Object.keys(a).forEach(e=>self.clearTimeout(a[e]));let{drmSystemOptions:o}=this.config;return(Es(o)?new Promise((e,n)=>{self.setTimeout(()=>n(Error(`MediaKeySession.remove() timeout`)),8e3),t.remove().then(e).catch(n)}):Promise.resolve()).catch(e=>{this.log(`Could not remove session: ${e}`),this.hls&&this.hls.trigger(B.ERROR,{type:R.OTHER_ERROR,details:z.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:Error(`Could not remove session: ${e}`)})}).then(()=>t.close()).catch(e=>{this.log(`Could not close session: ${e}`),this.hls&&this.hls.trigger(B.ERROR,{type:R.OTHER_ERROR,details:z.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:Error(`Could not close session: ${e}`)})})}return Promise.resolve()}};Sf.CDMCleanupPromise=void 0;function Cf(e){if(!e)throw Error(`Could not read keyId of undefined decryptdata`);if(e.keyId===null)throw Error(`keyId is null`);return li(e.keyId)}function wf(e,t){if(e.keyId&&t.mediaKeysSession.keyStatuses.has(e.keyId))return t.mediaKeysSession.keyStatuses.get(e.keyId);if(e.matches(t.decryptdata))return t.keyStatus}var Tf=class extends Error{constructor(e,t){super(t),this.data=void 0,e.error||=Error(t),this.data=e,e.err=e.error}};function Ef(e,t){let n=e===`output-restricted`,r=n?z.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:z.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Tf({type:R.KEY_SYSTEM_ERROR,details:r,fatal:!1,decryptdata:t},n?`HDCP level output restricted`:`key status changed to "${e}"`)}var Df=class{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(B.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(B.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(B.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(B.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){let n=this.hls.config;if(n.capLevelOnFPSDrop){let e=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=e,e&&typeof e.getVideoPlaybackQuality==`function`&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),n.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,n){let r=performance.now();if(t){if(this.lastTime){let e=r-this.lastTime,i=n-this.lastDroppedFrames,a=t-this.lastDecodedFrames,o=1e3*i/e,s=this.hls;if(s.trigger(B.FPS_DROP,{currentDropped:i,currentDecoded:a,totalDroppedFrames:n}),o>0&&i>s.config.fpsDroppedMonitoringThreshold*a){let e=s.currentLevel;s.logger.warn(`drop FPS ratio greater than max allowed value for currentLevel: `+e),e>0&&(s.autoLevelCapping===-1||s.autoLevelCapping>=e)&&(--e,s.trigger(B.FPS_DROP_LEVEL_CAPPING,{level:e,droppedLevel:s.currentLevel}),s.autoLevelCapping=e,this.streamController.nextLevelSwitch())}}this.lastTime=r,this.lastDroppedFrames=n,this.lastDecodedFrames=t}}checkFPSInterval(){let e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){let t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}};function Of(e,t){let n;try{n=new Event(`addtrack`)}catch{n=document.createEvent(`Event`),n.initEvent(`addtrack`,!1,!1)}n.track=e,t.dispatchEvent(n)}function kf(e,t){let n=e.mode;if(n===`disabled`&&(e.mode=`hidden`),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw Error(`addCue is failed for: ${t}`)}catch(n){G.debug(`[texttrack-utils]: ${n}`);try{let n=new self.TextTrackCue(t.startTime,t.endTime,t.text);n.id=t.id,e.addCue(n)}catch(e){G.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${e}`)}}n===`disabled`&&(e.mode=n)}function Af(e,t){let n=e.mode;if(n===`disabled`&&(e.mode=`hidden`),e.cues)for(let n=e.cues.length;n--;)t&&e.cues[n].removeEventListener(`enter`,t),e.removeCue(e.cues[n]);n===`disabled`&&(e.mode=n)}function jf(e,t,n,r){let i=e.mode;if(i===`disabled`&&(e.mode=`hidden`),e.cues&&e.cues.length>0){let i=Nf(e.cues,t,n);for(let t=0;t<i.length;t++)(!r||r(i[t]))&&e.removeCue(i[t])}i===`disabled`&&(e.mode=i)}function Mf(e,t){if(t<=e[0].startTime)return 0;let n=e.length-1;if(t>e[n].endTime)return-1;let r=0,i=n,a;for(;r<=i;)if(a=Math.floor((i+r)/2),t<e[a].startTime)i=a-1;else if(t>e[a].startTime&&r<n)r=a+1;else return a;return e[r].startTime-t<t-e[i].startTime?r:i}function Nf(e,t,n){let r=[],i=Mf(e,t);if(i>-1)for(let a=i,o=e.length;a<o;a++){let i=e[a];if(i.startTime>=t&&i.endTime<=n)r.push(i);else if(i.startTime>n)return r}return r}function Pf(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n];(r.kind===`subtitles`||r.kind===`captions`)&&r.label&&t.push(e[n])}return t}var Ff=class extends Iu{constructor(e){super(e,`subtitle-track-controller`),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let e=null,t=Pf(this.media.textTracks);for(let n=0;n<t.length;n++)if(t[n].mode===`hidden`)e=t[n];else if(t[n].mode===`showing`){e=t[n];break}let n=this.findTrackForTextTrack(e);this.subtitleTrack!==n&&this.setSubtitleTrack(n)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){let{hls:e}=this;e.on(B.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(B.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(B.MANIFEST_LOADING,this.onManifestLoading,this),e.on(B.MANIFEST_PARSED,this.onManifestParsed,this),e.on(B.LEVEL_LOADING,this.onLevelLoading,this),e.on(B.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(B.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(B.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(B.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(B.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(B.MANIFEST_LOADING,this.onManifestLoading,this),e.off(B.MANIFEST_PARSED,this.onManifestParsed,this),e.off(B.LEVEL_LOADING,this.onLevelLoading,this),e.off(B.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(B.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(B.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&`onchange`in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener(`change`,this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){let n=this.media;if(!n)return;let r=!!t.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||n.textTracks.removeEventListener(`change`,this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,!r&&Pf(n.textTracks).forEach(e=>{Af(e)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){let{id:n,groupId:r,details:i}=t,a=this.tracksInGroup[n];if(!a||a.groupId!==r){this.warn(`Subtitle track with id:${n} and group:${r} not found in active group ${a?.groupId}`);return}let o=a.details;a.details=t.details,this.log(`Subtitle track ${n} "${a.name}" lang:${a.lang} group:${r} loaded [${i.startSN}-${i.endSN}]`),n===this.trackId&&this.playlistLoaded(n,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){let t=this.hls.levels[e];if(!t)return;let n=t.subtitleGroups||null,r=this.groupIds,i=this.currentTrack;if(!n||r?.length!==n?.length||n!=null&&n.some(e=>r?.indexOf(e)===-1)){this.groupIds=n,this.trackId=-1,this.currentTrack=null;let e=this.tracks.filter(e=>!n||n.indexOf(e.groupId)!==-1);if(e.length)this.selectDefaultTrack&&!e.some(e=>e.default)&&(this.selectDefaultTrack=!1),e.forEach((e,t)=>{e.id=t});else if(!i&&!this.tracksInGroup.length)return;this.tracksInGroup=e;let t=this.hls.config.subtitlePreference;if(!i&&t){this.selectDefaultTrack=!1;let n=Ya(t,e);if(n>-1)i=e[n];else{let e=Ya(t,this.tracks);i=this.tracks[e]}}let r=this.findTrackId(i);r===-1&&i&&(r=this.findTrackId(null));let a={subtitleTracks:e};this.log(`Updating subtitle tracks, ${e.length} track(s) found in "${n?.join(`,`)}" group-id`),this.hls.trigger(B.SUBTITLE_TRACKS_UPDATED,a),r!==-1&&this.trackId===-1&&this.setSubtitleTrack(r)}}findTrackId(e){let t=this.tracksInGroup,n=this.selectDefaultTrack;for(let r=0;r<t.length;r++){let i=t[r];if(!(n&&!i.default||!n&&!e)&&(!e||Xa(i,e)))return r}if(e){for(let n=0;n<t.length;n++){let r=t[n];if(Ru(e.attrs,r.attrs,[`LANGUAGE`,`ASSOC-LANGUAGE`,`CHARACTERISTICS`]))return n}for(let n=0;n<t.length;n++){let r=t[n];if(Ru(e.attrs,r.attrs,[`LANGUAGE`]))return n}}return-1}findTrackForTextTrack(e){if(e){let t=this.tracksInGroup;for(let n=0;n<t.length;n++){let r=t[n];if(zu(r,e))return n}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===V.SUBTITLE_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(e.id===-1)return this.setSubtitleTrack(-1),null;let t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){let n=this.currentTrack;if(n&&Xa(e,n))return n;let r=Ya(e,this.tracksInGroup);if(r>-1){let e=this.tracksInGroup[r];return this.setSubtitleTrack(r),e}else if(n)return null;else{let n=Ya(e,t);if(n>-1)return t[n]}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let n=e.id,r=e.groupId,i=this.getUrlWithDirectives(e.url,t),a=e.details,o=a?.age;this.log(`Loading subtitle ${n} "${e.name}" lang:${e.lang} group:${r}${t?.msn===void 0?``:` at sn `+t.msn+` part `+t.part}${o&&a.live?` age `+o.toFixed(1)+(a.type&&` `+a.type||``):``} ${i}`),this.hls.trigger(B.SUBTITLE_TRACK_LOADING,{url:i,id:n,groupId:r,deliveryDirectives:t||null,track:e})}toggleTrackModes(){let{media:e}=this;if(!e)return;let t=Pf(e.textTracks),n=this.currentTrack,r;if(n&&(r=t.filter(e=>zu(n,e))[0],r||this.warn(`Unable to find subtitle TextTrack with name "${n.name}" and language "${n.lang}"`)),[].slice.call(t).forEach(e=>{e.mode!==`disabled`&&e!==r&&(e.mode=`disabled`)}),r){let e=this.subtitleDisplay?`showing`:`hidden`;r.mode!==e&&(r.mode=e)}}setSubtitleTrack(e){let t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!L(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.selectDefaultTrack=!1;let n=this.currentTrack,r=t[e]||null;if(this.trackId=e,this.currentTrack=r,this.toggleTrackModes(),!r){this.hls.trigger(B.SUBTITLE_TRACK_SWITCH,{id:e});return}let i=!!r.details&&!r.details.live;if(e===this.trackId&&r===n&&i)return;this.log(`Switching to subtitle-track ${e}`+(r?` "${r.name}" lang:${r.lang} group:${r.groupId}`:``));let{id:a,groupId:o=``,name:s,type:c,url:l}=r;this.hls.trigger(B.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:s,type:c,url:l});let u=this.switchParams(r.url,n?.details,r.details);this.loadPlaylist(u)}};function If(){try{return crypto.randomUUID()}catch{try{let e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf(`/`)+1)}catch{let e=new Date().getTime();return`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,t=>{let n=(e+Math.random()*16)%16|0;return e=Math.floor(e/16),(t==`x`?n:n&3|8).toString(16)})}}}function Lf(e){let t=5381,n=e.length;for(;n;)t=t*33^e.charCodeAt(--n);return(t>>>0).toString()}var Rf=.025,zf=function(e){return e[e.Point=0]=`Point`,e[e.Range=1]=`Range`,e}({});function Bf(e,t,n){return`${e.identifier}-${n+1}-${Lf(t)}`}var Vf=class{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat(`X-RESUME-OFFSET`,this.resumeOffset),this.playoutLimit=e.attr.optionalFloat(`X-PLAYOUT-LIMIT`,this.playoutLimit),this.restrictions=e.attr.enumeratedStringList(`X-RESTRICT`,this.restrictions),this.snapOptions=e.attr.enumeratedStringList(`X-SNAP`,this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,(e=this.assetListLoader)==null||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){if(e>0&&e>=this.assetList.length)return!0;let t=this.playoutLimit;return e<=0||isNaN(t)?!1:t===0?!0:(this.assetList[e]?.startOffset||0)>t}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){let e=this.dateRange.startTime;if(this.snapOptions.out){let t=this.dateRange.tagAnchor;if(t)return Hf(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;let e=this.dateRange.tagAnchor;if(e){let t=this.dateRange.startTime;return t-Hf(t,e)<.1}return!1}get resumptionOffset(){let e=this.resumeOffset,t=L(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){let e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){let t=this.resumeAnchor;if(t)return Hf(e,t)}return e}get appendInPlace(){return this.appendInPlaceStarted?!0:this.appendInPlaceDisabled?!1:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<Rf))}set appendInPlace(e){if(this.appendInPlaceStarted){this.resetOnResume=!e;return}this.appendInPlaceDisabled=!e}get timelineStart(){return this._timelineStart===null?this.startTime:this._timelineStart}set timelineStart(e){this._timelineStart=e}get duration(){let e=this.playoutLimit,t;return t=this._duration===null?this.dateRange.duration?this.dateRange.duration:this.dateRange.plannedDuration||0:this._duration,!isNaN(e)&&e<t&&(t=e),t}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return this.dateRange.attr[`X-TIMELINE-OCCUPIES`]===`RANGE`?zf.Range:zf.Point}get supplementsPrimary(){return this.dateRange.attr[`X-TIMELINE-STYLE`]===`PRIMARY`}get contentMayVary(){return this.dateRange.attr[`X-CONTENT-MAY-VARY`]!==`NO`}get assetUrl(){return this.dateRange.attr[`X-ASSET-URI`]}get assetListUrl(){return this.dateRange.attr[`X-ASSET-LIST`]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||this.assetListResponse!==null}toString(){return Gf(this)}};function Hf(e,t){return e-t.start<t.duration/2&&!(Math.abs(e-(t.start+t.duration))<Rf)?t.start:t.start+t.duration}function Uf(e,t,n){let r=new self.URL(e,n);return r.protocol!==`data:`&&r.searchParams.set(`_HLS_primary_id`,t),r}function Wf(e,t){for(;(n=e.assetList[++t])!=null&&n.error;)var n;return t}function Gf(e){return`["${e.identifier}" ${e.cue.pre?`<pre>`:e.cue.post?`<post>`:``}${e.timelineStart.toFixed(2)}-${e.resumeTime.toFixed(2)}]`}function Kf(e){let t=e.timelineStart,n=e.duration||0;return`["${e.identifier}" ${t.toFixed(2)}-${(t+n).toFixed(2)}]`}var qf=class{constructor(e,t,n,r){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(B.PLAYOUT_LIMIT_REACHED,{})};let i=this.hls=new e(t);this.interstitial=n,this.assetItem=r;let a=()=>{this.hasDetails=!0};i.once(B.LEVEL_LOADED,a),i.once(B.AUDIO_TRACK_LOADED,a),i.once(B.SUBTITLE_TRACK_LOADED,a),i.on(B.MEDIA_ATTACHING,(e,{media:t})=>{this.removeMediaListeners(),this.mediaAttached=t,this.interstitial.playoutLimit&&(t.addEventListener(`timeupdate`,this.checkPlayout),this.appendInPlace&&i.on(B.BUFFER_APPENDED,()=>{let e=this.bufferedEnd;this.reachedPlayout(e)&&(this._bufferedEosTime=e,i.trigger(B.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){let e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let t=this.assetItem.uri;try{t=Uf(t,e.config.primarySessionId||``).href}catch{}e.loadSource(t)}}bufferedInPlaceToEnd(e){var t;if(!this.appendInPlace)return!1;if((t=this.hls)!=null&&t.bufferedToEnd)return!0;if(!e)return!1;let n=Math.min(this._bufferedEosTime||1/0,this.duration),r=this.timelineOffset,i=X.bufferInfo(e,r,0);return this.getAssetTime(i.end)>=n-.02}reachedPlayout(e){let t=this.interstitial.playoutLimit;return this.startOffset+e>=t}get destroyed(){var e;return!((e=this.hls)!=null&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){return this.hls?.media||null}get bufferedEnd(){let e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;let t=X.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){let e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){let e=this.assetItem.duration;if(!e)return 0;let t=this.interstitial.playoutLimit;if(t){let n=t-this.startOffset;if(n>0&&n<e)return n}return e}get remaining(){let e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){return this.hls?.config.timelineOffset||0}set timelineOffset(e){let t=this.timelineOffset;if(e!==t){let n=e-t;if(Math.abs(n)>1/9e4&&this.hls){if(this.hasDetails)throw Error(`Cannot set timelineOffset after playlists are loaded`);this.hls.config.timelineOffset=e}}}getAssetTime(e){let t=this.timelineOffset,n=this.duration;return Math.min(Math.max(0,e-t),n)}removeMediaListeners(){let e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener(`timeupdate`,this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var e;(e=this.hls)!=null&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),(t=this.hls)==null||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,(e=this.hls)==null||e.detachMedia()}resumeBuffering(){var e;(e=this.hls)==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.hls)==null||e.pauseBuffering()}transferMedia(){return this.bufferSnapShot(),this.hls?.transferMedia()||null}resetDetails(){let e=this.hls;if(e&&this.hasDetails){e.stopLoad();let t=e=>delete e.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,n){var r;(r=this.hls)==null||r.on(e,t)}once(e,t,n){var r;(r=this.hls)==null||r.once(e,t)}off(e,t,n){var r;(r=this.hls)==null||r.off(e,t)}toString(){return`HlsAssetPlayer: ${Kf(this.assetItem)} ${this.hls?.sessionId} ${this.appendInPlace?`append-in-place`:``}`}},Jf=.033,Yf=class extends Zr{constructor(e,t){super(`interstitials-sched`,t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((n,r)=>e<=r.startOffset&&t>r.startOffset?(delete r.error,n+1):n,0):0}get duration(){let e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let n=-1;e.nextEvent?n=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(n=this.findEventIndex(e.previousEvent.identifier)+1);let r=this.items;if(r)for(r[n]||(t===void 0&&(t=e.start),n=this.findItemIndexAtTime(t));n>=0&&(i=r[n])!=null&&i.event;){var i;n--}return n}findItemIndexAtTime(e,t){let n=this.items;if(n)for(let r=0;r<n.length;r++){let i=n[r];if(t&&t!==`primary`&&(i=i[t]),e===i.start||e>i.start&&e<i.end)return r}return-1}findJumpRestrictedIndex(e,t){let n=this.items;if(n)for(let r=e;r<=t&&n[r];r++){let e=n[r].event;if(e!=null&&e.restrictions.jump&&!e.appendInPlace)return r}return-1}findEventIndex(e){let t=this.items;if(t){for(let n=t.length;n--;)if(t[n].event?.identifier===e)return n}return-1}findAssetIndex(e,t){let n=e.assetList,r=n.length;if(r>1)for(let e=0;e<r;e++){let i=n[e];if(!i.error){let n=i.timelineStart;if(t===n||t>n&&(t<n+(i.duration||0)||e===r-1))return e}}return 0}get assetIdAtEnd(){var e;let t=(e=this.items)==null||(e=e[this.length-1])==null?void 0:e.event;if(t){let e=t.assetList,n=e[e.length-1];if(n)return n.identifier}return null}parseInterstitialDateRanges(e,t){let n=e.main.details,{dateRanges:r}=n,i=this.events,a=this.parseDateRanges(r,{url:n.url},t),o=Object.keys(r),s=i?i.filter(e=>!o.includes(e.identifier)):[];a.length&&a.sort((e,t)=>{let n=e.cue.pre,r=e.cue.post,i=t.cue.pre,a=t.cue.post;if(n&&!i)return-1;if(i&&!n||r&&!a)return 1;if(a&&!r)return-1;if(!n&&!i&&!r&&!a){let n=e.startTime,r=t.startTime;if(n!==r)return n-r}return e.dateRange.tagOrder-t.dateRange.tagOrder}),this.events=a,s.forEach(e=>{this.removeEvent(e)}),this.updateSchedule(e,s)}updateSchedule(e,t=[],n=!1){let r=this.events||[];if(r.length||t.length||this.length<2){let i=this.items,a=this.parseSchedule(r,e);(n||t.length||i?.length!==a.length||a.some((e,t)=>Math.abs(e.playout.start-i[t].playout.start)>.005||Math.abs(e.playout.end-i[t].playout.end)>.005))&&(this.items=a,this.onScheduleUpdate(t,i))}}parseDateRanges(e,t,n){let r=[],i=Object.keys(e);for(let a=0;a<i.length;a++){let o=i[a],s=e[o];if(s.isInterstitial){let e=this.eventMap[o];e?e.setDateRange(s):(e=new Vf(s,t),this.eventMap[o]=e,n===!1&&(e.appendInPlace=n)),r.push(e)}}return r}parseSchedule(e,t){let n=[],r=t.main.details,i=r.live?1/0:r.edge,a=0;if(e=e.filter(e=>!e.error&&!(e.cue.once&&e.hasPlayed)),e.length){this.resolveOffsets(e,t);let r=0,o=0;if(e.forEach((t,s)=>{let c=t.cue.pre,l=t.cue.post,u=e[s-1]||null,d=t.appendInPlace,f=l?i:t.startOffset,p=t.duration,m=t.timelineOccupancy===zf.Range?p:0,h=t.resumptionOffset,g=u?.startTime===f,_=f+t.cumulativeDuration,v=d?_+p:f+h;if(c||!l&&f<=0){let e=o;o+=m,t.timelineStart=_;let r=a;a+=p,n.push({event:t,start:_,end:v,playout:{start:r,end:a},integrated:{start:e,end:o}})}else if(f<=i){if(!g){let i=f-r;if(i>Jf){let c=r,l=o;o+=i;let u=a;a+=i;let d={previousEvent:e[s-1]||null,nextEvent:t,start:c,end:c+i,playout:{start:u,end:a},integrated:{start:l,end:o}};n.push(d)}else i>0&&u&&(u.cumulativeDuration+=i,n[n.length-1].end=f)}l&&(v=_),t.timelineStart=_;let i=o;o+=m;let c=a;a+=p,n.push({event:t,start:_,end:v,playout:{start:c,end:a},integrated:{start:i,end:o}})}else return;let y=t.resumeTime;r=l||y>i?i:y}),r<i){let e=r,t=o,s=i-r;o+=s;let c=a;a+=s,n.push({previousEvent:n[n.length-1]?.event||null,nextEvent:null,start:r,end:e+s,playout:{start:c,end:a},integrated:{start:t,end:o}})}this.setDurations(i,a,o)}else n.push({previousEvent:null,nextEvent:null,start:0,end:i,playout:{start:0,end:i},integrated:{start:0,end:i}}),this.setDurations(i,i,i);return n}setDurations(e,t,n){this.durations={primary:e,playout:t,integrated:n}}resolveOffsets(e,t){let n=t.main.details,r=n.live?1/0:n.edge,i=0,a=-1;e.forEach((o,s)=>{let c=o.cue.pre,l=o.cue.post,u=c?0:l?r:o.startTime;this.updateAssetDurations(o),a===u?o.cumulativeDuration=i:(i=0,a=u),!l&&o.snapOptions.in&&(o.resumeAnchor=oo(null,n.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1)),!o.appendInPlace&&s+1<e.length&&e[s+1].startTime-e[s].resumeTime<Jf&&(e[s+1].appendInPlace=!1,e[s+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`));let d=L(o.resumeOffset)?o.resumeOffset:o.duration;i+=d})}primaryCanResumeInPlaceAt(e,t){let n=e.resumeTime,r=e.startTime+e.resumptionOffset;return Math.abs(n-r)>Rf?(this.log(`"${e.identifier}" resumption ${n} not aligned with estimated timeline end ${r}`),!1):!Object.keys(t).some(r=>{let i=t[r].details,a=i.edge;if(n>=a)return this.log(`"${e.identifier}" resumption ${n} past ${r} playlist end ${a}`),!1;let o=oo(null,i.fragments,n);if(!o)return this.log(`"${e.identifier}" resumption ${n} does not align with any fragments in ${r} playlist (${i.fragStart}-${i.fragmentEnd})`),!0;let s=r===`audio`?.175:0;return Math.abs(o.start-n)<Rf+s||Math.abs(o.end-n)<Rf+s?!1:(this.log(`"${e.identifier}" resumption ${n} not aligned with ${r} fragment bounds (${o.start}-${o.end} sn: ${o.sn} cc: ${o.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;let t=e.timelineStart,n=0,r=!1,i=!1;for(let a=0;a<e.assetList.length;a++){let o=e.assetList[a],s=t+n;o.startOffset=n,o.timelineStart=s,r||=o.duration===null,i||=!!o.error;let c=o.error?0:o.duration||0;n+=c}r&&!i?e.duration=Math.max(n,e.duration):e.duration=n}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}};function Xf(e){return`[${e.event?`"`+e.event.identifier+`"`:`primary`}: ${e.start.toFixed(2)}-${e.end.toFixed(2)}]`}var Zf=class{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){let n=e.assetListUrl,r;try{r=Uf(n,this.hls.sessionId,e.baseUrl)}catch(t){let r=this.assignAssetListError(e,z.ASSET_LIST_LOAD_ERROR,t,n);this.hls.trigger(B.ERROR,r);return}t&&r.protocol!==`data:`&&r.searchParams.set(`_HLS_start_offset`,``+t);let i=this.hls.config,a=i.loader,o=new a(i),s={responseType:`json`,url:r.href},c=i.interstitialAssetListLoadPolicy.default,l={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};return o.load(s,l,{onSuccess:(t,n,r,i)=>{let a=t.data,o=a?.ASSETS;if(!Array.isArray(o)){let t=this.assignAssetListError(e,z.ASSET_LIST_PARSING_ERROR,Error(`Invalid interstitial asset list`),r.url,n,i);this.hls.trigger(B.ERROR,t);return}e.assetListResponse=a,this.hls.trigger(B.ASSET_LIST_LOADED,{event:e,assetListResponse:a,networkDetails:i})},onError:(t,n,r,i)=>{let a=this.assignAssetListError(e,z.ASSET_LIST_LOAD_ERROR,Error(`Error loading X-ASSET-LIST: HTTP status ${t.code} ${t.text} (${n.url})`),n.url,i,r);this.hls.trigger(B.ERROR,a)},onTimeout:(t,n,r)=>{let i=this.assignAssetListError(e,z.ASSET_LIST_LOAD_TIMEOUT,Error(`Timeout loading X-ASSET-LIST (${n.url})`),n.url,t,r);this.hls.trigger(B.ERROR,i)}}),this.hls.trigger(B.ASSET_LIST_LOADING,{event:e}),o}assignAssetListError(e,t,n,r,i,a){return e.error=n,{type:R.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:r,error:n,networkDetails:a,stats:i}}};function Qf(e){var t;e==null||(t=e.play())==null||t.catch(()=>{})}function $f(e,t){return`[${e}] Advancing timeline position to ${t}`}var ep=class extends Zr{constructor(e,t){super(`interstitials`,e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{let e=this.currentTime;if(e===void 0||this.playbackDisabled||!this.schedule)return;let t=e-this.timelinePos;if(Math.abs(t)<1/7056e5)return;let n=t<=-.01;this.timelinePos=e,this.bufferedPos=e;let r=this.playingItem;if(!r){this.checkBuffer();return}if(n&&this.schedule.resetErrorsInRange(e,e-t)&&this.updateSchedule(!0),this.checkBuffer(),n&&e<r.start||e>=r.end){var i;let t=this.findItemIndex(r),a=this.schedule.findItemIndexAtTime(e);if(a===-1&&(a=t+(n?-1:1),this.log(`seeked ${n?`back `:``}to position not covered by schedule ${e} (resolving from ${t} to ${a})`)),!this.isInterstitial(r)&&(i=this.media)!=null&&i.paused&&(this.shouldPlay=!1),!n&&a>t){let e=this.schedule.findJumpRestrictedIndex(t+1,a);if(e>t){this.setSchedulePosition(e);return}}this.setSchedulePosition(a);return}let a=this.playingAsset;if(!a){if(this.playingLastItem&&this.isInterstitial(r)){let t=r.event.assetList[0];t&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(e,t))}return}let o=a.timelineStart,s=a.duration||0;if(n&&e<o||e>=o+s){var c;(c=r.event)!=null&&c.appendInPlace&&(this.clearAssetPlayers(r.event,r),this.flushFrontBuffer(e)),this.setScheduleToAssetAtTime(e,a)}},this.onTimeupdate=()=>{let e=this.currentTime;if(e===void 0||this.playbackDisabled)return;if(e>this.timelinePos)this.timelinePos=e,e>this.bufferedPos&&this.checkBuffer();else return;let t=this.playingItem;if(!t||this.playingLastItem)return;if(e>=t.end){this.timelinePos=t.end;let e=this.findItemIndex(t);this.setSchedulePosition(e+1)}let n=this.playingAsset;n&&e>=n.timelineStart+(n.duration||0)&&this.setScheduleToAssetAtTime(e,n)},this.onScheduleUpdate=(e,t)=>{let n=this.schedule;if(!n)return;let r=this.playingItem,i=n.events||[],a=n.items||[],o=n.durations,s=e.map(e=>e.identifier),c=!!(i.length||s.length);(c||t)&&this.log(`INTERSTITIALS_UPDATED (${i.length}): ${i}
30
+ Schedule: ${a.map(e=>Xf(e))} pos: ${this.timelinePos}`),s.length&&this.log(`Removed events ${s}`);let l=null,u=null;r&&(l=this.updateItem(r,this.timelinePos),this.itemsMatch(r,l)?this.playingItem=l:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);let d=this.bufferingItem;if(d&&(u=this.updateItem(d,this.bufferedPos),this.itemsMatch(d,u)?this.bufferingItem=u:d.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(d.event,null))),e.forEach(e=>{e.assetList.forEach(e=>{this.clearAssetPlayer(e.identifier,null)})}),this.playerQueue.forEach(e=>{if(e.interstitial.appendInPlace){let t=e.assetItem.timelineStart,n=e.timelineOffset-t;if(n)try{e.timelineOffset=t}catch(r){Math.abs(n)>Rf&&this.warn(`${r} ("${e.assetId}" ${e.timelineOffset}->${t})`)}}}),c||t){if(this.hls.trigger(B.INTERSTITIALS_UPDATED,{events:i.slice(0),schedule:a.slice(0),durations:o,removedIds:s}),this.isInterstitial(r)&&s.includes(r.event.identifier)){this.warn(`Interstitial "${r.event.identifier}" removed while playing`),this.primaryFallback(r.event);return}r&&this.trimInPlace(l,r),d&&u!==l&&this.trimInPlace(u,d),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new Zf(e),this.schedule=new Yf(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){let e=this.hls;e&&(e.on(B.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(B.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(B.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(B.MANIFEST_LOADING,this.onManifestLoading,this),e.on(B.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(B.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(B.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(B.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(B.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(B.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(B.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(B.BUFFER_APPENDED,this.onBufferAppended,this),e.on(B.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(B.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(B.MEDIA_ENDED,this.onMediaEnded,this),e.on(B.ERROR,this.onError,this),e.on(B.DESTROYING,this.onDestroying,this))}unregisterListeners(){let e=this.hls;e&&(e.off(B.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(B.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(B.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(B.MANIFEST_LOADING,this.onManifestLoading,this),e.off(B.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(B.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(B.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(B.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(B.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(B.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(B.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(B.BUFFER_CODECS,this.onBufferCodecs,this),e.off(B.BUFFER_APPENDED,this.onBufferAppended,this),e.off(B.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(B.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(B.MEDIA_ENDED,this.onMediaEnded,this),e.off(B.ERROR,this.onError,this),e.off(B.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;(e=this.getBufferingPlayer())==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.getBufferingPlayer())==null||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){let e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){xc(e,`play`,this.onPlay),xc(e,`pause`,this.onPause),xc(e,`seeking`,this.onSeeking),xc(e,`timeupdate`,this.onTimeupdate)}onMediaAttaching(e,t){let n=this.media=t.media;bc(n,`seeking`,this.onSeeking),bc(n,`timeupdate`,this.onTimeupdate),bc(n,`play`,this.onPlay),bc(n,`pause`,this.onPause)}onMediaAttached(e,t){let n=this.effectivePlayingItem,r=this.detachedData;if(this.detachedData=null,n===null)this.checkStart();else if(!r){this.clearScheduleState();let e=this.findItemIndex(n);this.setSchedulePosition(e)}}clearScheduleState(){this.log(`clear schedule state`),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){let n=!!t.transferMedia,r=this.media;if(this.media=null,!n&&(r&&this.removeMediaListeners(r),this.detachedData)){let e=this.getBufferingPlayer();e&&(this.log(`Removing schedule state for detachedData and ${e}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,e.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;let e=this,t=()=>e.bufferingItem||e.waitingItem,n=t=>t&&e.getAssetPlayer(t.identifier),r=(t,r,i,o,s)=>{if(t){let c=t[r].start,l=t.event;if(l){if(r===`playout`||l.timelineOccupancy!==zf.Point){let e=n(i);e?.interstitial===l&&(c+=e.assetItem.startOffset+e[s])}}else{let n=o===`bufferedPos`?a():e[o];c+=n-t.start}return c}return 0},i=(t,n)=>{var r;if(t!==0&&n!==`primary`&&(r=e.schedule)!=null&&r.length){let r=e.schedule.findItemIndexAtTime(t),i=e.schedule.items?.[r];if(i)return t+(i[n].start-i.start)}return t},a=()=>{let t=e.bufferedPos;return t===Number.MAX_VALUE?o(`primary`):Math.max(t,0)},o=t=>{var n;return(n=e.primaryDetails)!=null&&n.live?e.primaryDetails.edge:e.schedule?.durations[t]||0},s=(t,i)=>{var a;let o=e.effectivePlayingItem;if(o!=null&&(a=o.event)!=null&&a.restrictions.skip||!e.schedule)return;e.log(`seek to ${t} "${i}"`);let s=e.effectivePlayingItem,c=e.schedule.findItemIndexAtTime(t,i),l=e.schedule.items?.[c],u=e.getBufferingPlayer(),d=u?.interstitial?.appendInPlace,f=s&&e.itemsMatch(s,l);if(s&&(d||f)){let a=n(e.playingAsset),o=a?.media||e.primaryMedia;if(o){let n=i===`primary`?o.currentTime:r(s,i,e.playingAsset,`timelinePos`,`currentTime`),c=t-n,l=(d?n:o.currentTime)+c;if(l>=0&&(!a||d||l<=a.duration)){o.currentTime=l;return}}}if(l){let n=t;if(i!==`primary`){let e=t-l[i].start;n=l.start+e}let r=!e.isInterstitial(l);if((!e.isInterstitial(s)||s.event.appendInPlace)&&(r||l.event.appendInPlace)){let t=e.media||(d?u?.media:null);t&&(t.currentTime=n)}else if(s){let a=e.findItemIndex(s);if(c>a){let t=e.schedule.findJumpRestrictedIndex(a+1,c);if(t>a){e.setSchedulePosition(t);return}}let o=0;if(r)e.timelinePos=n,e.checkBuffer();else{let e=l.event.assetList,n=t-(l[i]||l).start;for(let t=e.length;t--;){let r=e[t];if(r.duration&&n>=r.startOffset&&n<r.startOffset+r.duration){o=t;break}}}e.setSchedulePosition(c,o)}}},c=()=>{let n=e.effectivePlayingItem;if(e.isInterstitial(n))return n;let r=t();return e.isInterstitial(r)?r:null},l={get bufferedEnd(){let n=t(),i=e.bufferingItem;return i&&i===n&&(r(i,`playout`,e.bufferingAsset,`bufferedPos`,`bufferedEnd`)-i.playout.start||e.bufferingAsset?.startOffset)||0},get currentTime(){let t=c(),n=e.effectivePlayingItem;return n&&n===t?r(n,`playout`,e.effectivePlayingAsset,`timelinePos`,`currentTime`)-n.playout.start:0},set currentTime(t){let n=c(),r=e.effectivePlayingItem;r&&r===n&&s(t+r.playout.start,`playout`)},get duration(){let e=c();return e?e.playout.end-e.playout.start:0},get assetPlayers(){let t=c()?.event.assetList;return t?t.map(t=>e.getAssetPlayer(t.identifier)):[]},get playingIndex(){let t=c()?.event;return t&&e.effectivePlayingAsset?t.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return c()}};return this.manager={get events(){var t;return((t=e.schedule)==null||(t=t.events)==null?void 0:t.slice(0))||[]},get schedule(){var t;return((t=e.schedule)==null||(t=t.items)==null?void 0:t.slice(0))||[]},get interstitialPlayer(){return c()?l:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){let n=t();return e.findItemIndex(n)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){let t=e.effectivePlayingItem;return e.findItemIndex(t)},primary:{get bufferedEnd(){return a()},get currentTime(){let t=e.timelinePos;return t>0?t:0},set currentTime(e){s(e,`primary`)},get duration(){return o(`primary`)},get seekableStart(){return e.primaryDetails?.fragmentStart||0}},integrated:{get bufferedEnd(){return r(t(),`integrated`,e.bufferingAsset,`bufferedPos`,`bufferedEnd`)},get currentTime(){return r(e.effectivePlayingItem,`integrated`,e.effectivePlayingAsset,`timelinePos`,`currentTime`)},set currentTime(e){s(e,`integrated`)},get duration(){return o(`integrated`)},get seekableStart(){return i(e.primaryDetails?.fragmentStart||0,`integrated`)}},skip:()=>{let t=e.effectivePlayingItem,n=t?.event;if(n&&!n.restrictions.skip){let r=e.findItemIndex(t);n.appendInPlace?s(t.playout.start+t.event.duration+.001,`playout`):e.advanceAfterAssetEnded(n,r,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){let e=this.playingItem,t=this.schedule?.items;return!this.playbackStarted||!e||!t?!1:this.findItemIndex(e)===t.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e;if(this.mediaSelection===null)return;let t=this.waitingItem||this.playingItem;if(this.isInterstitial(t)&&!t.event.appendInPlace)return;let n=this.media;!n&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(n=this.primaryMedia);let r=n?.currentTime;if(!(r===void 0||!L(r)))return r}get primaryMedia(){return this.media||this.detachedData?.media||null}isInterstitial(e){return!!(e!=null&&e.event)}retreiveMediaSource(e,t){let n=this.getAssetPlayer(e);n&&this.transferMediaFromPlayer(n,t)}transferMediaFromPlayer(e,t){let n=e.interstitial.appendInPlace,r=e.media;if(n&&r===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&r){this.detachedData={media:r};return}let n=e.transferMedia();this.log(`transfer MediaSource from ${e} ${Y(n)}`),this.detachedData=n}else t&&r&&(this.shouldPlay||=!r.paused)}transferMediaTo(e,t){if(e.media===t)return;let n=null,r=this.hls,i=e!==r,a=i&&e.interstitial.appendInPlace,o=this.detachedData?.mediaSource,s;if(r.media)a&&(n=r.transferMedia(),this.detachedData=n),s=`Primary`;else if(o){let e=this.getBufferingPlayer();e?(n=e.transferMedia(),s=`${e}`):s=`detached MediaSource`}else s=`detached media`;if(!n){if(o)n=this.detachedData,this.log(`using detachedData: MediaSource ${Y(n)}`);else if(!this.detachedData||r.media===t){let e=this.playerQueue;e.length>1&&e.forEach(e=>{if(i&&e.interstitial.appendInPlace!==a){let t=e.interstitial;this.clearInterstitial(e.interstitial,null),t.appendInPlace=!1,t.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${t}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}let c=n&&`mediaSource`in n&&n.mediaSource?.readyState!==`closed`,l=c&&n?n:t;this.log(`${c?`transfering MediaSource`:`attaching media`} to ${i?e:`Primary`} from ${s} (media.currentTime: ${t.currentTime})`);let u=this.schedule;if(l===n&&u){let t=i&&e.assetId===u.assetIdAtEnd;l.overrides={duration:u.duration,endOfStream:!i||t,cueRemoval:!i}}e.attachMedia(l)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){let e=this.schedule,t=e?.events;if(!t||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);let n=this.timelinePos,r=this.effectivePlayingItem;if(n===-1){let n=this.hls.startPosition;if(this.log($f(`checkStart`,n)),this.timelinePos=n,t.length&&t[0].cue.pre){let n=e.findEventIndex(t[0].identifier);this.setSchedulePosition(n)}else if(n>=0||!this.primaryLive){let t=this.timelinePos=n>0?n:0,r=e.findItemIndexAtTime(t);this.setSchedulePosition(r)}}else if(r&&!this.playingItem){let t=e.findItemIndex(r);this.setSchedulePosition(t)}}advanceAssetBuffering(e,t){let n=e.event,r=Wf(n,n.findAssetIndex(t));if(!n.isAssetPastPlayoutLimit(r))this.bufferedToEvent(e,r);else if(this.schedule){let t=this.schedule.items?.[this.findItemIndex(e)+1];t&&this.bufferedToItem(t)}}advanceAfterAssetEnded(e,t,n){let r=Wf(e,n);if(!e.isAssetPastPlayoutLimit(r)){if(e.appendInPlace){let t=e.assetList[r];t&&this.advanceInPlace(t.timelineStart)}this.setSchedulePosition(t,r)}else if(this.schedule){let n=this.schedule.items;if(n){let r=t+1;if(r>=n.length){this.setSchedulePosition(-1);return}let i=e.resumeTime;this.timelinePos<i&&(this.log($f(`advanceAfterAssetEnded`,i)),this.timelinePos=i,e.appendInPlace&&this.advanceInPlace(i),this.checkBuffer(this.bufferedPos<i)),this.setSchedulePosition(r)}}}setScheduleToAssetAtTime(e,t){let n=this.schedule;if(!n)return;let r=t.parentIdentifier,i=n.getEvent(r);if(i){let t=n.findEventIndex(r),a=n.findAssetIndex(i,e);this.advanceAfterAssetEnded(i,t,a-1)}}setSchedulePosition(e,t){let n=this.schedule?.items;if(!n||this.playbackDisabled)return;let r=e>=0?n[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${r&&Xf(r)}) pos: ${this.timelinePos}`);let i=this.waitingItem||this.playingItem,a=this.playingLastItem;if(this.isInterstitial(i)){let s=i.event,c=this.playingAsset,l=c?.identifier,u=l?this.getAssetPlayer(l):null;if(u&&l&&(!this.eventItemsMatch(i,r)||t!==void 0&&l!==s.assetList[t].identifier)){var o;let t=s.findAssetIndex(c);if(this.log(`INTERSTITIAL_ASSET_ENDED ${t+1}/${s.assetList.length} ${Kf(c)}`),this.endedAsset=c,this.playingAsset=null,this.hls.trigger(B.INTERSTITIAL_ASSET_ENDED,{asset:c,assetListIndex:t,event:s,schedule:n.slice(0),scheduleIndex:e,player:u}),i!==this.playingItem){this.itemsMatch(i,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(s,this.findItemIndex(this.playingItem),t);return}this.retreiveMediaSource(l,r),u.media&&!((o=this.detachedData)!=null&&o.mediaSource)&&u.detachMedia()}if(!this.eventItemsMatch(i,r)&&(this.endedItem=i,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${s} ${Xf(i)}`),s.hasPlayed=!0,this.hls.trigger(B.INTERSTITIAL_ENDED,{event:s,schedule:n.slice(0),scheduleIndex:e}),s.cue.once)){this.updateSchedule();let e=this.schedule?.items;if(r&&e){let n=this.findItemIndex(r);this.advanceSchedule(n,e,t,i,a)}return}}this.advanceSchedule(e,n,t,i,a)}advanceSchedule(e,t,n,r,i){let a=this.schedule;if(!a)return;let o=t[e]||null,s=this.primaryMedia,c=this.playerQueue;if(c.length&&c.forEach(t=>{let n=t.interstitial,r=a.findEventIndex(n.identifier);(r<e||r>e+1)&&this.clearInterstitial(n,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);let i=o.event;if(n===void 0){n=a.findAssetIndex(i,this.timelinePos);let t=Wf(i,n-1);if(i.isAssetPastPlayoutLimit(t)||i.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(i,e,n);return}n=t}let c=this.waitingItem;this.assetsBuffered(o,s)||this.setBufferingItem(o);let l=this.preloadAssets(i,n);if(this.eventItemsMatch(o,c||r)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${Xf(o)} ${i.appendInPlace?`append in place`:``}`),this.hls.trigger(B.INTERSTITIAL_STARTED,{event:i,schedule:t.slice(0),scheduleIndex:e})),!i.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${i}`);return}if(i.assetListLoader&&=(i.assetListLoader.destroy(),void 0),!s){this.log(`Waiting for attachMedia to start Interstitial ${i}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;let u=i.assetList[n];if(!u){this.advanceAfterAssetEnded(i,e,n||0);return}if(l||=this.getAssetPlayer(u.identifier),l===null||l.destroyed){let e=i.assetList.length;this.warn(`asset ${n+1}/${e} player destroyed ${i}`),l=this.createAssetPlayer(i,u,n),l.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&i.appendInPlace&&this.isAssetBuffered(u))return;this.startAssetPlayer(l,n,t,e,s),this.shouldPlay&&Qf(l.media)}else o?(this.resumePrimary(o,e,r),this.shouldPlay&&Qf(this.hls.media)):i&&this.isInterstitial(r)&&(this.endedItem=null,this.playingItem=r,r.event.appendInPlace||this.attachPrimary(a.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){return this.mediaSelection?.main.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,n){var r;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${Xf(e)}`),!((r=this.detachedData)!=null&&r.mediaSource)){let n=this.timelinePos;(n<e.start||n>=e.end)&&(n=this.getPrimaryResumption(e,t),this.log($f(`resumePrimary`,n)),this.timelinePos=n),this.attachPrimary(n,e)}if(!n)return;let i=this.schedule?.items;i&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${Xf(e)}`),this.hls.trigger(B.INTERSTITIALS_PRIMARY_RESUMED,{schedule:i.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){let n=e.start;if(this.primaryLive){let e=this.primaryDetails;if(t===0)return this.hls.startPosition;if(e&&(n<e.fragmentStart||n>e.edge))return this.hls.liveSyncPosition||-1}return n}isAssetBuffered(e){let t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:X.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,n){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;let r=this.primaryMedia;if(!r)return;let i=this.hls;i.media?this.checkBuffer():(this.transferMediaTo(i,r),n&&this.startLoadingPrimaryAt(e,n)),n||(this.log($f(`attachPrimary`,e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,n))}startLoadingPrimaryAt(e,t){let n=this.hls;!n.loadingEnabled||!n.media||Math.abs((n.mainForwardBufferInfo?.start||n.media.currentTime)-e)>.5?n.startLoad(e,t):n.bufferingEnabled||n.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),(e=this.schedule)==null||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(B.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(B.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1||!this.schedule)return;let n=this.hls.levels[t.level];if(!n.details)return;let r=W(W({},this.mediaSelection||this.altSelection),{},{main:n});this.mediaSelection=r,this.schedule.parseInterstitialDateRanges(r,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){let n=this.hls.audioTracks[t.id],r=this.mediaSelection;if(!r){this.altSelection=W(W({},this.altSelection),{},{audio:n});return}this.mediaSelection=W(W({},r),{},{audio:n})}onSubtitleTrackUpdated(e,t){let n=this.hls.subtitleTracks[t.id],r=this.mediaSelection;if(!r){this.altSelection=W(W({},this.altSelection),{},{subtitles:n});return}this.mediaSelection=W(W({},r),{},{subtitles:n})}onAudioTrackSwitching(e,t){let n=Ja(t);this.playerQueue.forEach(({hls:e})=>e&&(e.setAudioOption(t)||e.setAudioOption(n)))}onSubtitleTrackSwitch(e,t){let n=Ja(t);this.playerQueue.forEach(({hls:e})=>e&&(e.setSubtitleOption(t)||t.id!==-1&&e.setSubtitleOption(n)))}onBufferCodecs(e,t){let n=t.tracks;n&&(this.requiredTracks=n)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){let n=this.playingItem;n&&!this.itemsMatch(n,this.bufferingItem)&&!this.isInterstitial(n)&&(this.bufferedPos=this.timelinePos,this.checkBuffer())}onBufferedToEnd(e){if(!this.schedule)return;let t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let e=0;e<t.length;e++){let n=t[e];if(n.cue.post){let e=this.schedule.findEventIndex(n.identifier),t=this.schedule.items?.[e];this.isInterstitial(t)&&this.eventItemsMatch(t,this.bufferingItem)&&this.bufferedToItem(t,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){let t=this.playingItem;if(!this.playingLastItem&&t){let e=this.findItemIndex(t);this.setSchedulePosition(e+1)}else this.shouldPlay=!1}updateItem(e,t){let n=this.schedule?.items;return e&&n&&n[this.findItemIndex(e,t)]||null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((t,n)=>{e.event.isAssetPastPlayoutLimit(n)&&this.clearAssetPlayer(t.identifier,null)});let n=e.end+.25,r=X.bufferInfo(this.primaryMedia,n,0);(r.end>n||(r.nextStart||0)>n)&&(this.log(`trim buffered interstitial ${Xf(e)} (was ${Xf(t)})`),this.attachPrimary(n,null,!0),this.flushFrontBuffer(n))}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){return!!t&&(e===t||e.event.identifier===t.event?.identifier)}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;let n=this.mediaSelection;n&&((t=this.schedule)==null||t.updateSchedule(n,[],e))}checkBuffer(e){let t=this.schedule?.items;if(!t)return;let n=X.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||=n.len<1,this.updateBufferedPos(n.end,t,e)}updateBufferedPos(e,t,n){let r=this.schedule,i=this.bufferingItem;if(this.bufferedPos>e||!r)return;if(t.length===1&&this.itemsMatch(t[0],i)){this.bufferedPos=e;return}let a=this.playingItem,o=this.findItemIndex(a),s=r.findItemIndexAtTime(e);if(this.bufferedPos<e){var c;let n=this.findItemIndex(i),r=Math.min(n+1,t.length-1),a=t[r];if((s===-1&&i&&e>=i.end||(c=a.event)!=null&&c.appendInPlace&&e+.01>=a.start)&&(s=r),this.isInterstitial(i)){let e=i.event;if(r-o>1&&e.appendInPlace===!1||e.assetList.length===0&&e.assetListLoader)return}if(this.bufferedPos=e,s>n&&s>o)this.bufferedToItem(a);else{let t=this.primaryDetails;this.primaryLive&&t&&e>t.edge-t.targetduration&&a.start<t.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(a)&&this.preloadAssets(a.event,0)}}else n&&a&&!this.itemsMatch(a,i)&&(s===o?this.bufferedToItem(a):s===o+1&&this.bufferedToItem(t[s]))}assetsBuffered(e,t){return e.event.assetList.length===0?!1:!e.event.assetList.some(e=>{let n=this.getAssetPlayer(e.identifier);return!(n!=null&&n.bufferedInPlaceToEnd(t))})}setBufferingItem(e){let t=this.bufferingItem,n=this.schedule;if(!this.itemsMatch(e,t)&&n){let{items:r,events:i}=n;if(!r||!i)return t;let a=this.isInterstitial(e),o=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));let s=o?o.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${Xf(e)}`+(t?` (${s.toFixed(2)} remaining)`:``)),!this.playbackDisabled)if(a){let t=n.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((e,n)=>{let r=this.getAssetPlayer(e.identifier);r&&(n===t&&r.loadSource(),r.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(e=>e.pauseBuffering());this.hls.trigger(B.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:i.slice(0),schedule:r.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){let n=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(n!==null){this.bufferingAsset=null;let t=this.detachedData;t&&t.mediaSource?this.attachPrimary(e.start,e,!0):this.preloadPrimary(e)}}}preloadPrimary(e){let t=this.findItemIndex(e),n=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(n)}bufferedToEvent(e,t){let n=e.event,r=n.assetList.length===0&&!n.assetListLoader,i=n.cue.once;if(r||!i){let e=this.preloadAssets(n,t);if(e!=null&&e.interstitial.appendInPlace){let t=this.primaryMedia;t&&this.bufferAssetPlayer(e,t)}}}preloadAssets(e,t){let n=e.assetUrl,r=e.assetList.length,i=r===0&&!e.assetListLoader,a=e.cue.once;if(i){let i=e.timelineStart;if(e.appendInPlace){var o;let t=this.playingItem;!this.isInterstitial(t)&&(t==null||(o=t.nextEvent)==null?void 0:o.identifier)===e.identifier&&this.flushFrontBuffer(i+.25)}let a,s=0;if(!this.playingItem&&this.primaryLive&&(s=this.hls.startPosition,s===-1&&(s=this.hls.liveSyncPosition||0)),s&&!(e.cue.pre||e.cue.post)){let e=s-i;e>0&&(a=Math.round(e*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${n?1:r} ${e}${a?` live-start: ${s} start-offset: ${a}`:``}`),n)return this.createAsset(e,0,0,i,e.duration,n);let c=this.assetListLoader.loadAssetList(e,a);c&&(e.assetListLoader=c)}else if(!a&&r){for(let n=t;n<r;n++){let t=e.assetList[n],r=this.getAssetPlayerQueueIndex(t.identifier);(r===-1||this.playerQueue[r].destroyed)&&!t.error&&this.createAssetPlayer(e,t,n)}let n=e.assetList[t];if(n){let e=this.getAssetPlayer(n.identifier);return e&&e.loadSource(),e}}return null}flushFrontBuffer(e){let t=this.requiredTracks;t&&(this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(t=>{this.hls.trigger(B.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:t})}))}getAssetPlayerQueueIndex(e){let t=this.playerQueue;for(let n=0;n<t.length;n++)if(e===t[n].assetId)return n;return-1}getAssetPlayer(e){let t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){let{playerQueue:e,primaryMedia:t}=this;if(t){for(let n=0;n<e.length;n++)if(e[n].media===t)return e[n]}return null}createAsset(e,t,n,r,i,a){let o={parentIdentifier:e.identifier,identifier:Bf(e,a,t),duration:i,startOffset:n,timelineStart:r,uri:a};return this.createAssetPlayer(e,o,t)}createAssetPlayer(e,t,n){let r=this.hls,i=r.userConfig,a=i.videoPreference,o=r.loadLevelObj||r.levels[r.currentLevel];(a||o)&&(a=U({},a),o.videoCodec&&(a.videoCodec=o.videoCodec),o.videoRange&&(a.allowedVideoRanges=[o.videoRange]));let s=r.audioTracks[r.audioTrack],c=r.subtitleTracks[r.subtitleTrack],l=0;if(this.primaryLive||e.appendInPlace){let e=this.timelinePos-t.timelineStart;if(e>1){let n=t.duration;n&&e<n&&(l=e)}}let u=t.identifier,d=W(W({},i),{},{maxMaxBufferLength:Math.min(180,r.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:r.sessionId,assetPlayerId:u,abrEwmaDefaultEstimate:r.bandwidthEstimate,interstitialsController:void 0,startPosition:l,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:a,audioPreference:s||i.audioPreference,subtitlePreference:c||i.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(d.timelineOffset=t.timelineStart));let f=d.cmcd;f!=null&&f.sessionId&&f.contentId&&(d.cmcd=U({},f,{contentId:Lf(t.uri)})),this.getAssetPlayer(u)&&this.warn(`Duplicate date range identifier ${e} and asset ${u}`);let p=new qf(this.HlsPlayerClass,d,e,t);this.playerQueue.push(p),e.assetList[n]=t;let m=!0,h=r=>{if(r.live){let t=Error(`Interstitials MUST be VOD assets ${e}`),r={fatal:!0,type:R.OTHER_ERROR,details:z.INTERSTITIAL_ASSET_ITEM_ERROR,error:t},i=this.schedule?.findEventIndex(e.identifier)||-1;this.handleAssetItemError(r,e,i,n,t.message);return}let i=r.edge-r.fragmentStart,a=t.duration;(m||a===null||i>a)&&(m=!1,this.log(`Interstitial asset "${u}" duration change ${a} > ${i}`),t.duration=i,this.updateSchedule())};p.on(B.LEVEL_UPDATED,(e,{details:t})=>h(t)),p.on(B.LEVEL_PTS_UPDATED,(e,{details:t})=>h(t)),p.on(B.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());let g=(e,t)=>{let n=this.getAssetPlayer(u);if(n&&t.tracks){n.off(B.BUFFER_CODECS,g),n.tracks=t.tracks;let e=this.primaryMedia;this.bufferingAsset===n.assetItem&&e&&!n.media&&this.bufferAssetPlayer(n,e)}};p.on(B.BUFFER_CODECS,g),p.on(B.BUFFERED_TO_END,()=>{let n=this.getAssetPlayer(u);if(this.log(`buffered to end of asset ${n}`),!n||!this.schedule)return;let r=this.schedule.findEventIndex(e.identifier),i=this.schedule.items?.[r];this.isInterstitial(i)&&this.advanceAssetBuffering(i,t)});let _=t=>()=>{if(!this.getAssetPlayer(u)||!this.schedule)return;this.shouldPlay=!0;let n=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,n,t)};return p.once(B.MEDIA_ENDED,_(n)),p.once(B.PLAYOUT_LIMIT_REACHED,_(1/0)),p.on(B.ERROR,(t,r)=>{if(!this.schedule)return;let i=this.getAssetPlayer(u);if(r.details===z.BUFFER_STALLED_ERROR){if(i!=null&&i.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(r,e,this.schedule.findEventIndex(e.identifier),n,`Asset player error ${r.error} ${e}`)}),p.on(B.DESTROYING,()=>{if(!this.getAssetPlayer(u)||!this.schedule)return;let t=Error(`Asset player destroyed unexpectedly ${u}`),r={fatal:!0,type:R.OTHER_ERROR,details:z.INTERSTITIAL_ASSET_ITEM_ERROR,error:t};this.handleAssetItemError(r,e,this.schedule.findEventIndex(e.identifier),n,t.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${Kf(t)}`),this.hls.trigger(B.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:n,event:e,player:p}),p}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(e=>{this.clearAssetPlayer(e.identifier,t)})}resetAssetPlayer(e){let t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);let n=this.playerQueue[t];this.transferMediaFromPlayer(n,null),n.resetDetails()}}clearAssetPlayer(e,t){let n=this.getAssetPlayerQueueIndex(e);if(n!==-1){let e=this.playerQueue[n];this.log(`clear ${e} toSegment: ${t&&Xf(t)}`),this.transferMediaFromPlayer(e,t),this.playerQueue.splice(n,1),e.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,n,r,i){let{interstitial:a,assetItem:o,assetId:s}=e,c=a.assetList.length,l=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(!l||l.identifier!==s)&&(l&&(this.clearAssetPlayer(l.identifier,n[r]),delete l.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${c} ${Kf(o)}`),this.hls.trigger(B.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:t,event:a,schedule:n.slice(0),scheduleIndex:r,player:e})),this.bufferAssetPlayer(e,i)}bufferAssetPlayer(e,t){if(!this.schedule)return;let{interstitial:n,assetItem:r}=e,i=this.schedule.findEventIndex(n.identifier),a=this.schedule.items?.[i];if(!a)return;e.loadSource(),this.setBufferingItem(a),this.bufferingAsset=r;let o=this.getBufferingPlayer();if(o===e)return;let s=n.appendInPlace;if(s&&o?.interstitial.appendInPlace===!1)return;let c=o?.tracks||this.detachedData?.tracks||this.requiredTracks;if(s&&r!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(c&&!si(c,e.tracks)){let t=Error(`Asset ${Kf(r)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(c)}')`),a={fatal:!0,type:R.OTHER_ERROR,details:z.INTERSTITIAL_ASSET_ITEM_ERROR,error:t},o=n.findAssetIndex(r);this.handleAssetItemError(a,n,i,o,t.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){let t=this.schedule,n=this.primaryMedia;if(!t||!n)return;let r=n.currentTime,i=t.findAssetIndex(e,r),a=e.assetList[i];if(a){let o=this.getAssetPlayer(a.identifier);if(o){let s=o.currentTime||r-a.timelineStart,c=o.duration-s;if(this.warn(`Stalled at ${s} of ${s+c} in ${o} ${e} (media.currentTime: ${r})`),s&&(c/n.playbackRate<.5||o.bufferedInPlaceToEnd(n))&&o.hls){let n=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,n,i)}}}}advanceInPlace(e){let t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e)}handleAssetItemError(e,t,n,r,i){if(e.details===z.BUFFER_STALLED_ERROR)return;let a=t.assetList[r]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${a&&Kf(a)} ${e.error}`),!this.schedule)return;let o=a?.identifier||``,s=this.getAssetPlayerQueueIndex(o),c=this.playerQueue[s]||null,l=this.schedule.items,u=U({},e,{fatal:!1,errorAction:wo(!0),asset:a,assetListIndex:r,event:t,schedule:l,scheduleIndex:n,player:c});if(this.hls.trigger(B.INTERSTITIAL_ASSET_ERROR,u),!e.fatal)return;let d=this.playingAsset,f=this.bufferingAsset,p=Error(i);if(a&&(this.clearAssetPlayer(o,null),a.error=p),!t.assetList.some(e=>!e.error))t.error=p;else for(let e=r;e<t.assetList.length;e++)this.resetAssetPlayer(t.assetList[e].identifier);this.updateSchedule(!0),t.error?this.primaryFallback(t):d&&d.identifier===o?this.advanceAfterAssetEnded(t,n,r):f&&f.identifier===o&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,f)}primaryFallback(e){let t=e.timelineStart,n=this.effectivePlayingItem,r=this.timelinePos;if(n){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${r} playing: ${Xf(n)} error: ${e.error}`),r===-1&&(r=this.hls.startPosition);let i=this.updateItem(n,r);this.itemsMatch(n,i)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(r===-1){this.checkStart();return}if(!this.schedule)return;let i=this.schedule.findItemIndexAtTime(r);this.setSchedulePosition(i)}onAssetListLoaded(e,t){var n;let r=t.event,i=r.identifier,a=t.assetListResponse.ASSETS;if(!((n=this.schedule)!=null&&n.hasEvent(i)))return;let o=r.timelineStart,s=r.duration,c=0;a.forEach((e,t)=>{let n=parseFloat(e.DURATION);this.createAsset(r,t,c,o+c,n,e.URI),c+=n}),r.duration=c,this.log(`Loaded asset-list with duration: ${c} (was: ${s}) ${r}`);let l=this.waitingItem?.event.identifier===i;this.updateSchedule();let u=this.bufferingItem?.event;if(l){let e=this.schedule.findEventIndex(i),t=this.schedule.items?.[e];if(t){if(!this.playingItem&&this.timelinePos>t.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==e){r.error=Error(`Interstitial ${a.length?`no longer within playback range`:`asset-list is empty`} ${this.timelinePos} ${r}`),this.log(r.error.message),this.updateSchedule(!0),this.primaryFallback(r);return}this.setBufferingItem(t)}this.setSchedulePosition(e)}else if(u?.identifier===i){let e=r.assetList[0];if(e){let t=this.getAssetPlayer(e.identifier);if(u.appendInPlace){let e=this.primaryMedia;t&&e&&this.bufferAssetPlayer(t,e)}else t&&t.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case z.ASSET_LIST_PARSING_ERROR:case z.ASSET_LIST_LOAD_ERROR:case z.ASSET_LIST_LOAD_TIMEOUT:{let e=t.interstitial;e&&(this.updateSchedule(!0),this.primaryFallback(e));break}case z.BUFFER_STALLED_ERROR:{let e=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(e)&&e.event.appendInPlace){this.handleInPlaceStall(e.event);return}this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}},tp=500,np=class extends Cc{constructor(e,t,n){super(e,t,n,`subtitle-stream-controller`,H.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(B.LEVEL_LOADED,this.onLevelLoaded,this),e.on(B.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(B.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(B.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(B.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(B.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(B.LEVEL_LOADED,this.onLevelLoaded,this),e.off(B.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(B.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(B.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(B.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(B.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=Z.IDLE,this.setInterval(tp),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){let{frag:n,success:r}=t;if(this.fragContextChanged(n)||(vi(n)&&(this.fragPrevious=n),this.state=Z.IDLE),!r)return;let i=this.tracksBuffered[this.currentTrackId];if(!i)return;let a,o=n.start;for(let e=0;e<i.length;e++)if(o>=i[e].start&&o<=i[e].end){a=i[e];break}let s=n.start+n.duration;a?a.end=s:(a={start:o,end:s},i.push(a)),this.fragmentTracker.fragBuffered(n),this.fragBufferedComplete(n,null),this.media&&this.tick()}onBufferFlushing(e,t){let{startOffset:n,endOffset:r}=t;if(n===0&&r!==1/0){let e=r-1;if(e<=0)return;t.endOffsetSubtitles=Math.max(0,e),this.tracksBuffered.forEach(t=>{for(let n=0;n<t.length;){if(t[n].end<=e){t.shift();continue}else if(t[n].start<e)t[n].start=e;else break;n++}}),this.fragmentTracker.removeFragmentsInRange(n,e,H.SUBTITLE)}}onError(e,t){let n=t.frag;n?.type===H.SUBTITLE&&(t.details===z.FRAG_GAP&&this.fragmentTracker.fragBuffered(n,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==Z.STOPPED&&(this.state=Z.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&Lu(this.levels,t)){this.levels=t.map(e=>new za(e));return}this.tracksBuffered=[],this.levels=t.map(e=>{let t=new za(e);return this.tracksBuffered[t.id]=[],t}),this.fragmentTracker.removeFragmentsInRange(0,1/0,H.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var n;if(this.currentTrackId=t.id,!((n=this.levels)!=null&&n.length)||this.currentTrackId===-1){this.clearInterval();return}let r=this.levels[this.currentTrackId];r!=null&&r.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,r&&this.state!==Z.STOPPED&&this.setInterval(tp)}onSubtitleTrackLoaded(e,t){var n;let{currentTrackId:r,levels:i}=this,{details:a,id:o}=t;if(!i){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}let s=i[o];if(o>=i.length||!s)return;this.log(`Subtitle track ${o} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:``},duration:${a.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let c=0;if(a.live||(n=s.details)!=null&&n.live){if(a.deltaUpdateFailed)return;let e=this.mainDetails;if(!e){this.startFragRequested=!1;return}let t=e.fragments[0];s.details?(c=this.alignPlaylists(a,s.details,this.levelLastLoaded?.details),c===0&&t&&(c=t.start,ac(a,c))):a.hasProgramDateTime&&e.hasProgramDateTime?(yc(a,e),c=a.fragmentStart):t&&(c=t.start,ac(a,c)),e&&!this.startFragRequested&&this.setStartPosition(e,c)}s.details=a,this.levelLastLoaded=s,o===r&&(this.hls.trigger(B.SUBTITLE_TRACK_UPDATED,{details:a,id:o,groupId:t.groupId}),this.tick(),a.live&&!this.fragCurrent&&this.media&&this.state===Z.IDLE&&(oo(null,a.fragments,this.media.currentTime,0)||(this.warn(`Subtitle playlist not aligned with playback`),s.details=void 0)))}_handleFragmentLoadComplete(e){let{frag:t,payload:n}=e,r=t.decryptdata,i=this.hls;if(!this.fragContextChanged(t)&&n&&n.byteLength>0&&r!=null&&r.key&&r.iv&&us(r.method)){let e=performance.now();this.decrypter.decrypt(new Uint8Array(n),r.key.buffer,r.iv.buffer,ds(r.method)).catch(e=>{throw i.trigger(B.ERROR,{type:R.MEDIA_ERROR,details:z.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t}),e}).then(n=>{let r=performance.now();i.trigger(B.FRAG_DECRYPTED,{frag:t,payload:n,stats:{tstart:e,tdecrypt:r}})}).catch(e=>{this.warn(`${e.name}: ${e.message}`),this.state=Z.IDLE})}}doTick(){if(!this.media){this.state=Z.IDLE;return}if(this.state===Z.IDLE){let{currentTrackId:e,levels:t}=this,n=t?.[e];if(!n||!t.length||!n.details||this.waitForLive(n))return;let{config:r}=this,i=this.getLoadPosition(),{end:a,len:o}=X.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],i,r.maxBufferHole),s=n.details;if(o>this.hls.maxBufferLength+s.levelTargetDuration)return;let c=s.fragments,l=c.length,u=s.edge,d=null,f=this.fragPrevious;if(a<u){let e=r.maxFragLookUpTolerance,t=a>u-e?0:e;d=oo(f,c,Math.max(c[0].start,a),t),!d&&f&&f.start<c[0].start&&(d=c[0])}else d=c[l-1];if(d=this.filterReplacedPrimary(d,n.details),!d)return;let p=c[d.sn-s.startSN-1];if(p&&p.cc===d.cc&&this.fragmentTracker.getState(p)===To.NOT_LOADED&&(d=p),this.fragmentTracker.getState(d)===To.NOT_LOADED){let e=this.mapToInitFragWhenRequired(d);e&&this.loadFragment(e,n,a)}}}loadFragment(e,t,n){vi(e)?super.loadFragment(e,t,n):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new rp(this.tracksBuffered[this.currentTrackId]||[])}},rp=class{constructor(e){this.buffered=void 0;let t=(t,n,r)=>{if(n>>>=0,n>r-1)throw new DOMException(`Failed to execute '${t}' on 'TimeRanges': The index provided (${n}) is greater than the maximum bound (${r})`);return e[n][t]};this.buffered={get length(){return e.length},end(n){return t(`end`,n,e.length)},start(n){return t(`start`,n,e.length)}}}},ip={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},ap=e=>String.fromCharCode(ip[e]||e),op=15,sp=100,cp={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},lp={17:2,18:4,21:6,22:8,23:10,19:13,20:15},up={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},dp={25:2,26:4,29:6,30:8,31:10,27:13,28:15},fp=[`white`,`green`,`blue`,`cyan`,`red`,`yellow`,`magenta`,`black`,`transparent`],pp=class{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){let n=typeof t==`function`?t():t;G.log(`${this.time} [${e}] ${n}`)}}},mp=function(e){let t=[];for(let n=0;n<e.length;n++)t.push(e[n].toString(16));return t},hp=class{constructor(){this.foreground=`white`,this.underline=!1,this.italics=!1,this.background=`black`,this.flash=!1}reset(){this.foreground=`white`,this.underline=!1,this.italics=!1,this.background=`black`,this.flash=!1}setStyles(e){let t=[`foreground`,`underline`,`italics`,`background`,`flash`];for(let n=0;n<t.length;n++){let r=t[n];e.hasOwnProperty(r)&&(this[r]=e[r])}}isDefault(){return this.foreground===`white`&&!this.underline&&!this.italics&&this.background===`black`&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return`color=`+this.foreground+`, underline=`+this.underline+`, italics=`+this.italics+`, background=`+this.background+`, flash=`+this.flash}},gp=class{constructor(){this.uchar=` `,this.penState=new hp}reset(){this.uchar=` `,this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return this.uchar===` `&&this.penState.isDefault()}},_p=class{constructor(e){this.chars=[],this.pos=0,this.currPenState=new hp,this.cueStartTime=null,this.logger=void 0;for(let e=0;e<sp;e++)this.chars.push(new gp);this.logger=e}equals(e){for(let t=0;t<sp;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<sp;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<sp;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,`Negative cursor position `+this.pos),this.pos=0):this.pos>sp&&(this.logger.log(3,`Too large cursor position `+this.pos),this.pos=sp)}moveCursor(e){let t=this.pos+e;if(e>1)for(let e=this.pos+1;e<t+1;e++)this.chars[e].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(` `,this.currPenState)}insertChar(e){e>=144&&this.backSpace();let t=ap(e);if(this.pos>=sp){this.logger.log(0,()=>`Cannot insert `+e.toString(16)+` (`+t+`) at position `+this.pos+`. Skipping it!`);return}this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1)}clearFromPos(e){let t;for(t=e;t<sp;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){let e=[],t=!0;for(let n=0;n<sp;n++){let r=this.chars[n].uchar;r!==` `&&(t=!1),e.push(r)}return t?``:e.join(``)}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}},vp=class{constructor(e){this.rows=[],this.currRow=op-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<op;t++)this.rows.push(new _p(e));this.logger=e}reset(){for(let e=0;e<op;e++)this.rows[e].clear();this.currRow=op-1}equals(e){let t=!0;for(let n=0;n<op;n++)if(!this.rows[n].equals(e.rows[n])){t=!1;break}return t}copy(e){for(let t=0;t<op;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<op;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,`setCursor: `+e),this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,()=>`pacData = `+Y(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let e=0;e<op;e++)this.rows[e].clear();let e=this.currRow+1-this.nrRollUpRows,n=this.lastOutputScreen;if(n){let r=n.rows[e].cueStartTime,i=this.logger.time;if(r!==null&&i!==null&&r<i)for(let r=0;r<this.nrRollUpRows;r++)this.rows[t-this.nrRollUpRows+r+1].copy(n.rows[e+r])}}this.currRow=t;let n=this.rows[this.currRow];if(e.indent!==null){let t=e.indent,r=Math.max(t-1,0);n.setCursor(e.indent),e.color=n.chars[r].penState.foreground}let r={foreground:e.color,underline:e.underline,italics:e.italics,background:`black`,flash:!1};this.setPen(r)}setBkgData(e){this.logger.log(2,()=>`bkgData = `+Y(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,`roll_up but nrRollUpRows not set yet`);return}this.logger.log(1,()=>this.getDisplayText());let e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,`Rolling up`)}getDisplayText(e){e||=!1;let t=[],n=``,r=-1;for(let n=0;n<op;n++){let i=this.rows[n].getTextString();i&&(r=n+1,e?t.push(`Row `+r+`: '`+i+`'`):t.push(i.trim()))}return t.length>0&&(n=e?`[`+t.join(` | `)+`]`:t.join(`
31
+ `)),n}getTextAndFormat(){return this.rows}},yp=class{constructor(e,t,n){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new vp(n),this.nonDisplayedMemory=new vp(n),this.lastOutputScreen=new vp(n),this.currRollUpRow=this.displayedMemory.rows[op-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=n}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[op-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>`MODE=`+e),this.mode===`MODE_POP-ON`?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!==`MODE_ROLL-UP`&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let t=0;t<e.length;t++)this.writeScreen.insertChar(e[t]);let t=this.writeScreen===this.displayedMemory?`DISP`:`NON_DISP`;this.logger.log(2,()=>t+`: `+this.writeScreen.getDisplayText(!0)),(this.mode===`MODE_PAINT-ON`||this.mode===`MODE_ROLL-UP`)&&(this.logger.log(1,()=>`DISPLAYED: `+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,`RCL - Resume Caption Loading`),this.setMode(`MODE_POP-ON`)}ccBS(){this.logger.log(2,`BS - BackSpace`),this.mode!==`MODE_TEXT`&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,`DER- Delete to End of Row`),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,`RU(`+e+`) - Roll Up`),this.writeScreen=this.displayedMemory,this.setMode(`MODE_ROLL-UP`),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,`FON - Flash On`),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,`RDC - Resume Direct Captioning`),this.setMode(`MODE_PAINT-ON`)}ccTR(){this.logger.log(2,`TR`),this.setMode(`MODE_TEXT`)}ccRTD(){this.logger.log(2,`RTD`),this.setMode(`MODE_TEXT`)}ccEDM(){this.logger.log(2,`EDM - Erase Displayed Memory`),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,`CR - Carriage Return`),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,`ENM - Erase Non-displayed Memory`),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,`EOC - End Of Caption`),this.mode===`MODE_POP-ON`){let e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>`DISP: `+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,`TO(`+e+`) - Tab Offset`),this.writeScreen.moveCursor(e)}ccMIDROW(e){let t={flash:!1};t.underline=e%2==1,t.italics=e>=46,t.italics?t.foreground=`white`:t.foreground=[`white`,`green`,`blue`,`cyan`,`red`,`yellow`,`magenta`][Math.floor(e/2)-16],this.logger.log(2,`MIDROW: `+Y(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){let t=this.logger.time;t!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=t:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}},bp=class{constructor(e,t,n){this.channels=void 0,this.currentChannel=0,this.cmdHistory=Cp(),this.logger=void 0;let r=this.logger=new pp;this.channels=[null,new yp(e,t,r),new yp(e+1,n,r)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let e=0;e<t.length;e+=2){let n=t[e]&127,r=t[e+1]&127,i=!1,a=null;if(n===0&&r===0)continue;this.logger.log(3,()=>`[`+mp([t[e],t[e+1]])+`] -> (`+mp([n,r])+`)`);let o=this.cmdHistory;if(n>=16&&n<=31){if(Sp(n,r,o)){xp(null,null,o),this.logger.log(3,()=>`Repeated command (`+mp([n,r])+`) is dropped`);continue}xp(n,r,this.cmdHistory),i=this.parseCmd(n,r),i||=this.parseMidrow(n,r),i||=this.parsePAC(n,r),i||=this.parseBackgroundAttributes(n,r)}else xp(null,null,o);if(!i&&(a=this.parseChars(n,r),a)){let e=this.currentChannel;e&&e>0?this.channels[e].insertChars(a):this.logger.log(2,`No channel found yet. TEXT-MODE?`)}!i&&!a&&this.logger.log(2,()=>`Couldn't parse cleaned data `+mp([n,r])+` orig: `+mp([t[e],t[e+1]]))}}parseCmd(e,t){if(!((e===20||e===28||e===21||e===29)&&t>=32&&t<=47||(e===23||e===31)&&t>=33&&t<=35))return!1;let n=e===20||e===21||e===23?1:2,r=this.channels[n];return e===20||e===21||e===28||e===29?t===32?r.ccRCL():t===33?r.ccBS():t===34?r.ccAOF():t===35?r.ccAON():t===36?r.ccDER():t===37?r.ccRU(2):t===38?r.ccRU(3):t===39?r.ccRU(4):t===40?r.ccFON():t===41?r.ccRDC():t===42?r.ccTR():t===43?r.ccRTD():t===44?r.ccEDM():t===45?r.ccCR():t===46?r.ccENM():t===47&&r.ccEOC():r.ccTO(t-32),this.currentChannel=n,!0}parseMidrow(e,t){let n=0;if((e===17||e===25)&&t>=32&&t<=47){if(n=e===17?1:2,n!==this.currentChannel)return this.logger.log(0,`Mismatch channel in midrow parsing`),!1;let r=this.channels[n];return r?(r.ccMIDROW(t),this.logger.log(3,()=>`MIDROW (`+mp([e,t])+`)`),!0):!1}return!1}parsePAC(e,t){let n;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127||(e===16||e===24)&&t>=64&&t<=95))return!1;let r=e<=23?1:2;n=t>=64&&t<=95?r===1?cp[e]:up[e]:r===1?lp[e]:dp[e];let i=this.channels[r];return i?(i.setPAC(this.interpretPAC(n,t)),this.currentChannel=r,!0):!1}interpretPAC(e,t){let n,r={color:null,italics:!1,indent:null,underline:!1,row:e};return n=t>95?t-96:t-64,r.underline=(n&1)==1,n<=13?r.color=[`white`,`green`,`blue`,`cyan`,`red`,`yellow`,`magenta`,`white`][Math.floor(n/2)]:n<=15?(r.italics=!0,r.color=`white`):r.indent=Math.floor((n-16)/2)*4,r}parseChars(e,t){let n,r=null,i=null;if(e>=25?(n=2,i=e-8):(n=1,i=e),i>=17&&i<=19){let e;e=i===17?t+80:i===18?t+112:t+144,this.logger.log(2,()=>`Special char '`+ap(e)+`' in channel `+n),r=[e]}else e>=32&&e<=127&&(r=t===0?[e]:[e,t]);return r&&this.logger.log(3,()=>`Char codes = `+mp(r).join(`,`)),r}parseBackgroundAttributes(e,t){if(!((e===16||e===24)&&t>=32&&t<=47||(e===23||e===31)&&t>=45&&t<=47))return!1;let n,r={};e===16||e===24?(n=Math.floor((t-32)/2),r.background=fp[n],t%2==1&&(r.background+=`_semi`)):t===45?r.background=`transparent`:(r.foreground=`black`,t===47&&(r.underline=!0));let i=e<=23?1:2;return this.channels[i].setBkgData(r),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){let t=this.channels[e];t&&t.reset()}xp(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){let n=this.channels[t];n&&n.cueSplitAtTime(e)}}};function xp(e,t,n){n.a=e,n.b=t}function Sp(e,t,n){return n.a===e&&n.b===t}function Cp(){return{a:null,b:null}}var wp=(function(){if(_s!=null&&_s.VTTCue)return self.VTTCue;let e=[``,`lr`,`rl`],t=[`start`,`middle`,`end`,`left`,`right`];function n(e,t){if(typeof t!=`string`||!Array.isArray(e))return!1;let n=t.toLowerCase();return~e.indexOf(n)?n:!1}function r(t){return n(e,t)}function i(e){return n(t,e)}function a(e,...t){let n=1;for(;n<arguments.length;n++){let t=arguments[n];for(let n in t)e[n]=t[n]}return e}function o(e,t,n){let o=this,s={enumerable:!0};o.hasBeenReset=!1;let c=``,l=!1,u=e,d=t,f=n,p=null,m=``,h=!0,g=`auto`,_=`start`,v=50,y=`middle`,b=50,x=`middle`;Object.defineProperty(o,`id`,a({},s,{get:function(){return c},set:function(e){c=``+e}})),Object.defineProperty(o,`pauseOnExit`,a({},s,{get:function(){return l},set:function(e){l=!!e}})),Object.defineProperty(o,`startTime`,a({},s,{get:function(){return u},set:function(e){if(typeof e!=`number`)throw TypeError(`Start time must be set to a number.`);u=e,this.hasBeenReset=!0}})),Object.defineProperty(o,`endTime`,a({},s,{get:function(){return d},set:function(e){if(typeof e!=`number`)throw TypeError(`End time must be set to a number.`);d=e,this.hasBeenReset=!0}})),Object.defineProperty(o,`text`,a({},s,{get:function(){return f},set:function(e){f=``+e,this.hasBeenReset=!0}})),Object.defineProperty(o,`region`,a({},s,{get:function(){return p},set:function(e){p=e,this.hasBeenReset=!0}})),Object.defineProperty(o,`vertical`,a({},s,{get:function(){return m},set:function(e){let t=r(e);if(t===!1)throw SyntaxError(`An invalid or illegal string was specified.`);m=t,this.hasBeenReset=!0}})),Object.defineProperty(o,`snapToLines`,a({},s,{get:function(){return h},set:function(e){h=!!e,this.hasBeenReset=!0}})),Object.defineProperty(o,`line`,a({},s,{get:function(){return g},set:function(e){if(typeof e!=`number`&&e!==`auto`)throw SyntaxError(`An invalid number or illegal string was specified.`);g=e,this.hasBeenReset=!0}})),Object.defineProperty(o,`lineAlign`,a({},s,{get:function(){return _},set:function(e){let t=i(e);if(!t)throw SyntaxError(`An invalid or illegal string was specified.`);_=t,this.hasBeenReset=!0}})),Object.defineProperty(o,`position`,a({},s,{get:function(){return v},set:function(e){if(e<0||e>100)throw Error(`Position must be between 0 and 100.`);v=e,this.hasBeenReset=!0}})),Object.defineProperty(o,`positionAlign`,a({},s,{get:function(){return y},set:function(e){let t=i(e);if(!t)throw SyntaxError(`An invalid or illegal string was specified.`);y=t,this.hasBeenReset=!0}})),Object.defineProperty(o,`size`,a({},s,{get:function(){return b},set:function(e){if(e<0||e>100)throw Error(`Size must be between 0 and 100.`);b=e,this.hasBeenReset=!0}})),Object.defineProperty(o,`align`,a({},s,{get:function(){return x},set:function(e){let t=i(e);if(!t)throw SyntaxError(`An invalid or illegal string was specified.`);x=t,this.hasBeenReset=!0}})),o.displayState=void 0}return o.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},o})(),Tp=class{decode(e,t){if(!e)return``;if(typeof e!=`string`)throw Error(`Error - expected string data.`);return decodeURIComponent(encodeURIComponent(e))}};function Ep(e){function t(e,t,n,r){return(e|0)*3600+(t|0)*60+(n|0)+parseFloat(r||0)}let n=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return n?parseFloat(n[2])>59?t(n[2],n[3],0,n[4]):t(n[1],n[2],n[3],n[4]):null}var Dp=class{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==``&&(this.values[e]=t)}get(e,t,n){return n?this.has(e)?this.values[e]:t[n]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,n){for(let r=0;r<n.length;++r)if(t===n[r]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){let n=parseFloat(t);if(n>=0&&n<=100)return this.set(e,n),!0}return!1}};function Op(e,t,n,r){let i=r?e.split(r):[e];for(let e in i){if(typeof i[e]!=`string`)continue;let r=i[e].split(n);if(r.length!==2)continue;let a=r[0],o=r[1];t(a,o)}}var kp=new wp(0,0,``),Ap=kp.align===`middle`?`middle`:`center`;function jp(e,t,n){let r=e;function i(){let t=Ep(e);if(t===null)throw Error(`Malformed timestamp: `+r);return e=e.replace(/^[^\sa-zA-Z-]+/,``),t}function a(e,t){let r=new Dp;Op(e,function(e,t){let i;switch(e){case`region`:for(let i=n.length-1;i>=0;i--)if(n[i].id===t){r.set(e,n[i].region);break}break;case`vertical`:r.alt(e,t,[`rl`,`lr`]);break;case`line`:i=t.split(`,`),r.integer(e,i[0]),r.percent(e,i[0])&&r.set(`snapToLines`,!1),r.alt(e,i[0],[`auto`]),i.length===2&&r.alt(`lineAlign`,i[1],[`start`,Ap,`end`]);break;case`position`:i=t.split(`,`),r.percent(e,i[0]),i.length===2&&r.alt(`positionAlign`,i[1],[`start`,Ap,`end`,`line-left`,`line-right`,`auto`]);break;case`size`:r.percent(e,t);break;case`align`:r.alt(e,t,[`start`,Ap,`end`,`left`,`right`]);break}},/:/,/\s/),t.region=r.get(`region`,null),t.vertical=r.get(`vertical`,``);let i=r.get(`line`,`auto`);i===`auto`&&kp.line===-1&&(i=-1),t.line=i,t.lineAlign=r.get(`lineAlign`,`start`),t.snapToLines=r.get(`snapToLines`,!0),t.size=r.get(`size`,100),t.align=r.get(`align`,Ap);let a=r.get(`position`,`auto`);a===`auto`&&kp.position===50&&(a=t.align===`start`||t.align===`left`?0:t.align===`end`||t.align===`right`?100:50),t.position=a}function o(){e=e.replace(/^\s+/,``)}if(o(),t.startTime=i(),o(),e.slice(0,3)!==`-->`)throw Error(`Malformed time stamp (time stamps must be separated by '-->'): `+r);e=e.slice(3),o(),t.endTime=i(),o(),a(e,t)}function Mp(e){return e.replace(/<br(?: \/)?>/gi,`
32
+ `)}var Np=class{constructor(){this.state=`INITIAL`,this.buffer=``,this.decoder=new Tp,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){let t=this;e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));function n(){let e=t.buffer,n=0;for(e=Mp(e);n<e.length&&e[n]!==`\r`&&e[n]!==`
33
+ `;)++n;let r=e.slice(0,n);return e[n]===`\r`&&++n,e[n]===`
34
+ `&&++n,t.buffer=e.slice(n),r}function r(e){Op(e,function(e,t){},/:/)}try{let e=``;if(t.state===`INITIAL`){if(!/\r\n|\n/.test(t.buffer))return this;e=n();let r=e.match(/^()?WEBVTT([ \t].*)?$/);if(!(r!=null&&r[0]))throw Error(`Malformed WebVTT signature.`);t.state=`HEADER`}let i=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(i?i=!1:e=n(),t.state){case`HEADER`:/:/.test(e)?r(e):e||(t.state=`ID`);continue;case`NOTE`:e||(t.state=`ID`);continue;case`ID`:if(/^NOTE($|[ \t])/.test(e)){t.state=`NOTE`;break}if(!e)continue;if(t.cue=new wp(0,0,``),t.state=`CUE`,e.indexOf(`-->`)===-1){t.cue.id=e;continue}case`CUE`:if(!t.cue){t.state=`BADCUE`;continue}try{jp(e,t.cue,t.regionList)}catch{t.cue=null,t.state=`BADCUE`;continue}t.state=`CUETEXT`;continue;case`CUETEXT`:{let n=e.indexOf(`-->`)!==-1;if(!e||n&&(i=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state=`ID`;continue}if(t.cue===null)continue;t.cue.text&&(t.cue.text+=`
35
+ `),t.cue.text+=e}continue;case`BADCUE`:e||(t.state=`ID`)}}}catch{t.state===`CUETEXT`&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state=t.state===`INITIAL`?`BADWEBVTT`:`BADCUE`}return this}flush(){let e=this;try{if((e.cue||e.state===`HEADER`)&&(e.buffer+=`
36
36
 
37
- `,e.parse()),e.state==="INITIAL"||e.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}}const cp=/\r\n|\n\r|\n|\r/g,Bn=function(e,t,s=0){return e.slice(s,s+t.length)===t},up=function(e){let t=parseInt(e.slice(-3));const s=parseInt(e.slice(-6,-4)),i=parseInt(e.slice(-9,-7)),n=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!$(t)||!$(s)||!$(i)||!$(n))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*s,t+=60*1e3*i,t+=3600*1e3*n,t};function Un(r,e,t){return di(r.toString())+di(e.toString())+di(t)}const hp=function(e,t,s){let i=e[t],n=e[i.prevCC];if(!n||!n.new&&i.new){e.ccOffset=e.presentationOffset=i.start,i.new=!1;return}for(;(a=n)!=null&&a.new;){var a;e.ccOffset+=i.start-n.start,i.new=!1,i=n,n=e[i.prevCC]}e.presentationOffset=s};function dp(r,e,t,s,i,n,a){const o=new lp,c=je(new Uint8Array(r)).trim().replace(cp,`
37
+ `,e.parse()),e.state===`INITIAL`||e.state===`BADWEBVTT`)throw Error(`Malformed WebVTT signature.`)}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}},Pp=/\r\n|\n\r|\n|\r/g,Fp=function(e,t,n=0){return e.slice(n,n+t.length)===t},Ip=function(e){let t=parseInt(e.slice(-3)),n=parseInt(e.slice(-6,-4)),r=parseInt(e.slice(-9,-7)),i=e.length>9?parseInt(e.substring(0,e.indexOf(`:`))):0;if(!L(t)||!L(n)||!L(r)||!L(i))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*n,t+=60*1e3*r,t+=3600*1e3*i,t};function Lp(e,t,n){return Lf(e.toString())+Lf(t.toString())+Lf(n)}var Rp=function(e,t,n){let r=e[t],i=e[r.prevCC];if(!i||!i.new&&r.new){e.ccOffset=e.presentationOffset=r.start,r.new=!1;return}for(;(a=i)!=null&&a.new;){var a;e.ccOffset+=r.start-i.start,r.new=!1,r=i,i=e[r.prevCC]}e.presentationOffset=n};function zp(e,t,n,r,i,a,o){let s=new Np,c=ci(new Uint8Array(e)).trim().replace(Pp,`
38
38
  `).split(`
39
- `),l=[],u=e?Sg(e.baseTime,e.timescale):0;let h="00:00.000",d=0,g=0,f,p=!0;o.oncue=function(y){const v=t[s];let E=t.ccOffset;const T=(d-u)/9e4;if(v!=null&&v.new&&(g!==void 0?E=t.ccOffset=v.start:hp(t,s,T)),T){if(!e){f=new Error("Missing initPTS for VTT MPEGTS");return}E=T-t.presentationOffset}const S=y.endTime-y.startTime,_=Qe((y.startTime+E-g)*9e4,i*9e4)/9e4;y.startTime=Math.max(_,0),y.endTime=Math.max(_+S,0);const D=y.text.trim();y.text=decodeURIComponent(encodeURIComponent(D)),y.id||(y.id=Un(y.startTime,y.endTime,D)),y.endTime>0&&l.push(y)},o.onparsingerror=function(y){f=y},o.onflush=function(){if(f){a(f);return}n(l)},c.forEach(y=>{if(p)if(Bn(y,"X-TIMESTAMP-MAP=")){p=!1,y.slice(16).split(",").forEach(v=>{Bn(v,"LOCAL:")?h=v.slice(6):Bn(v,"MPEGTS:")&&(d=parseInt(v.slice(7)))});try{g=up(h)/1e3}catch(v){f=v}return}else y===""&&(p=!1);o.parse(y+`
40
- `)}),o.flush()}const Gn="stpp.ttml.im1t",$c=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Bc=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,fp={left:"start",center:"center",right:"end",start:"start",end:"end"};function Uc(r,e,t,s){const i=J(new Uint8Array(r),["mdat"]);if(i.length===0){s(new Error("Could not parse IMSC1 mdat"));return}const n=i.map(o=>je(o)),a=Tg(e.baseTime,1,e.timescale);try{n.forEach(o=>t(gp(o,a)))}catch(o){s(o)}}function gp(r,e){const i=new DOMParser().parseFromString(r,"text/xml").getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");const n={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},a=Object.keys(n).reduce((h,d)=>(h[d]=i.getAttribute(`ttp:${d}`)||n[d],h),{}),o=i.getAttribute("xml:space")!=="preserve",c=Gc(Kn(i,"styling","style")),l=Gc(Kn(i,"layout","region")),u=Kn(i,"body","[begin]");return[].map.call(u,h=>{const d=Kc(h,o);if(!d||!h.hasAttribute("begin"))return null;const g=Hn(h.getAttribute("begin"),a),f=Hn(h.getAttribute("dur"),a);let p=Hn(h.getAttribute("end"),a);if(g===null)throw Vc(h);if(p===null){if(f===null)throw Vc(h);p=g+f}const y=new Nn(g-e,p-e,d);y.id=Un(y.startTime,y.endTime,y.text);const v=l[h.getAttribute("region")],E=c[h.getAttribute("style")],T=mp(v,E,c),{textAlign:S}=T;if(S){const _=fp[S];_&&(y.lineAlign=_),y.align=S}return le(y,T),y}).filter(h=>h!==null)}function Kn(r,e,t){const s=r.getElementsByTagName(e)[0];return s?[].slice.call(s.querySelectorAll(t)):[]}function Gc(r){return r.reduce((e,t)=>{const s=t.getAttribute("xml:id");return s&&(e[s]=t),e},{})}function Kc(r,e){return[].slice.call(r.childNodes).reduce((t,s,i)=>{var n;return s.nodeName==="br"&&i?t+`
41
- `:(n=s.childNodes)!=null&&n.length?Kc(s,e):e?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent},"")}function mp(r,e,t){const s="http://www.w3.org/ns/ttml#styling";let i=null;const n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=r!=null&&r.hasAttribute("style")?r.getAttribute("style"):null;return a&&t.hasOwnProperty(a)&&(i=t[a]),n.reduce((o,c)=>{const l=Vn(e,s,c)||Vn(r,s,c)||Vn(i,s,c);return l&&(o[c]=l),o},{})}function Vn(r,e,t){return r&&r.hasAttributeNS(e,t)?r.getAttributeNS(e,t):null}function Vc(r){return new Error(`Could not parse ttml timestamp ${r}`)}function Hn(r,e){if(!r)return null;let t=Mc(r);return t===null&&($c.test(r)?t=pp(r,e):Bc.test(r)&&(t=yp(r,e))),t}function pp(r,e){const t=$c.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 yp(r,e){const t=Bc.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 hr{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 vp{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=Yc(),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(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(m.FRAG_LOADING,this.onFragLoading,this),e.on(m.FRAG_LOADED,this.onFragLoaded,this),e.on(m.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(m.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(m.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(m.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(m.FRAG_LOADING,this.onFragLoading,this),e.off(m.FRAG_LOADED,this.onFragLoaded,this),e.off(m.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(m.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(m.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(m.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new hr(this,"textTrack1"),t=new hr(this,"textTrack2"),s=new hr(this,"textTrack3"),i=new hr(this,"textTrack4");this.cea608Parser1=new Oc(1,e,t),this.cea608Parser2=new Oc(3,s,i)}addCues(e,t,s,i,n){let a=!1;for(let o=n.length;o--;){const c=n[o],l=Ep(c[0],c[1],t,s);if(l>=0&&(c[0]=Math.min(c[0],t),c[1]=Math.max(c[1],s),a=!0,l/(s-t)>.5))return}if(a||n.push([t,s]),this.config.renderTextTracksNatively){const o=this.captionsTracks[e];this.Cues.newCue(o,t,s,i)}else{const o=this.Cues.newCue(null,t,s,i);this.hls.trigger(m.CUES_PARSED,{type:"captions",cues:o,track:e})}}onInitPtsFound(e,{frag:t,id:s,initPTS:i,timescale:n,trackId:a}){const{unparsedVttFrags:o}=this;s===G.MAIN&&(this.initPTS[t.cc]={baseTime:i,timescale:n,trackId:a}),o.length&&(this.unparsedVttFrags=[],o.forEach(c=>{this.initPTS[c.frag.cc]?this.onFragLoaded(m.FRAG_LOADED,c):this.hls.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:c.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(e,t){const{media:s}=this;if(s)for(let i=0;i<s.textTracks.length;i++){const n=s.textTracks[i];if(Wc(n,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return n}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:i}=this,{label:n,languageCode:a}=t[e],o=this.getExistingTrack(n,a);if(o)s[e]=o,Vs(s[e]),Ic(s[e],i);else{const c=this.createTextTrack("captions",n,a);c&&(c[e]=!0,s[e]=c)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const s=t.label,i={_id:e,label:s,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=i,this.hls.trigger(m.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}createTextTrack(e,t,s){const i=this.media;if(i)return i.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:i}=this;Object.keys(i).forEach(n=>{Vs(i[n]),delete i[n]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Yc(),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++)Vs(t[s])}onSubtitleTracksUpdated(e,t){const s=t.subtitleTracks||[],i=s.some(n=>n.textCodec===Gn);if(this.config.enableWebVTT||i&&this.config.enableIMSC1){if(nc(this.tracks,s)){this.tracks=s;return}if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){const a=this.media,o=a?ar(a.textTracks):null;if(this.tracks.forEach((c,l)=>{let u;if(o){let h=null;for(let d=0;d<o.length;d++)if(o[d]&&Wc(o[d],c)){h=o[d],o[d]=null;break}h&&(u=h)}if(u)Vs(u);else{const h=Hc(c);u=this.createTextTrack(h,c.name,c.lang),u&&(u.mode="disabled")}u&&this.textTracks.push(u)}),o!=null&&o.length){const c=o.filter(l=>l!==null).map(l=>l.label);c.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${c.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const a=this.tracks.map(o=>({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(m.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:a})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(s=>{const i=/(?:CC|SERVICE)([1-4])/.exec(s.instreamId);if(!i)return;const n=`textTrack${i[1]}`,a=this.captionsProperties[n];a&&(a.label=s.name,s.lang&&(a.languageCode=s.lang),a.media=s)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t?.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===G.MAIN){var s,i;const{cea608Parser1:n,cea608Parser2:a,lastSn:o}=this,{cc:c,sn:l}=t.frag,u=(s=(i=t.part)==null?void 0:i.index)!=null?s:-1;n&&a&&(l!==o+1||l===o&&u!==this.lastPartIndex+1||c!==this.lastCc)&&(n.reset(),a.reset()),this.lastCc=c,this.lastSn=l,this.lastPartIndex=u}}onFragLoaded(e,t){const{frag:s,payload:i}=t;if(s.type===G.SUBTITLE)if(i.byteLength){const n=s.decryptdata,a="stats"in t;if(n==null||!n.encrypted||a){const o=this.tracks[s.level],c=this.vttCCs;c[s.cc]||(c[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),o&&o.textCodec===Gn?this._parseIMSC1(s,i):this._parseVTTs(t)}}else this.hls.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const s=this.hls;Uc(t,this.initPTS[e.cc],i=>{this._appendCues(i,e.level),s.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},i=>{s.logger.log(`Failed to parse IMSC1: ${i}`),s.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:i})})}_parseVTTs(e){var t;const{frag:s,payload:i}=e,{initPTS:n,unparsedVttFrags:a}=this,o=n.length-1;if(!n[s.cc]&&o===-1){a.push(e);return}const c=this.hls,l=(t=s.initSegment)!=null&&t.data?nt(s.initSegment.data,new Uint8Array(i)).buffer:i;dp(l,this.initPTS[s.cc],this.vttCCs,s.cc,s.start,u=>{this._appendCues(u,s.level),c.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s})},u=>{const h=u.message==="Missing initPTS for VTT MPEGTS";h?a.push(e):this._fallbackToIMSC1(s,i),c.logger.log(`Failed to parse VTT cue: ${u}`),!(h&&o>s.cc)&&c.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:u})})}_fallbackToIMSC1(e,t){const s=this.tracks[e.level];s.textCodec||Uc(t,this.initPTS[e.cc],()=>{s.textCodec=Gn,this._parseIMSC1(e,t)},()=>{s.textCodec="wvtt"})}_appendCues(e,t){const s=this.hls;if(this.config.renderTextTracksNatively){const i=this.textTracks[t];if(!i||i.mode==="disabled")return;e.forEach(n=>Lc(i,n))}else{const i=this.tracks[t];if(!i)return;const n=i.default?"default":"subtitles"+t;s.trigger(m.CUES_PARSED,{type:"subtitles",cues:e,track:n})}}onFragDecrypted(e,t){const{frag:s}=t;s.type===G.SUBTITLE&&this.onFragLoaded(m.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:s,samples:i}=t;if(!(s.type===G.MAIN&&this.closedCaptionsForLevel(s)==="NONE"))for(let n=0;n<i.length;n++){const a=i[n].bytes;if(a){this.cea608Parser1||this.initCea608Parsers();const o=this.extractCea608Data(a);this.cea608Parser1.addData(i[n].pts,o[0]),this.cea608Parser2.addData(i[n].pts,o[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:s,endOffsetSubtitles:i,type:n}){const{media:a}=this;if(!(!a||a.currentTime<s)){if(!n||n==="video"){const{captionsTracks:o}=this;Object.keys(o).forEach(c=>kn(o[c],t,s))}if(this.config.renderTextTracksNatively&&t===0&&i!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(c=>kn(o[c],t,i))}}}extractCea608Data(e){const t=[[],[]],s=e[0]&31;let i=2;for(let n=0;n<s;n++){const a=e[i++],o=127&e[i++],c=127&e[i++];if(o===0&&c===0)continue;if((4&a)!==0){const u=3&a;(u===0||u===1)&&(t[u].push(o),t[u].push(c))}}return t}}function Hc(r){return r.characteristics&&/transcribes-spoken-dialog/gi.test(r.characteristics)&&/describes-music-and-sound/gi.test(r.characteristics)?"captions":"subtitles"}function Wc(r,e){return!!r&&r.kind===Hc(e)&&In(e,r)}function Ep(r,e,t,s){return Math.min(e,s)-Math.max(r,t)}function Yc(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}const Tp=/\s/,Sp={newCue(r,e,t,s){const i=[];let n,a,o,c,l;const u=self.VTTCue||self.TextTrackCue;for(let d=0;d<s.rows.length;d++)if(n=s.rows[d],o=!0,c=0,l="",!n.isEmpty()){var h;for(let p=0;p<n.chars.length;p++)Tp.test(n.chars[p].uchar)&&o?c++:(l+=n.chars[p].uchar,o=!1);n.cueStartTime=e,e===t&&(t+=1e-4),c>=16?c--:c++;const g=Nc(l.trim()),f=Un(e,t,g);r!=null&&(h=r.cues)!=null&&h.getCueById(f)||(a=new u(e,t,g),a.id=f,a.line=d+1,a.align="left",a.position=10+Math.min(80,Math.floor(c*8/32)*10),i.push(a))}return r&&i.length&&(i.sort((d,g)=>d.line==="auto"||g.line==="auto"?0:d.line>8&&g.line>8?g.line-d.line:d.line-g.line),i.forEach(d=>Lc(r,d))),i}};function xp(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const Ap=/(\d+)-(\d+)\/(\d+)/;class qc{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||Rp,this.controller=new self.AbortController,this.stats=new Ur}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 i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now();const n=_p(e,this.controller.signal),a=e.responseType==="arraybuffer",o=a?"byteLength":"length",{maxTimeToFirstByteMs:c,maxLoadTimeMs:l}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=s,this.request=this.fetchSetup(e,n),self.clearTimeout(this.requestTimeout),t.timeout=c&&$(c)?c:l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,e,this.response))},t.timeout),(ui(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(h=>{var d;this.response=this.loader=h;const g=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,e,this.response))},l-(g-i.loading.start)),!h.ok){const{status:p,statusText:y}=h;throw new bp(y||"fetch, bad network response",p,h)}i.loading.first=g,i.total=Lp(h.headers)||i.total;const f=(d=this.callbacks)==null?void 0:d.onProgress;return f&&$(t.highWaterMark)?this.loadProgressively(h,i,e,t.highWaterMark,f):a?h.arrayBuffer():e.responseType==="json"?h.json():h.text()}).then(h=>{var d,g;const f=this.response;if(!f)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);const p=h[o];p&&(i.loaded=i.total=p);const y={url:f.url,data:h,code:f.status},v=(d=this.callbacks)==null?void 0:d.onProgress;v&&!$(t.highWaterMark)&&v(i,e,h,f),(g=this.callbacks)==null||g.onSuccess(y,i,e,f)}).catch(h=>{var d;if(self.clearTimeout(this.requestTimeout),i.aborted)return;const g=h&&h.code||0,f=h?h.message:null;(d=this.callbacks)==null||d.onError({code:g,text:f},e,h?h.details:null,i)})}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,i=0,n){const a=new Pl,o=e.body.getReader(),c=()=>o.read().then(l=>{if(l.done)return a.dataLength&&n(t,s,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const u=l.value,h=u.length;return t.loaded+=h,h<i||a.dataLength?(a.push(u),a.dataLength>=i&&n(t,s,a.flush().buffer,e)):n(t,s,u.buffer,e),c()}).catch(()=>Promise.reject());return c()}}function _p(r,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(le({},r.headers))};return r.rangeEnd&&t.headers.set("Range","bytes="+r.rangeStart+"-"+String(r.rangeEnd-1)),t}function Ip(r){const e=Ap.exec(r);if(e)return parseInt(e[2])-parseInt(e[1])+1}function Lp(r){const e=r.get("Content-Range");if(e){const s=Ip(e);if($(s))return s}const t=r.get("Content-Length");if(t)return parseInt(t)}function Rp(r,e){return new self.Request(r.url,e)}class bp extends Error{constructor(e,t,s){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=s}}const Dp=/^age:\s*[\d.]+\s*$/im;class jc{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 Ur,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,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;const n=this.xhrSetup;n?Promise.resolve().then(()=>{if(!(this.loader!==s||this.stats.aborted))return n(s,t.url)}).catch(a=>{if(!(this.loader!==s||this.stats.aborted))return s.open("GET",t.url,!0),n(s,t.url)}).then(()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,t,e)}).catch(a=>{var o;(o=this.callbacks)==null||o.onError({code:s.status,text:a.message},t,s,i)}):this.openAndSendXhr(s,t,e)}openAndSendXhr(e,t,s){e.readyState||e.open("GET",t.url,!0);const i=t.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:a}=s.loadPolicy;if(i)for(const o in i)e.setRequestHeader(o,i[o]);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=n&&$(n)?n:a,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 i=t.readyState,n=this.config;if(!s.aborted&&i>=2&&(s.loading.first===0&&(s.loading.first=Math.max(self.performance.now(),s.loading.start),n.timeout!==n.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),n.timeout=n.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.loadPolicy.maxLoadTimeMs-(s.loading.first-s.loading.start)))),i===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const l=t.status,u=t.responseType==="text"?t.responseText:null;if(l>=200&&l<300){const f=u??t.response;if(f!=null){var a,o;s.loading.end=Math.max(self.performance.now(),s.loading.first);const p=t.responseType==="arraybuffer"?f.byteLength:f.length;s.loaded=s.total=p,s.bwEstimate=s.total*8e3/(s.loading.end-s.loading.first);const y=(a=this.callbacks)==null?void 0:a.onProgress;y&&y(s,e,f,t);const v={url:t.responseURL,data:f,code:l};(o=this.callbacks)==null||o.onSuccess(v,s,e,t);return}}const h=n.loadPolicy.errorRetry,d=s.retry,g={url:e.url,data:void 0,code:l};if(Ki(h,d,!1,g))this.retry(h);else{var c;oe.error(`${l} while loading ${e.url}`),(c=this.callbacks)==null||c.onError({code:l,text:t.statusText},e,t,s)}}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(Ki(e,t,!0))this.retry(e);else{var s;oe.warn(`timeout while loading ${(s=this.context)==null?void 0:s.url}`);const i=this.callbacks;i&&(this.abortInternal(),i.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:s}=this;this.retryDelay=Xr(e,s.retry),s.retry++,oe.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${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&&Dp.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 Cp={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},Pp=ae(ae({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:jc,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:Wd,bufferController:Fg,capLevelController:Rn,errorController:zd,fpsController:Om,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:nl,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:Cp},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},wp()),{},{subtitleStreamController:Ym,subtitleTrackController:Nm,timelineController:vp,audioStreamController:wg,audioTrackController:kg,emeController:Ks,cmcdController:Cm,contentSteeringController:wm,interstitialsController:Wm});function wp(){return{cueHandler:Sp,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 kp(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=Wn(r),i=["manifest","level","frag"],n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return i.forEach(a=>{const o=`${a==="level"?"playlist":a}LoadPolicy`,c=e[o]===void 0,l=[];n.forEach(u=>{const h=`${a}Loading${u}`,d=e[h];if(d!==void 0&&c){l.push(h);const g=s[o].default;switch(e[o]={default:g},u){case"TimeOut":g.maxLoadTimeMs=d,g.maxTimeToFirstByteMs=d;break;case"MaxRetry":g.errorRetry.maxNumRetry=d,g.timeoutRetry.maxNumRetry=d;break;case"RetryDelay":g.errorRetry.retryDelayMs=d,g.timeoutRetry.retryDelayMs=d;break;case"MaxRetryTimeout":g.errorRetry.maxRetryDelayMs=d,g.timeoutRetry.maxRetryDelayMs=d;break}}}),l.length&&t.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${o}": ${ue(e[o])}`)}),ae(ae({},s),e)}function Wn(r){return r&&typeof r=="object"?Array.isArray(r)?r.map(Wn):Object.keys(r).reduce((e,t)=>(e[t]=Wn(r[t]),e),{}):r}function Op(r,e){const t=r.loader;t!==qc&&t!==jc?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),r.progressive=!1):xp()&&(r.loader=qc,r.progressive=!0,r.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}const dr=2,Mp=.1,Fp=.05,Np=100;class $p extends Xo{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(m.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.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(Np),this.mediaSource=t.mediaSource;const s=this.media=t.media;Ue(s,"playing",this.onMediaPlaying),Ue(s,"waiting",this.onMediaWaiting),Ue(s,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:s}=this;s&&(He(s,"playing",this.onMediaPlaying),He(s,"waiting",this.onMediaWaiting),He(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,i;const n=(s=this.hls)==null?void 0:s.config;if(!n)return;const a=this.media;if(!a)return;const{seeking:o}=a,c=this.seeking&&!o,l=!this.seeking&&o,u=a.paused&&!o||a.ended||a.playbackRate===0;if(this.seeking=o,e!==t){t&&(this.ended=0),this.moved=!0,o||(this.nudgeRetry=0,n.nudgeOnVideoHole&&!u&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(l||c){c&&this.stallResolved(e);return}if(u){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&a.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(m.MEDIA_ENDED,{stalled:!1}));return}if(!j.getBuffered(a).length){this.nudgeRetry=0;return}const h=j.bufferInfo(a,e,0),d=h.nextStart||0,g=this.fragmentTracker;if(o&&g&&this.hls){const D=Xc(this.hls.inFlightFragments,e),I=h.len>dr,b=!d||D||d-e>dr&&!g.getPartialFragment(e);if(I||b)return;this.moved=!1}const f=(i=this.hls)==null?void 0:i.latestLevelDetails;if(!this.moved&&this.stalled!==null&&g){if(!(h.len>0)&&!d)return;const I=Math.max(d,h.start||0)-e,A=!!(f!=null&&f.live)?f.targetduration*2:dr,x=fr(e,g);if(I>0&&(I<=A||x)){a.paused||this._trySkipBufferHole(x);return}}const p=n.detectStallWithCurrentTimeMs,y=self.performance.now(),v=this.waiting;let E=this.stalled;if(E===null)if(v>0&&y-v<p)E=this.stalled=v;else{this.stalled=y;return}const T=y-E;if(!o&&(T>=p||v)&&this.hls){var S;if(((S=this.mediaSource)==null?void 0:S.readyState)==="ended"&&!(f!=null&&f.live)&&Math.abs(e-(f?.edge||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(m.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(h),!this.media||!this.hls)return}const _=j.bufferInfo(a,e,n.maxBufferHole);this._tryFixBufferStall(_,T,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(m.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var s;const i=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(s=this.buffered.audio)!=null&&s.length&&i&&i.length>1&&e>i.end(0)){const n=j.bufferedInfo(j.timeRangesToArray(this.buffered.audio),e,0);if(n.len>1&&t>=n.start){const a=j.timeRangesToArray(i),o=j.bufferedInfo(a,t,0).bufferedIndex;if(o>-1&&o<a.length-1){const c=j.bufferedInfo(a,e,0).bufferedIndex,l=a[o].end,u=a[o+1].start;if((c===-1||c>o)&&u-l<1&&e-l<2){const h=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${l} -> ${u} buffered index: ${c}`);this.warn(h.message),this.media.currentTime+=1e-6;let d=fr(e,this.fragmentTracker);d&&"fragment"in d?d=d.fragment:d||(d=void 0);const g=j.bufferInfo(this.media,e,0);this.hls.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:R.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:h,reason:h.message,frag:d,buffer:g.len,bufferInfo:g})}}}}}_tryFixBufferStall(e,t,s){var i,n;const{fragmentTracker:a,media:o}=this,c=(i=this.hls)==null?void 0:i.config;if(!o||!a||!c)return;const l=(n=this.hls)==null?void 0:n.latestLevelDetails,u=fr(s,a);if((u||l!=null&&l.live&&s<l.fragmentStart)&&(this._trySkipBufferHole(u)||!this.media))return;const h=e.buffered,d=this.adjacentTraversal(e,s);(h&&h.length>1&&e.len>c.maxBufferHole||e.nextStart&&(e.nextStart-s<c.maxBufferHole||d))&&(t>c.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){const s=this.fragmentTracker,i=e.nextStart;if(s&&i){const n=s.getFragAtPos(t,G.MAIN),a=s.getFragAtPos(i,G.MAIN);if(n&&a)return a.sn-n.sn<2}return!1}_reportStall(e){const{hls:t,media:s,stallReported:i,stalled:n}=this;if(!i&&n!==null&&s&&t){this.stallReported=!0;const a=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${ue(e)})`);this.warn(a.message),t.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:R.BUFFER_STALLED_ERROR,fatal:!1,error:a,buffer:e.len,bufferInfo:e,stalled:{start:n}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:s,media:i}=this,n=(t=this.hls)==null?void 0:t.config;if(!i||!s||!n)return 0;const a=i.currentTime,o=j.bufferInfo(i,a,0),c=a<o.start?o.start:o.nextStart;if(c&&this.hls){const u=o.len<=n.maxBufferHole,h=o.len>0&&o.len<1&&i.readyState<3,d=c-a;if(d>0&&(u||h)){if(d>n.maxBufferHole){let f=!1;if(a===0){const p=s.getAppendedFrag(0,G.MAIN);p&&c<p.end&&(f=!0)}if(!f&&e){var l;if(!((l=this.hls.loadLevelObj)!=null&&l.details)||Xc(this.hls.inFlightFragments,c))return 0;let y=!1,v=e.end;for(;v<c;){const E=fr(v,s);if(E)v+=E.duration;else{y=!0;break}}if(y)return 0}}const g=Math.max(c+Fp,a+Mp);if(this.warn(`skipping hole, adjusting currentTime from ${a} to ${g}`),this.moved=!0,i.currentTime=g,!(e!=null&&e.gap)){const f=new Error(`fragment loaded with buffer holes, seeking from ${a} to ${g}`),p={type:H.MEDIA_ERROR,details:R.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:f,reason:f.message,buffer:o.len,bufferInfo:o};e&&("fragment"in e?p.part=e:p.frag=e),this.hls.trigger(m.ERROR,p)}return g}}return 0}_tryNudgeBuffer(e){const{hls:t,media:s,nudgeRetry:i}=this,n=t?.config;if(!s||!n)return 0;const a=s.currentTime;if(this.nudgeRetry++,i<n.nudgeMaxRetry){const o=a+(i+1)*n.nudgeOffset,c=new Error(`Nudging 'currentTime' from ${a} to ${o}`);this.warn(c.message),s.currentTime=o,t.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:R.BUFFER_NUDGE_ON_STALL,error:c,fatal:!1,buffer:e.len,bufferInfo:e})}else{const o=new Error(`Playhead still not moving while enough data buffered @${a} after ${n.nudgeMaxRetry} nudges`);this.error(o.message),t.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:R.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:e.len,bufferInfo:e})}}}function Xc(r,e){const t=zc(r.main);if(t&&t.start<=e)return t;const s=zc(r.audio);return s&&s.start<=e?s:null}function zc(r){if(!r)return null;switch(r.state){case P.IDLE:case P.STOPPED:case P.ENDED:case P.ERROR:return null}return r.frag}function fr(r,e){return e.getAppendedFrag(r,G.MAIN)||e.getPartialFragment(r)}const Bp=.25;function Yn(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function qn(r,e,t,s,i){let n=new r(e,t,"");try{n.value=s,i&&(n.type=i)}catch{n=new r(e,t,ue(i?ae({type:i},s):s))}return n}const gr=(()=>{const r=Yn();try{r&&new r(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class Up{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(m.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(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(m.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(m.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&&Vs(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 Ic(s,this.media),s}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:s,enableID3MetadataCues:i}=this.hls.config;if(!s&&!i)return;const{samples:n}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const a=Yn();if(a)for(let o=0;o<n.length;o++){const c=n[o].type;if(c===ze.emsg&&!s||!i)continue;const l=Bl(n[o].data),u=n[o].pts;let h=u+n[o].duration;h>gr&&(h=gr),h-u<=0&&(h=u+Bp);for(let g=0;g<l.length;g++){const f=l[g];if(!Ul(f)){this.updateId3CueEnds(u,c);const p=qn(a,u,h,f,c);p&&this.id3Track.addCue(p)}}}}updateId3CueEnds(e,t){var s;const i=(s=this.id3Track)==null?void 0:s.cues;if(i)for(let n=i.length;n--;){const a=i[n];a.type===t&&a.startTime<e&&a.endTime===gr&&(a.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:s,type:i}){const{id3Track:n,hls:a}=this;if(!a)return;const{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:c}}=a;if(n&&(o||c)){let l;i==="audio"?l=u=>u.type===ze.audioId3&&c:i==="video"?l=u=>u.type===ze.emsg&&o:l=u=>u.type===ze.audioId3&&c||u.type===ze.emsg&&o,kn(n,t,s,l)}}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:i,enableDateRangeMetadataCues:n,interstitialsController:a}=this.hls.config;if(!n)return;const o=Yn();if(s&&i&&!a){const{fragmentStart:p,fragmentEnd:y}=e;let v=this.assetCue;v?(v.startTime=p,v.endTime=y):o&&(v=this.assetCue=qn(o,p,y,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),v&&(v.id=s,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(v),v.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:c}=this,{dateRanges:l}=e,u=Object.keys(l);let h=this.dateRangeCuesAppended;if(c&&t){var d;if((d=c.cues)!=null&&d.length){const p=Object.keys(h).filter(y=>!u.includes(y));for(let y=p.length;y--;){var g;const v=p[y],E=(g=h[v])==null?void 0:g.cues;delete h[v],E&&Object.keys(E).forEach(T=>{const S=E[T];if(S){S.removeEventListener("enter",this.onEventCueEnter);try{c.removeCue(S)}catch{}}})}}else h=this.dateRangeCuesAppended={}}const f=e.fragments[e.fragments.length-1];if(!(u.length===0||!$(f?.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let p=0;p<u.length;p++){const y=u[p],v=l[y],E=v.startTime,T=h[y],S=T?.cues||{};let _=T?.durationKnown||!1,D=gr;const{duration:I,endDate:b}=v;if(b&&I!==null)D=E+I,_=!0;else if(v.endOnNext&&!_){const x=u.reduce((C,M)=>{if(M!==v.id){const K=l[M];if(K.class===v.class&&K.startDate>v.startDate&&(!C||v.startDate<C.startDate))return K}return C},null);x&&(D=x.startTime,_=!0)}const A=Object.keys(v.attr);for(let x=0;x<A.length;x++){const C=A[x];if(!uf(C))continue;const M=S[C];if(M)_&&!(T!=null&&T.durationKnown)?M.endTime=D:Math.abs(M.startTime-E)>.01&&(M.startTime=E,M.endTime=D);else if(o){let K=v.attr[C];hf(C)&&(K=co(K));const N=qn(o,E,D,{key:C,data:K},ze.dateRange);N&&(N.id=y,this.id3Track.addCue(N),S[C]=N,a&&(C==="X-ASSET-LIST"||C==="X-ASSET-URL")&&N.addEventListener("enter",this.onEventCueEnter))}}h[y]={cues:S,dateRange:v,durationKnown:_}}}}}class Gp{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 i=this.computeLatency();if(i===null)return;this._latency=i;const{lowLatencyMode:n,maxLiveSyncPlaybackRate:a}=this.config;if(!n||a===1||!s.live)return;const o=this.targetLatency;if(o===null)return;const c=i-o,l=Math.min(this.maxLatency,o+s.targetduration);if(c<l&&c>.05&&this.forwardBufferLength>1){const h=Math.min(2,Math.max(1,a)),d=Math.round(2/(1+Math.exp(-.75*c-this.edgeStalled))*20)/20,g=Math.min(h,Math.max(1,d));this.changeMediaPlaybackRate(t,g)}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:i}=e,{liveSyncDuration:n,liveSyncDurationCount:a,lowLatencyMode:o}=this.config,c=this.hls.userConfig;let l=o&&s||t;(this._targetLatencyUpdated||c.liveSyncDuration||c.liveSyncDurationCount||l===0)&&(l=n!==void 0?n:a*i);const u=i;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,u)}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 i=s.edge,n=e-t-this.edgeStalled,a=i-s.totalduration,o=i-(this.config.lowLatencyMode&&s.partTarget||s.targetduration);return Math.min(Math.max(a,n),o)}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(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(m.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(m.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===R.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,i;e.playbackRate!==t&&((s=this.hls)==null||s.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(i=this.targetLatency)==null?void 0:i.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 Kp extends _n{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(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this),e.on(m.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this),e.off(m.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,i=[],n={},a={};let o=!1,c=!1,l=!1;t.levels.forEach(u=>{const h=u.attrs;let{audioCodec:d,videoCodec:g}=u;d&&(u.audioCodec=d=Fi(d,s)||void 0),g&&(g=u.videoCodec=Ld(g));const{width:f,height:p,unknownCodecs:y}=u,v=y?.length||0;if(o||(o=!!(f&&p)),c||(c=!!g),l||(l=!!d),v||d&&!this.isAudioSupported(d)||g&&!this.isVideoSupported(g)){this.log(`Some or all CODECS not supported "${h.CODECS}"`);return}const{CODECS:E,"FRAME-RATE":T,"HDCP-LEVEL":S,"PATHWAY-ID":_,RESOLUTION:D,"VIDEO-RANGE":I}=h,A=`${`${_||"."}-`}${u.bitrate}-${D}-${T}-${E}-${I}-${S}`;if(n[A])if(n[A].uri!==u.url&&!u.attrs["PATHWAY-ID"]){const x=a[A]+=1;u.attrs["PATHWAY-ID"]=new Array(x+1).join(".");const C=this.createLevel(u);n[A]=C,i.push(C)}else n[A].addGroupId("audio",h.AUDIO),n[A].addGroupId("text",h.SUBTITLES);else{const x=this.createLevel(u);n[A]=x,a[A]=1,i.push(x)}}),this.filterAndSortMediaOptions(i,t,o,c,l)}createLevel(e){const t=new ii(e),s=e.supplemental;if(s!=null&&s.videoCodec&&!this.isVideoSupported(s.videoCodec)){const i=new Error(`SUPPLEMENTAL-CODECS not supported "${s.videoCodec}"`);this.log(i.message),t.supportedResult=Do(i,[])}return t}isAudioSupported(e){return ti(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return ti(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,s,i,n){var a;let o=[],c=[],l=e;const u=((a=t.stats)==null?void 0:a.parsing)||{};if((s||i)&&n&&(l=l.filter(({videoCodec:E,videoRange:T,width:S,height:_})=>(!!E||!!(S&&_))&&Fd(T))),l.length===0){Promise.resolve().then(()=>{if(this.hls){let E="no level with compatible codecs found in manifest",T=E;t.levels.length&&(T=`one or more CODECS in variant not supported: ${ue(t.levels.map(_=>_.attrs.CODECS).filter((_,D,I)=>I.indexOf(_)===D))}`,this.warn(T),E+=` (${T})`);const S=new Error(E);this.hls.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:R.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:S,reason:T})}}),u.end=performance.now();return}t.audioTracks&&(o=t.audioTracks.filter(E=>!E.audioCodec||this.isAudioSupported(E.audioCodec)),Qc(o)),t.subtitles&&(c=t.subtitles,Qc(c));const h=l.slice(0);l.sort((E,T)=>{if(E.attrs["HDCP-LEVEL"]!==T.attrs["HDCP-LEVEL"])return(E.attrs["HDCP-LEVEL"]||"")>(T.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&E.height!==T.height)return E.height-T.height;if(E.frameRate!==T.frameRate)return E.frameRate-T.frameRate;if(E.videoRange!==T.videoRange)return $i.indexOf(E.videoRange)-$i.indexOf(T.videoRange);if(E.videoCodec!==T.videoCodec){const S=Io(E.videoCodec),_=Io(T.videoCodec);if(S!==_)return _-S}if(E.uri===T.uri&&E.codecSet!==T.codecSet){const S=Mi(E.codecSet),_=Mi(T.codecSet);if(S!==_)return _-S}return E.averageBitrate!==T.averageBitrate?E.averageBitrate-T.averageBitrate:0});let d=h[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==h.length)){for(let E=0;E<h.length;E++)if(h[E].pathwayId===l[0].pathwayId){d=h[E];break}}this._levels=l;for(let E=0;E<l.length;E++)if(l[E]===d){var g;this._firstLevel=E;const T=d.bitrate,S=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${T}`),((g=this.hls.userConfig)==null?void 0:g.abrEwmaDefaultEstimate)===void 0){const _=Math.min(T,this.hls.config.abrEwmaDefaultEstimateMax);_>S&&S===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=_)}break}const f=n&&!i,p=this.hls.config,y=!!(p.audioStreamController&&p.audioTrackController),v={levels:l,audioTracks:o,subtitleTracks:c,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:i,altAudio:y&&!f&&o.some(E=>!!E.url)};u.end=performance.now(),this.hls.trigger(m.MANIFEST_PARSED,v)}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 u=new Error("invalid level idx"),h=e<0;if(this.hls.trigger(m.ERROR,{type:H.OTHER_ERROR,details:R.LEVEL_SWITCH_ERROR,level:e,fatal:h,error:u,reason:u.message}),h)return;e=Math.min(e,t.length-1)}const s=this.currentLevelIndex,i=this.currentLevel,n=i?i.attrs["PATHWAY-ID"]:void 0,a=t[e],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,s===e&&i&&n===o)return;this.log(`Switching to level ${e} (${a.height?a.height+"p ":""}${a.videoRange?a.videoRange+" ":""}${a.codecSet?a.codecSet+" ":""}@${a.bitrate})${o?" with Pathway "+o:""} from level ${s}${n?" with Pathway "+n:""}`);const c={level:e,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger(m.LEVEL_SWITCHING,c);const l=a.details;if(!l||l.live){const u=this.switchParams(a.uri,i?.details,l);this.loadPlaylist(u)}}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(i=>t.indexOf(i)!==-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===ee.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===G.MAIN){const s=t.elementaryStreams;if(!Object.keys(s).some(n=>!!s[n]))return;const i=this._levels[t.level];i!=null&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(e,t){var s;const{level:i,details:n}=t,a=t.levelInfo;if(!a){var o;this.warn(`Invalid level index ${i}`),(o=t.deliveryDirectives)!=null&&o.skip&&(n.deltaUpdateFailed=!0);return}if(a===this.currentLevel||t.withoutMultiVariant){a.fragmentError===0&&(a.loadError=0);let c=a.details;c===t.details&&c.advanced&&(c=void 0),this.playlistLoaded(i,t,c)}else(s=t.deliveryDirectives)!=null&&s.skip&&(n.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),i=this.currentLevelIndex,n=e.attrs["PATHWAY-ID"],a=e.details,o=a?.age;this.log(`Loading level index ${i}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${n?" Pathway "+n:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${s}`),this.hls.trigger(m.LEVEL_LOADING,{url:s,level:i,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((n,a)=>a!==e?!0:(this.steering&&this.steering.removeLevel(n),n===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,n.details&&n.details.fragments.forEach(o=>o.level=-1)),!1));Il(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 i=s.length-1;this._firstLevel=Math.min(this._firstLevel,i),this._startLevel&&(this._startLevel=Math.min(this._startLevel,i)),this.hls.trigger(m.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(m.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}}function Qc(r){const e={};r.forEach(t=>{const s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++})}function Jc(){return self.SourceBuffer||self.WebKitSourceBuffer}function Zc(){if(!Zt())return!1;const e=Jc();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function Vp(){if(!Zc())return!1;const r=Zt();return typeof r?.isTypeSupported=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>r.isTypeSupported(si(e,"video")))||["mp4a.40.2","fLaC"].some(e=>r.isTypeSupported(si(e,"audio"))))}function Hp(){var r;const e=Jc();return typeof(e==null||(r=e.prototype)==null?void 0:r.changeType)=="function"}const Wp=100;class Yp extends cn{constructor(e,t,s){super(e,t,s,"stream-controller",G.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 i=this.media,n=i?i.currentTime:null;if(n===null||!$(n)||(this.log(`Media seeked to ${n.toFixed(3)}`),!this.getBufferedFrag(n)))return;const a=this.getFwdBufferInfoAtPos(i,n,G.MAIN,0);if(a===null||a.len===0){this.warn(`Main forward buffer length at ${n} on "seeked" event ${a?a.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.LEVEL_LOADING,this.onLevelLoading,this),e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(m.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(m.BUFFER_CREATED,this.onBufferCreated,this),e.on(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(m.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(m.BUFFER_CREATED,this.onBufferCreated,this),e.off(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(m.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:i}=this;if(this.stopLoad(),this.setInterval(Wp),this.level=-1,!this.startFragRequested){let n=i.startLevel;n===-1&&(i.config.testBandwidth&&this.levels.length>1?(n=0,this.bitrateTest=!0):n=i.firstAutoLevel),i.nextLoadLevel=n,this.level=i.loadLevel,this._hasEnoughToStart=!!t}s>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s),this.state=P.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=P.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case P.WAITING_LEVEL:{const{levels:e,level:t}=this,s=e?.[t],i=s?.details;if(i&&(!i.live||this.levelLastLoaded===s&&!this.waitForLive(s))){if(this.waitForCdnTuneIn(i))break;this.state=P.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=P.IDLE;break}break}case P.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===P.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:i}=this;if(t===null||!i&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const n=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(s!=null&&s[n]))return;const a=s[n],o=this.getMainFwdBufferInfo();if(o===null)return;const c=this.getLevelDetails();if(c&&this._streamEnded(o,c)){const p={};this.altAudio===2&&(p.type="video"),this.hls.trigger(m.BUFFER_EOS,p),this.state=P.ENDED;return}if(!this.buffering)return;e.loadLevel!==n&&e.manualLevel===-1&&this.log(`Adapting to level ${n} from level ${this.level}`),this.level=e.nextLoadLevel=n;const l=a.details;if(!l||this.state===P.WAITING_LEVEL||this.waitForLive(a)){this.level=n,this.state=P.WAITING_LEVEL,this.startFragRequested=!1;return}const u=o.len,h=this.getMaxBufferLength(a.maxBitrate);if(u>=h)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const d=this.backtrackFragment?this.backtrackFragment.start:o.end;let g=this.getNextFragment(d,l);if(this.couldBacktrack&&!this.fragPrevious&&g&&xe(g)&&this.fragmentTracker.getState(g)!==Re.OK){var f;const y=((f=this.backtrackFragment)!=null?f:g).sn-l.startSN,v=l.fragments[y-1];v&&g.cc===v.cc&&(g=v,this.fragmentTracker.removeFragment(v))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(g&&this.isLoopLoading(g,d)){if(!g.gap){const y=this.audioOnly&&!this.altAudio?ce.AUDIO:ce.VIDEO,v=(y===ce.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;v&&this.afterBufferFlushed(v,y,G.MAIN)}g=this.getNextFragmentLoopLoading(g,l,o,G.MAIN,h)}g&&(g.initSegment&&!g.initSegment.data&&!this.bitrateTest&&(g=g.initSegment),this.loadFragment(g,a,d))}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);i===Re.NOT_LOADED||i===Re.PARTIAL?xe(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,G.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 i=this.getAppendedFrag(t.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.start-1);const n=this.getLevelDetails();if(n!=null&&n.live){const o=this.getMainFwdBufferInfo();if(!o||o.len<n.targetduration*2)return}if(!t.paused&&e){const o=this.hls.nextLoadLevel,c=e[o],l=this.fragLastKbps;l&&this.fragCurrent?s=this.fragCurrent.duration*c.maxBitrate/(1e3*l)+1:s=0}else s=0;const a=this.getBufferedFrag(t.currentTime+s);if(a){const o=this.followingBufferedFrag(a);if(o){this.abortCurrentFrag();const c=o.maxStartPTS?o.maxStartPTS:o.start,l=o.duration,u=Math.max(a.end,c+Math.min(Math.max(l-this.config.maxFragLookUpTolerance,l*(this.couldBacktrack?.5:.125)),l*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(u,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 P.KEY_LOADING:case P.FRAG_LOADING:case P.FRAG_LOADING_WAITING_RETRY:case P.PARSING:case P.PARSED:this.state=P.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;Ue(s,"playing",this.onMediaPlaying),Ue(s,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:s}=this;s&&(He(s,"playing",this.onMediaPlaying),He(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(m.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,i=!1;for(let n=0;n<t.levels.length;n++){const a=t.levels[n].audioCodec;a&&(s=s||a.indexOf("mp4a.40.2")!==-1,i=i||a.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=s&&i&&!Hp(),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!==P.IDLE)return;const i=t.levelInfo;(!i.details||i.details.live&&(this.levelLastLoaded!==i||i.details.expired)||this.waitForCdnTuneIn(i.details))&&(this.state=P.WAITING_LEVEL)}onLevelLoaded(e,t){var s;const{levels:i,startFragRequested:n}=this,a=t.level,o=t.details,c=o.totalduration;if(!i){this.warn(`Levels were reset while loading level ${a}`);return}this.log(`Level ${a} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${c}`);const l=t.levelInfo,u=this.fragCurrent;u&&(this.state===P.FRAG_LOADING||this.state===P.FRAG_LOADING_WAITING_RETRY)&&u.level!==t.level&&u.loader&&this.abortCurrentFrag();let h=0;if(o.live||(s=l.details)!=null&&s.live){var d;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;h=this.alignPlaylists(o,l.details,(d=this.levelLastLoaded)==null?void 0:d.details)}if(l.details=o,this.levelLastLoaded=l,n||this.setStartPosition(o,h),this.hls.trigger(m.LEVEL_UPDATED,{details:o,level:a}),this.state===P.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=P.IDLE}n&&o.live&&this.synchronizeToLiveEdge(o),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:s}=this;if(!s)return;const i=this.hls.liveSyncPosition,n=this.getLoadPosition(),a=e.fragmentStart,o=e.edge,c=n>=a-t.maxFragLookUpTolerance&&n<=o;if(i!==null&&s.duration>i&&(n<i||!c)){const u=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!c&&s.readyState<4||n<o-u)&&(this._hasEnoughToStart||(this.nextLoadPosition=i),s.readyState))if(this.warn(`Playback: ${n.toFixed(3)} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${i.toFixed(3)}`),this.config.liveSyncMode==="buffered"){var l;const h=j.bufferInfo(s,i,0);if(!((l=h.buffered)!=null&&l.length)){s.currentTime=i;return}if(h.start<=n){s.currentTime=i;return}const{nextStart:g}=j.bufferedInfo(h.buffered,n,0);g&&(s.currentTime=g)}else s.currentTime=i}}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:i,payload:n}=e,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}const o=a[s.level];if(!o){this.warn(`Level ${s.level} not found on progress`);return}const c=o.details;if(!c){this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),this.fragmentTracker.removeFragment(s);return}const l=o.videoCodec,u=c.PTSKnown||!c.live,h=(t=s.initSegment)==null?void 0:t.data,d=this._getAudioCodec(o),g=this.transmuxer=this.transmuxer||new ic(this.hls,G.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=i?i.index:-1,p=f!==-1,y=new Jr(s.level,s.sn,s.stats.chunkCount,n.byteLength,f,p),v=this.initPTS[s.cc];g.push(n,h,d,l,s,i,c.totalduration,u,y,v)}onAudioTrackSwitching(e,t){const s=this.hls,i=this.altAudio!==0;if(Ui(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 a=this.fragCurrent;a&&(this.log("Switching to main audio track, cancel main fragment load"),a.abortRequests(),this.fragmentTracker.removeFragment(a)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(i){this.altAudio=0,this.fragmentTracker.removeAllFragments(),s.once(m.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(m.AUDIO_TRACK_SWITCHED,t)}),s.trigger(m.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}s.trigger(m.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const s=Ui(t.url,this.hls);if(s){const i=this.videoBuffer;i&&this.mediaBuffer!==i&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=i)}this.altAudio=s?2:0,this.tick()}onBufferCreated(e,t){const s=t.tracks;let i,n,a=!1;for(const o in s){const c=s[o];if(c.id==="main"){if(n=o,i=c,o==="video"){const l=s[o];l&&(this.videoBuffer=l.buffer)}}else a=!0}a&&i?(this.log(`Alternate track found, use ${n}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:s,part:i}=t,n=s.type===G.MAIN;if(n){if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),this.state===P.PARSED&&(this.state=P.IDLE);return}const o=i?i.stats:s.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),xe(s)&&(this.fragPrevious=s),this.fragBufferedComplete(s,i)}const a=this.media;a&&(!this._hasEnoughToStart&&j.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),n&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var s;if(t.fatal){this.state=P.ERROR;return}switch(t.details){case R.FRAG_GAP:case R.FRAG_PARSING_ERROR:case R.FRAG_DECRYPT_ERROR:case R.FRAG_LOAD_ERROR:case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_ERROR:case R.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(G.MAIN,t);break;case R.LEVEL_LOAD_ERROR:case R.LEVEL_LOAD_TIMEOUT:case R.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===P.WAITING_LEVEL&&((s=t.context)==null?void 0:s.type)===ee.LEVEL&&(this.state=P.IDLE);break;case R.BUFFER_ADD_CODEC_ERROR:case R.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case R.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 R.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=P.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==ce.AUDIO||!this.altAudio){const s=(t===ce.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;s&&(this.afterBufferFlushed(s,t,G.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 i=this.timelineOffset;i&&s&&(s+=i);const n=this.getLevelDetails(),a=j.getBuffered(e),o=a.length?a.start(0):0,c=o-s,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||c>0&&(c<l||this.loadingParts&&c<2*(n?.partTarget||0)))&&(this.log(`adjusting start position by ${c} to match buffer start`),s+=c,this.startPosition=s),t<s&&(this.log(`seek to target start position ${s} from current time ${t} buffer start ${o}`),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:i}=this,n=s?.frag;if(!n||this.fragContextChanged(n))return;t.fragmentError=0,this.state=P.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const a=n.stats;a.parsing.start=a.parsing.end=a.buffering.start=a.buffering.end=self.performance.now(),i.trigger(m.FRAG_LOADED,s),n.bitrateTest=!1}).catch(s=>{this.state===P.STOPPED||this.state===P.ERROR||(this.warn(s),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:s}=this,{remuxResult:i,chunkMeta:n}=e,a=this.getCurrentContext(n);if(!a){this.resetWhenMissingContext(n);return}const{frag:o,part:c,level:l}=a,{video:u,text:h,id3:d,initSegment:g}=i,{details:f}=l,p=this.altAudio?void 0:i.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=P.PARSING,g){const y=g.tracks;if(y){const S=o.initSegment||o;if(this.unhandledEncryptionError(g,o))return;this._bufferInitSegment(l,y,S,n),s.trigger(m.FRAG_PARSING_INIT_SEGMENT,{frag:S,id:t,tracks:y})}const v=g.initPTS,E=g.timescale,T=this.initPTS[o.cc];if($(v)&&(!T||T.baseTime!==v||T.timescale!==E)){const S=g.trackId;this.initPTS[o.cc]={baseTime:v,timescale:E,trackId:S},s.trigger(m.INIT_PTS_FOUND,{frag:o,id:t,initPTS:v,timescale:E,trackId:S})}}if(u&&f){p&&u.type==="audiovideo"&&this.logMuxedErr(o);const y=f.fragments[o.sn-1-f.startSN],v=o.sn===f.startSN,E=!y||o.cc>y.cc;if(i.independent!==!1){const{startPTS:T,endPTS:S,startDTS:_,endDTS:D}=u;if(c)c.elementaryStreams[u.type]={startPTS:T,endPTS:S,startDTS:_,endDTS:D};else if(u.firstKeyFrame&&u.independent&&n.id===1&&!E&&(this.couldBacktrack=!0),u.dropped&&u.independent){const I=this.getMainFwdBufferInfo(),b=(I?I.end:this.getLoadPosition())+this.config.maxBufferHole,A=u.firstKeyFramePTS?u.firstKeyFramePTS:T;if(!v&&b<A-this.config.maxBufferHole&&!E){this.backtrack(o);return}else E&&(o.gap=!0);o.setElementaryStreamInfo(u.type,o.start,S,o.start,D,!0)}else v&&T-(f.appliedTimelineOffset||0)>dr&&(o.gap=!0);o.setElementaryStreamInfo(u.type,T,S,_,D),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(u,o,c,n,v||E)}else if(v||E)o.gap=!0;else{this.backtrack(o);return}}if(p){const{startPTS:y,endPTS:v,startDTS:E,endDTS:T}=p;c&&(c.elementaryStreams[ce.AUDIO]={startPTS:y,endPTS:v,startDTS:E,endDTS:T}),o.setElementaryStreamInfo(ce.AUDIO,y,v,E,T),this.bufferFragmentData(p,o,c,n)}if(f&&d!=null&&d.samples.length){const y={id:t,frag:o,details:f,samples:d.samples};s.trigger(m.FRAG_PARSING_METADATA,y)}if(f&&h){const y={id:t,frag:o,details:f,samples:h.samples};s.trigger(m.FRAG_PARSING_USERDATA,y)}}logMuxedErr(e){this.warn(`${xe(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,s,i){if(this.state!==P.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(s));const{audio:n,video:a,audiovideo:o}=t;if(n){const l=e.audioCodec;let u=Ni(n.codec,l);u==="mp4a"&&(u="mp4a.40.5");const h=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){u&&(u.indexOf("mp4a.40.5")!==-1?u="mp4a.40.2":u="mp4a.40.5");const d=n.metadata;d&&"channelCount"in d&&(d.channelCount||1)!==1&&h.indexOf("firefox")===-1&&(u="mp4a.40.5")}u&&u.indexOf("mp4a.40.5")!==-1&&h.indexOf("android")!==-1&&n.container!=="audio/mpeg"&&(u="mp4a.40.2",this.log(`Android: force audio codec to ${u}`)),l&&l!==u&&this.log(`Swapping manifest audio codec "${l}" for "${u}"`),n.levelCodec=u,n.id=G.MAIN,this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${u||""}/${l||""}/${n.codec}]`),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=G.MAIN;const l=a.codec;if(l?.length===4)switch(l){case"hvc1":case"hev1":a.codec="hvc1.1.6.L120.90";break;case"av01":a.codec="av01.0.04M.08";break;case"avc1":a.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||""}/${l}]${a.codec!==l?" parsed-corrected="+a.codec:""}${a.supplemental?" supplemental="+a.supplemental:""}`),delete t.audiovideo}o&&(this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),delete t.video,delete t.audio);const c=Object.keys(t);if(c.length){if(this.hls.trigger(m.BUFFER_CODECS,t),!this.hls)return;c.forEach(l=>{const h=t[l].initSegment;h!=null&&h.byteLength&&this.hls.trigger(m.BUFFER_APPENDING,{type:l,data:h,frag:s,part:null,chunkMeta:i,parent:s.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,G.MAIN)}get maxBufferLength(){const{levels:e,level:t}=this,s=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=P.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const s=e.currentTime;if(j.isBuffered(e,s)?t=this.getAppendedFrag(s):j.isBuffered(e,s+.1)&&(t=this.getAppendedFrag(s+.1)),t){this.backtrackFragment=null;const i=this.fragPlaying,n=t.level;(!i||t.sn!==i.sn||i.level!==n)&&(this.fragPlaying=t,this.hls.trigger(m.FRAG_CHANGED,{frag:t}),(!i||i.level!==n)&&this.hls.trigger(m.LEVEL_SWITCHED,{level:n}))}}}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 $(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if($(t)){const s=this.getLevelDetails(),i=this.currentFrag||(s?gs(null,s.fragments,t):null);if(i){const n=i.programDateTime;if(n!==null){const a=n+(t-i.start)*1e3;return new Date(a)}}}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 qp extends rt{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 i=this.keyIdToKeyInfo[s].loader;if(i){var t;if(e&&e!==((t=i.context)==null?void 0:t.frag.type))return;i.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=R.KEY_LOAD_ERROR,s,i,n){return new Ft({type:H.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:n,error:s,networkDetails:i})}loadClear(e,t,s){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let i=0,n=t.length;i<n;i++){const a=t[i];if(e.cc<=a.cc&&(!xe(e)||!xe(a)||e.sn<a.sn)||!s&&i==n-1)return this.emeController.selectKeySystemFormat(a).then(o=>{if(!this.emeController)return;a.setKeyFormat(o);const c=qi(o);if(c)return this.emeController.getKeySystemAccess([c])})}if(this.config.requireKeySystemAccessOnStart){const i=ri(this.config);if(i.length)return this.emeController.getKeySystemAccess(i)}}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,i;t&&e.setKeyFormat(t);const n=e.decryptdata;if(!n){const l=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,R.KEY_LOAD_ERROR,l))}const a=n.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,R.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));const o=jn(n);let c=this.keyIdToKeyInfo[o];if((s=c)!=null&&s.decryptdata.key)return n.key=c.decryptdata.key,Promise.resolve({frag:e,keyInfo:c});if(this.emeController&&(i=c)!=null&&i.keyLoadPromise)switch(this.emeController.getKeyStatus(c.decryptdata)){case"usable":case"usable-in-future":return c.keyLoadPromise.then(u=>{const{keyInfo:h}=u;return n.key=h.decryptdata.key,{frag:e,keyInfo:h}})}switch(this.log(`${this.keyIdToKeyInfo[o]?"Rel":"L"}oading${n.keyId?" keyId: "+we(n.keyId):""} URI: ${n.uri} from ${e.type} ${e.level}`),c=this.keyIdToKeyInfo[o]={decryptdata:n,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},n.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return n.keyFormat==="identity"?this.loadKeyHTTP(c,e):this.loadKeyEME(c,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(c,e);default:return Promise.reject(this.createKeyLoadError(e,R.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${n.method}"`)))}}loadKeyEME(e,t){const s={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var i;if(!e.decryptdata.keyId&&(i=t.initSegment)!=null&&i.data){const a=gd(t.initSegment.data);if(a.length){let o=a[0];o.some(c=>c!==0)?(this.log(`Using keyId found in init segment ${we(o)}`),ts.setKeyIdForUri(e.decryptdata.uri,o)):(o=ts.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${we(o)}`)),e.decryptdata.keyId=o}}if(!e.decryptdata.keyId&&!xe(t))return Promise.resolve(s);const n=this.emeController.loadKey(s);return(e.keyLoadPromise=n.then(a=>(e.mediaKeySessionContext=a,s))).catch(a=>{throw e.keyLoadPromise=null,"data"in a&&(a.data.frag=t),a})}return Promise.resolve(s)}loadKeyHTTP(e,t){const s=this.config,i=s.loader,n=new i(s);return t.keyLoader=e.loader=n,e.keyLoadPromise=new Promise((a,o)=>{const c={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},l=s.keyLoadPolicy.default,u={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(d,g,f,p)=>{const{frag:y,keyInfo:v}=f,E=jn(v.decryptdata);if(!y.decryptdata||v!==this.keyIdToKeyInfo[E])return o(this.createKeyLoadError(y,R.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),p));v.decryptdata.key=y.decryptdata.key=new Uint8Array(d.data),y.keyLoader=null,v.loader=null,a({frag:y,keyInfo:v})},onError:(d,g,f,p)=>{this.resetLoader(g),o(this.createKeyLoadError(t,R.KEY_LOAD_ERROR,new Error(`HTTP Error ${d.code} loading key ${d.text}`),f,ae({url:c.url,data:void 0},d)))},onTimeout:(d,g,f)=>{this.resetLoader(g),o(this.createKeyLoadError(t,R.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),f))},onAbort:(d,g,f)=>{this.resetLoader(g),o(this.createKeyLoadError(t,R.INTERNAL_ABORTED,new Error("key loading aborted"),f))}};n.load(c,u,h)})}resetLoader(e){const{frag:t,keyInfo:s,url:i}=e,n=s.loader;t.keyLoader===n&&(t.keyLoader=null,s.loader=null);const a=jn(s.decryptdata)||i;delete this.keyIdToKeyInfo[a],n&&n.destroy()}}function jn(r){if(r.keyFormat!==Oe.FAIRPLAY){const e=r.keyId;if(e)return we(e)}return r.uri}function eu(r){const{type:e}=r;switch(e){case ee.AUDIO_TRACK:return G.AUDIO;case ee.SUBTITLE_TRACK:return G.SUBTITLE;default:return G.MAIN}}function Xn(r,e){let t=r.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class jp{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(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.LEVEL_LOADING,this.onLevelLoading,this),e.on(m.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(m.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.LEVEL_LOADING,this.onLevelLoading,this),e.off(m.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(m.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,s=t.pLoader,i=t.loader,n=s||i,a=new n(t);return this.loaders[e.type]=a,a}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:ee.MANIFEST,url:s,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:s,level:i,pathwayId:n,url:a,deliveryDirectives:o,levelInfo:c}=t;this.load({id:s,level:i,pathwayId:n,responseType:"text",type:ee.LEVEL,url:a,deliveryDirectives:o,levelOrTrack:c})}onAudioTrackLoading(e,t){const{id:s,groupId:i,url:n,deliveryDirectives:a,track:o}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:ee.AUDIO_TRACK,url:n,deliveryDirectives:a,levelOrTrack:o})}onSubtitleTrackLoading(e,t){const{id:s,groupId:i,url:n,deliveryDirectives:a,track:o}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:ee.SUBTITLE_TRACK,url:n,deliveryDirectives:a,levelOrTrack:o})}onLevelsUpdated(e,t){const s=this.loaders[ee.LEVEL];if(s){const i=s.context;i&&!t.levels.some(n=>n===i.levelOrTrack)&&(s.abort(),delete this.loaders[ee.LEVEL])}}load(e){var t;const s=this.hls.config;let i=this.getInternalLoader(e);if(i){const l=this.hls.logger,u=i.context;if(u&&u.levelOrTrack===e.levelOrTrack&&(u.url===e.url||u.deliveryDirectives&&!e.deliveryDirectives)){u.url===e.url?l.log(`[playlist-loader]: ignore ${e.url} ongoing request`):l.log(`[playlist-loader]: ignore ${e.url} in favor of ${u.url}`);return}l.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),i.abort()}let n;if(e.type===ee.MANIFEST?n=s.manifestLoadPolicy.default:n=le({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),i=this.createInternalLoader(e),$((t=e.deliveryDirectives)==null?void 0:t.part)){let l;if(e.type===ee.LEVEL&&e.level!==null?l=this.hls.levels[e.level].details:e.type===ee.AUDIO_TRACK&&e.id!==null?l=this.hls.audioTracks[e.id].details:e.type===ee.SUBTITLE_TRACK&&e.id!==null&&(l=this.hls.subtitleTracks[e.id].details),l){const u=l.partTarget,h=l.targetduration;if(u&&h){const d=Math.max(u*3,h*.8)*1e3;n=le({},n,{maxTimeToFirstByteMs:Math.min(d,n.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(d,n.maxTimeToFirstByteMs)})}}}const a=n.errorRetry||n.timeoutRetry||{},o={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},c={onSuccess:(l,u,h,d)=>{const g=this.getInternalLoader(h);this.resetInternalLoader(h.type);const f=l.data;u.parsing.start=performance.now(),_t.isMediaPlaylist(f)||h.type!==ee.MANIFEST?this.handleTrackOrLevelPlaylist(l,u,h,d||null,g):this.handleMasterPlaylist(l,u,h,d)},onError:(l,u,h,d)=>{this.handleNetworkError(u,h,!1,l,d)},onTimeout:(l,u,h)=>{this.handleNetworkError(u,h,!0,void 0,l)}};i.load(e,o,c)}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,i){const n=this.hls,a=e.data,o=Xn(e,s),c=_t.parseMasterPlaylist(a,o);if(c.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,s,c.playlistParsingError,i,t);return}const{contentSteering:l,levels:u,sessionData:h,sessionKeys:d,startTimeOffset:g,variableList:f}=c;this.variableList=f,u.forEach(E=>{const{unknownCodecs:T}=E;if(T){const{preferManagedMediaSource:S}=this.hls.config;let{audioCodec:_,videoCodec:D}=E;for(let I=T.length;I--;){const b=T[I];ti(b,"audio",S)?(E.audioCodec=_=_?`${_},${b}`:b,Os.audio[_.substring(0,4)]=2,T.splice(I,1)):ti(b,"video",S)&&(E.videoCodec=D=D?`${D},${b}`:b,Os.video[D.substring(0,4)]=2,T.splice(I,1))}}});const{AUDIO:p=[],SUBTITLES:y,"CLOSED-CAPTIONS":v}=_t.parseMasterPlaylistMedia(a,o,c);p.length&&!p.some(T=>!T.url)&&u[0].audioCodec&&!u[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new pe({}),bitrate:0,url:""})),n.trigger(m.MANIFEST_LOADED,{levels:u,audioTracks:p,subtitles:y,captions:v,contentSteering:l,url:o,stats:t,networkDetails:i,sessionData:h,sessionKeys:d,startTimeOffset:g,variableList:f})}handleTrackOrLevelPlaylist(e,t,s,i,n){const a=this.hls,{id:o,level:c,type:l}=s,u=Xn(e,s),h=$(c)?c:$(o)?o:0,d=eu(s),g=_t.parseLevelPlaylist(e.data,u,h,d,0,this.variableList);if(l===ee.MANIFEST){const f={attrs:new pe({}),bitrate:0,details:g,name:"",url:u};g.requestScheduled=t.loading.start+Sl(g,0),a.trigger(m.MANIFEST_LOADED,{levels:[f],audioTracks:[],url:u,stats:t,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),s.levelDetails=g,this.handlePlaylistLoaded(g,e,t,s,i,n)}handleManifestParsingError(e,t,s,i,n){this.hls.trigger(m.ERROR,{type:H.NETWORK_ERROR,details:R.MANIFEST_PARSING_ERROR,fatal:t.type===ee.MANIFEST,url:e.url,err:s,error:s,reason:s.message,response:e,context:t,networkDetails:i,stats:n})}handleNetworkError(e,t,s=!1,i,n){let a=`A network ${s?"timeout":"error"+(i?" (status "+i.code+")":"")} occurred while loading ${e.type}`;e.type===ee.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===ee.AUDIO_TRACK||e.type===ee.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);const o=new Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let c=R.UNKNOWN,l=!1;const u=this.getInternalLoader(e);switch(e.type){case ee.MANIFEST:c=s?R.MANIFEST_LOAD_TIMEOUT:R.MANIFEST_LOAD_ERROR,l=!0;break;case ee.LEVEL:c=s?R.LEVEL_LOAD_TIMEOUT:R.LEVEL_LOAD_ERROR,l=!1;break;case ee.AUDIO_TRACK:c=s?R.AUDIO_TRACK_LOAD_TIMEOUT:R.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case ee.SUBTITLE_TRACK:c=s?R.SUBTITLE_TRACK_LOAD_TIMEOUT:R.SUBTITLE_LOAD_ERROR,l=!1;break}u&&this.resetInternalLoader(e.type);const h={type:H.NETWORK_ERROR,details:c,fatal:l,url:e.url,loader:u,context:e,error:o,networkDetails:t,stats:n};if(i){const d=t?.url||e.url;h.response=ae({url:d,data:void 0},i)}this.hls.trigger(m.ERROR,h)}handlePlaylistLoaded(e,t,s,i,n,a){const o=this.hls,{type:c,level:l,levelOrTrack:u,id:h,groupId:d,deliveryDirectives:g}=i,f=Xn(t,i),p=eu(i);let y=typeof i.level=="number"&&p===G.MAIN?l:void 0;const v=e.playlistParsingError;if(v){if(this.hls.logger.warn(`${v} ${e.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(m.ERROR,{type:H.NETWORK_ERROR,details:R.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:v,reason:v.message,response:t,context:i,level:y,parent:p,networkDetails:n,stats:s});return}e.playlistParsingError=null}if(!e.fragments.length){const E=e.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(m.ERROR,{type:H.NETWORK_ERROR,details:R.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:E,reason:E.message,response:t,context:i,level:y,parent:p,networkDetails:n,stats:s});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),c){case ee.MANIFEST:case ee.LEVEL:if(y){if(!u)y=0;else if(u!==o.levels[y]){const E=o.levels.indexOf(u);E>-1&&(y=E)}}o.trigger(m.LEVEL_LOADED,{details:e,levelInfo:u||o.levels[0],level:y||0,id:h||0,stats:s,networkDetails:n,deliveryDirectives:g,withoutMultiVariant:c===ee.MANIFEST});break;case ee.AUDIO_TRACK:o.trigger(m.AUDIO_TRACK_LOADED,{details:e,track:u,id:h||0,groupId:d||"",stats:s,networkDetails:n,deliveryDirectives:g});break;case ee.SUBTITLE_TRACK:o.trigger(m.SUBTITLE_TRACK_LOADED,{details:e,track:u,id:h||0,groupId:d||"",stats:s,networkDetails:n,deliveryDirectives:g});break}}}class Dt{static get version(){return ai}static isMSESupported(){return Zc()}static isSupported(){return Vp()}static getMediaSource(){return Zt()}static get Events(){return m}static get MetadataSchema(){return ze}static get ErrorTypes(){return H}static get ErrorDetails(){return R}static get DefaultConfig(){return Dt.defaultConfig?Dt.defaultConfig:Pp}static set DefaultConfig(e){Dt.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 hn,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=sd(e.debug||!1,"Hls instance",e.assetPlayerId),s=this.config=kp(Dt.DefaultConfig,e,t);this.userConfig=e,s.progressive&&Op(s,t);const{abrController:i,bufferController:n,capLevelController:a,errorController:o,fpsController:c}=s,l=new o(this),u=this.abrController=new i(this),h=new Qd(this),d=s.interstitialsController,g=d?this.interstitialsController=new d(this,Dt):null,f=this.bufferController=new n(this,h),p=this.capLevelController=new a(this),y=new c(this),v=new jp(this),E=s.contentSteeringController,T=E?new E(this):null,S=this.levelController=new Kp(this,T),_=new Up(this),D=new qp(this.config,this.logger),I=this.streamController=new Yp(this,h,D),b=this.gapController=new $p(this,h);p.setStreamController(I),y.setStreamController(I);const A=[v,S,I];g&&A.splice(1,0,g),T&&A.splice(1,0,T),this.networkControllers=A;const x=[u,f,b,p,y,_,h];this.audioTrackController=this.createController(s.audioTrackController,A);const C=s.audioStreamController;C&&A.push(this.audioStreamController=new C(this,h,D)),this.subtitleTrackController=this.createController(s.subtitleTrackController,A);const M=s.subtitleStreamController;M&&A.push(this.subtititleStreamController=new M(this,h,D)),this.createController(s.timelineController,x),D.emeController=this.emeController=this.createController(s.emeController,x),this.cmcdController=this.createController(s.cmcdController,x),this.latencyController=this.createController(Gp,x),this.coreComponents=x,A.push(l);const K=l.onErrorOut;typeof K=="function"&&this.on(m.ERROR,K,l),this.on(m.MANIFEST_LOADED,v.onManifestLoaded,v)}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,i){this._emitter.off(e,t,s,i)}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 i=e===m.ERROR;this.trigger(m.ERROR,{type:H.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,fatal:i,event:e,error:s}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(m.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 n=new Error(`attachMedia failed: invalid argument (${e})`);this.trigger(m.ERROR,{type:H.OTHER_ERROR,details:R.ATTACH_MEDIA_ERROR,fatal:!0,error:n});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,i=t?e:{media:s};this._media=s,this.trigger(m.MEDIA_ATTACHING,i)}detachMedia(){this.logger.log("detachMedia"),this.trigger(m.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger(m.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const t=this.media,s=this._url,i=this._url=Br.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${i}`),t&&s&&(s!==i||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(m.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={[G.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[G.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[G.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,t=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=$m()),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){Md(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 i=0;i<s;i++)if(e[i].maxBitrate>=t)return i;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:s}=this;let i;if(t===-1&&e!=null&&e.length?i=e.length-1:i=t,s)for(let n=i;n--;){const a=e[n].attrs["HDCP-LEVEL"];if(a&&a<=s)return n}return i}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=Mo(t);return Co(e,s,navigator.mediaCapabilities)}}Dt.defaultConfig=void 0;class Xp{constructor(e){if(this.terminated=!1,this.restartPause=2e3,this.ws=null,this.pc=null,this.restartTimeout=null,!e?.videoElement)throw new Error("videoElement is required");if(!e.wsUri)throw new Error("wsUri is required");this.wsUri=e.wsUri,this.videoElement=e.videoElement,this.onOnline=e.onOnline,this.onOffline=e.onOffline}start(){console.log("connecting"),this.ws=new WebSocket(this.wsUri),this.ws.onerror=()=>{console.log("ws error"),this.ws!==null&&(this.ws.close(),this.ws=null)},this.ws.onclose=()=>{console.log("ws closed"),this.ws=null,this.onOffline(),this.scheduleRestart()},this.ws.onmessage=e=>this.onIceServers(e)}onIceServers(e){if(this.ws===null)return;const t=JSON.parse(e.data);this.pc=new RTCPeerConnection({iceServers:t}),this.ws.onmessage=i=>this.onRemoteDescription(i),this.pc.onicecandidate=i=>this.onIceCandidate(i),this.pc.oniceconnectionstatechange=()=>{if(this.pc!==null)switch(console.log("peer connection state:",this.pc.iceConnectionState),this.pc.iceConnectionState){case"connected":this.pc.onicecandidate=void 0,this.ws.onmessage=void 0,this.ws.onerror=void 0,this.ws.onclose=void 0,this.onOnline();break;case"disconnected":this.scheduleRestart(),this.onOffline()}},this.pc.ontrack=i=>{console.log("new track "+i.track.kind),this.videoElement.srcObject=i.streams[0]};const s="sendrecv";this.pc.addTransceiver("video",{direction:s}),this.pc.addTransceiver("audio",{direction:s}),this.pc.createOffer().then(i=>{this.pc===null||this.ws===null||(this.pc.setLocalDescription(i),console.log("sending offer"),this.ws.send(JSON.stringify(i)))})}onRemoteDescription(e){this.pc===null||this.ws===null||(this.pc.setRemoteDescription(new RTCSessionDescription(JSON.parse(e.data))),this.ws.onmessage=t=>this.onRemoteCandidate(t))}onIceCandidate(e){this.ws!==null&&e.candidate!==null&&e.candidate.candidate!==""&&this.ws.send(JSON.stringify(e.candidate))}onRemoteCandidate(e){this.pc!==null&&this.pc.addIceCandidate(JSON.parse(e.data))}scheduleRestart(){this.terminated||(this.ws!==null&&(this.ws.close(),this.ws=null),this.pc!==null&&(this.pc.close(),this.pc=null),this.restartTimeout=window.setTimeout(()=>{this.restartTimeout=null,this.start()},this.restartPause))}}var Q=function(r,e,t,s){if(t==="a"&&!s)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?s:t==="a"?s.call(r):s?s.value:e.get(r)},_e,me,tu,zn,su,iu,Ze,ru,nu,au,ou,lu,cu,fi,uu,Qn,Jn,hu,du,fu,gu,mu,Zn,pu,yu;class at{constructor(e){_e.add(this),this.retryPause=2e3,this.state="getting_codecs",this.restartTimeout=null,this.pc=null,this.offerData=null,this.sessionUrl=null,this.queuedCandidates=[],this.nonAdvertisedCodecs=[],this.conf=e,Q(this,_e,"m",uu).call(this)}close(){this.state="closed",this.pc!==null&&this.pc.close(),this.restartTimeout!==null&&clearTimeout(this.restartTimeout)}}me=at,_e=new WeakSet,tu=function(e,t){return new Promise(s=>{const i=new RTCPeerConnection({iceServers:[]}),n="audio";let a="";i.addTransceiver(n,{direction:"recvonly"}),i.createOffer().then(o=>{if(o.sdp===void 0)throw new Error("SDP not present");if(o.sdp.includes(` ${e}`))throw new Error("already present");const c=o.sdp.split(`m=${n}`),l=c.slice(1).map(h=>h.split(`\r
42
- `)[0].split(" ").slice(3)).reduce((h,d)=>[...h,...d],[]);a=Q(this,me,"m",Ze).call(this,l);const u=c[1].split(`\r
43
- `);return u[0]+=` ${a}`,u.splice(u.length-1,0,`a=rtpmap:${a} ${e}`),t!==void 0&&u.splice(u.length-1,0,`a=fmtp:${a} ${t}`),c[1]=u.join(`\r
44
- `),o.sdp=c.join(`m=${n}`),i.setLocalDescription(o)}).then(()=>i.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:`v=0\r
39
+ `),l=[],u=t?ou(t.baseTime,t.timescale):0,d=`00:00.000`,f=0,p=0,m,h=!0;s.oncue=function(e){let a=n[r],o=n.ccOffset,s=(f-u)/9e4;if(a!=null&&a.new&&(p===void 0?Rp(n,r,s):o=n.ccOffset=a.start),s){if(!t){m=Error(`Missing initPTS for VTT MPEGTS`);return}o=s-n.presentationOffset}let c=e.endTime-e.startTime,d=gu((e.startTime+o-p)*9e4,i*9e4)/9e4;e.startTime=Math.max(d,0),e.endTime=Math.max(d+c,0);let h=e.text.trim();e.text=decodeURIComponent(encodeURIComponent(h)),e.id||=Lp(e.startTime,e.endTime,h),e.endTime>0&&l.push(e)},s.onparsingerror=function(e){m=e},s.onflush=function(){if(m){o(m);return}a(l)},c.forEach(e=>{if(h)if(Fp(e,`X-TIMESTAMP-MAP=`)){h=!1,e.slice(16).split(`,`).forEach(e=>{Fp(e,`LOCAL:`)?d=e.slice(6):Fp(e,`MPEGTS:`)&&(f=parseInt(e.slice(7)))});try{p=Ip(d)/1e3}catch(e){m=e}return}else e===``&&(h=!1);s.parse(e+`
40
+ `)}),s.flush()}var Bp=`stpp.ttml.im1t`,Vp=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Hp=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Up={left:`start`,center:`center`,right:`end`,start:`start`,end:`end`};function Wp(e,t,n,r){let i=J(new Uint8Array(e),[`mdat`]);if(i.length===0){r(Error(`Could not parse IMSC1 mdat`));return}let a=i.map(e=>ci(e)),o=iu(t.baseTime,1,t.timescale);try{a.forEach(e=>n(Gp(e,o)))}catch(e){r(e)}}function Gp(e,t){let n=new DOMParser().parseFromString(e,`text/xml`).getElementsByTagName(`tt`)[0];if(!n)throw Error(`Invalid ttml`);let r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},i=Object.keys(r).reduce((e,t)=>(e[t]=n.getAttribute(`ttp:${t}`)||r[t],e),{}),a=n.getAttribute(`xml:space`)!==`preserve`,o=qp(Kp(n,`styling`,`style`)),s=qp(Kp(n,`layout`,`region`)),c=Kp(n,`body`,`[begin]`);return[].map.call(c,e=>{let n=Jp(e,a);if(!n||!e.hasAttribute(`begin`))return null;let r=Qp(e.getAttribute(`begin`),i),c=Qp(e.getAttribute(`dur`),i),l=Qp(e.getAttribute(`end`),i);if(r===null)throw Zp(e);if(l===null){if(c===null)throw Zp(e);l=r+c}let u=new wp(r-t,l-t,n);u.id=Lp(u.startTime,u.endTime,u.text);let d=s[e.getAttribute(`region`)],f=o[e.getAttribute(`style`)],p=Yp(d,f,o),{textAlign:m}=p;if(m){let e=Up[m];e&&(u.lineAlign=e),u.align=m}return U(u,p),u}).filter(e=>e!==null)}function Kp(e,t,n){let r=e.getElementsByTagName(t)[0];return r?[].slice.call(r.querySelectorAll(n)):[]}function qp(e){return e.reduce((e,t)=>{let n=t.getAttribute(`xml:id`);return n&&(e[n]=t),e},{})}function Jp(e,t){return[].slice.call(e.childNodes).reduce((e,n,r)=>{var i;return n.nodeName===`br`&&r?e+`
41
+ `:(i=n.childNodes)!=null&&i.length?Jp(n,t):t?e+n.textContent.trim().replace(/\s+/g,` `):e+n.textContent},``)}function Yp(e,t,n){let r=`http://www.w3.org/ns/ttml#styling`,i=null,a=[`displayAlign`,`textAlign`,`color`,`backgroundColor`,`fontSize`,`fontFamily`],o=e!=null&&e.hasAttribute(`style`)?e.getAttribute(`style`):null;return o&&n.hasOwnProperty(o)&&(i=n[o]),a.reduce((n,a)=>{let o=Xp(t,r,a)||Xp(e,r,a)||Xp(i,r,a);return o&&(n[a]=o),n},{})}function Xp(e,t,n){return e&&e.hasAttributeNS(t,n)?e.getAttributeNS(t,n):null}function Zp(e){return Error(`Could not parse ttml timestamp ${e}`)}function Qp(e,t){if(!e)return null;let n=Ep(e);return n===null&&(Vp.test(e)?n=$p(e,t):Hp.test(e)&&(n=em(e,t))),n}function $p(e,t){let n=Vp.exec(e),r=(n[4]|0)+(n[5]|0)/t.subFrameRate;return(n[1]|0)*3600+(n[2]|0)*60+(n[3]|0)+r/t.frameRate}function em(e,t){let n=Hp.exec(e),r=Number(n[1]);switch(n[2]){case`h`:return r*3600;case`m`:return r*60;case`ms`:return r*1e3;case`f`:return r/t.frameRate;case`t`:return r/t.tickRate}return r}var tm=class{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,n){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=n,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}},nm=class{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=om(),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(B.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(B.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(B.MANIFEST_LOADING,this.onManifestLoading,this),e.on(B.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(B.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(B.FRAG_LOADING,this.onFragLoading,this),e.on(B.FRAG_LOADED,this.onFragLoaded,this),e.on(B.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(B.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(B.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(B.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(B.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){let{hls:e}=this;e.off(B.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(B.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(B.MANIFEST_LOADING,this.onManifestLoading,this),e.off(B.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(B.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(B.FRAG_LOADING,this.onFragLoading,this),e.off(B.FRAG_LOADED,this.onFragLoaded,this),e.off(B.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(B.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(B.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(B.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(B.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){let e=new tm(this,`textTrack1`),t=new tm(this,`textTrack2`),n=new tm(this,`textTrack3`),r=new tm(this,`textTrack4`);this.cea608Parser1=new bp(1,e,t),this.cea608Parser2=new bp(3,n,r)}addCues(e,t,n,r,i){let a=!1;for(let e=i.length;e--;){let r=i[e],o=am(r[0],r[1],t,n);if(o>=0&&(r[0]=Math.min(r[0],t),r[1]=Math.max(r[1],n),a=!0,o/(n-t)>.5))return}if(a||i.push([t,n]),this.config.renderTextTracksNatively){let i=this.captionsTracks[e];this.Cues.newCue(i,t,n,r)}else{let i=this.Cues.newCue(null,t,n,r);this.hls.trigger(B.CUES_PARSED,{type:`captions`,cues:i,track:e})}}onInitPtsFound(e,{frag:t,id:n,initPTS:r,timescale:i,trackId:a}){let{unparsedVttFrags:o}=this;n===H.MAIN&&(this.initPTS[t.cc]={baseTime:r,timescale:i,trackId:a}),o.length&&(this.unparsedVttFrags=[],o.forEach(e=>{this.initPTS[e.frag.cc]?this.onFragLoaded(B.FRAG_LOADED,e):this.hls.trigger(B.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e.frag,error:Error(`Subtitle discontinuity domain does not match main`)})}))}getExistingTrack(e,t){let{media:n}=this;if(n)for(let r=0;r<n.textTracks.length;r++){let i=n.textTracks[r];if(im(i,{name:e,lang:t,characteristics:`transcribes-spoken-dialog,describes-music-and-sound`}))return i}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;let{captionsProperties:t,captionsTracks:n,media:r}=this,{label:i,languageCode:a}=t[e],o=this.getExistingTrack(i,a);if(o)n[e]=o,Af(n[e]),Of(n[e],r);else{let t=this.createTextTrack(`captions`,i,a);t&&(t[e]=!0,n[e]=t)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;let t=this.captionsProperties[e];if(!t)return;let n={_id:e,label:t.label,kind:`captions`,default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=n,this.hls.trigger(B.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[n]})}createTextTrack(e,t,n){let r=this.media;if(r)return r.addTextTrack(e,t,n)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){let n=!!t.transferMedia;if(this.media=null,n)return;let{captionsTracks:r}=this;Object.keys(r).forEach(e=>{Af(r[e]),delete r[e]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=om(),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(){let{media:e}=this;if(!e)return;let t=e.textTracks;if(t)for(let e=0;e<t.length;e++)Af(t[e])}onSubtitleTracksUpdated(e,t){let n=t.subtitleTracks||[],r=n.some(e=>e.textCodec===Bp);if(this.config.enableWebVTT||r&&this.config.enableIMSC1){if(Lu(this.tracks,n)){this.tracks=n;return}if(this.textTracks=[],this.tracks=n,this.config.renderTextTracksNatively){let e=this.media,t=e?Pf(e.textTracks):null;if(this.tracks.forEach((e,n)=>{let r;if(t){let n=null;for(let r=0;r<t.length;r++)if(t[r]&&im(t[r],e)){n=t[r],t[r]=null;break}n&&(r=n)}if(r)Af(r);else{let t=rm(e);r=this.createTextTrack(t,e.name,e.lang),r&&(r.mode=`disabled`)}r&&this.textTracks.push(r)}),t!=null&&t.length){let e=t.filter(e=>e!==null).map(e=>e.label);e.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${e.join(`, `)}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){let e=this.tracks.map(e=>({label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e}));this.hls.trigger(B.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:e})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(e=>{let t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(!t)return;let n=`textTrack${t[1]}`,r=this.captionsProperties[n];r&&(r.label=e.name,e.lang&&(r.languageCode=e.lang),r.media=e)})}closedCaptionsForLevel(e){return this.hls.levels[e.level]?.attrs[`CLOSED-CAPTIONS`]}onFragLoading(e,t){if(this.enabled&&t.frag.type===H.MAIN){let{cea608Parser1:e,cea608Parser2:n,lastSn:r}=this,{cc:i,sn:a}=t.frag,o=t.part?.index??-1;e&&n&&(a!==r+1||a===r&&o!==this.lastPartIndex+1||i!==this.lastCc)&&(e.reset(),n.reset()),this.lastCc=i,this.lastSn=a,this.lastPartIndex=o}}onFragLoaded(e,t){let{frag:n,payload:r}=t;if(n.type===H.SUBTITLE)if(r.byteLength){let e=n.decryptdata,i=`stats`in t;if(e==null||!e.encrypted||i){let e=this.tracks[n.level],i=this.vttCCs;i[n.cc]||(i[n.cc]={start:n.start,prevCC:this.prevCC,new:!0},this.prevCC=n.cc),e&&e.textCodec===Bp?this._parseIMSC1(n,r):this._parseVTTs(t)}}else this.hls.trigger(B.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,error:Error(`Empty subtitle payload`)})}_parseIMSC1(e,t){let n=this.hls;Wp(t,this.initPTS[e.cc],t=>{this._appendCues(t,e.level),n.trigger(B.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},t=>{n.logger.log(`Failed to parse IMSC1: ${t}`),n.trigger(B.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:t})})}_parseVTTs(e){var t;let{frag:n,payload:r}=e,{initPTS:i,unparsedVttFrags:a}=this,o=i.length-1;if(!i[n.cc]&&o===-1){a.push(e);return}let s=this.hls;zp((t=n.initSegment)!=null&&t.data?Gi(n.initSegment.data,new Uint8Array(r)).buffer:r,this.initPTS[n.cc],this.vttCCs,n.cc,n.start,e=>{this._appendCues(e,n.level),s.trigger(B.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:n})},t=>{let i=t.message===`Missing initPTS for VTT MPEGTS`;i?a.push(e):this._fallbackToIMSC1(n,r),s.logger.log(`Failed to parse VTT cue: ${t}`),!(i&&o>n.cc)&&s.trigger(B.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,error:t})})}_fallbackToIMSC1(e,t){let n=this.tracks[e.level];n.textCodec||Wp(t,this.initPTS[e.cc],()=>{n.textCodec=Bp,this._parseIMSC1(e,t)},()=>{n.textCodec=`wvtt`})}_appendCues(e,t){let n=this.hls;if(this.config.renderTextTracksNatively){let n=this.textTracks[t];if(!n||n.mode===`disabled`)return;e.forEach(e=>kf(n,e))}else{let r=this.tracks[t];if(!r)return;let i=r.default?`default`:`subtitles`+t;n.trigger(B.CUES_PARSED,{type:`subtitles`,cues:e,track:i})}}onFragDecrypted(e,t){let{frag:n}=t;n.type===H.SUBTITLE&&this.onFragLoaded(B.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;let{frag:n,samples:r}=t;if(!(n.type===H.MAIN&&this.closedCaptionsForLevel(n)===`NONE`))for(let e=0;e<r.length;e++){let t=r[e].bytes;if(t){this.cea608Parser1||this.initCea608Parsers();let n=this.extractCea608Data(t);this.cea608Parser1.addData(r[e].pts,n[0]),this.cea608Parser2.addData(r[e].pts,n[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:n,endOffsetSubtitles:r,type:i}){let{media:a}=this;if(!(!a||a.currentTime<n)){if(!i||i===`video`){let{captionsTracks:e}=this;Object.keys(e).forEach(r=>jf(e[r],t,n))}if(this.config.renderTextTracksNatively&&t===0&&r!==void 0){let{textTracks:e}=this;Object.keys(e).forEach(n=>jf(e[n],t,r))}}}extractCea608Data(e){let t=[[],[]],n=e[0]&31,r=2;for(let i=0;i<n;i++){let n=e[r++],i=127&e[r++],a=127&e[r++];if(!(i===0&&a===0)&&4&n){let e=3&n;(e===0||e===1)&&(t[e].push(i),t[e].push(a))}}return t}};function rm(e){return e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?`captions`:`subtitles`}function im(e,t){return!!e&&e.kind===rm(t)&&zu(t,e)}function am(e,t,n,r){return Math.min(t,r)-Math.max(e,n)}function om(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}var sm=/\s/,cm={newCue(e,t,n,r){let i=[],a,o,s,c,l,u=self.VTTCue||self.TextTrackCue;for(let f=0;f<r.rows.length;f++)if(a=r.rows[f],s=!0,c=0,l=``,!a.isEmpty()){var d;for(let e=0;e<a.chars.length;e++)sm.test(a.chars[e].uchar)&&s?c++:(l+=a.chars[e].uchar,s=!1);a.cueStartTime=t,t===n&&(n+=1e-4),c>=16?c--:c++;let r=Mp(l.trim()),p=Lp(t,n,r);e!=null&&(d=e.cues)!=null&&d.getCueById(p)||(o=new u(t,n,r),o.id=p,o.line=f+1,o.align=`left`,o.position=10+Math.min(80,Math.floor(c*8/32)*10),i.push(o))}return e&&i.length&&(i.sort((e,t)=>e.line===`auto`||t.line===`auto`?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line),i.forEach(t=>kf(e,t))),i}};function lm(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}var um=/(\d+)-(\d+)\/(\d+)/,dm=class{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||hm,this.controller=new self.AbortController,this.stats=new gi}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,n){let r=this.stats;if(r.loading.start)throw Error(`Loader can only be used once.`);r.loading.start=self.performance.now();let i=fm(e,this.controller.signal),a=e.responseType===`arraybuffer`,o=a?`byteLength`:`length`,{maxTimeToFirstByteMs:s,maxLoadTimeMs:c}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=n,this.request=this.fetchSetup(e,i),self.clearTimeout(this.requestTimeout),t.timeout=s&&L(s)?s:c,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(r,e,this.response))},t.timeout),(ku(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(n=>{this.response=this.loader=n;let i=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=c,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(r,e,this.response))},c-(i-r.loading.start)),!n.ok){let{status:e,statusText:t}=n;throw new gm(t||`fetch, bad network response`,e,n)}r.loading.first=i,r.total=mm(n.headers)||r.total;let o=this.callbacks?.onProgress;return o&&L(t.highWaterMark)?this.loadProgressively(n,r,e,t.highWaterMark,o):a?n.arrayBuffer():e.responseType===`json`?n.json():n.text()}).then(n=>{var i;let a=this.response;if(!a)throw Error(`loader destroyed`);self.clearTimeout(this.requestTimeout),r.loading.end=Math.max(self.performance.now(),r.loading.first);let s=n[o];s&&(r.loaded=r.total=s);let c={url:a.url,data:n,code:a.status},l=this.callbacks?.onProgress;l&&!L(t.highWaterMark)&&l(r,e,n,a),(i=this.callbacks)==null||i.onSuccess(c,r,e,a)}).catch(t=>{var n;if(self.clearTimeout(this.requestTimeout),r.aborted)return;let i=t&&t.code||0,a=t?t.message:null;(n=this.callbacks)==null||n.onError({code:i,text:a},e,t?t.details:null,r)})}getCacheAge(){let e=null;if(this.response){let 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,n,r=0,i){let a=new Tc,o=e.body.getReader(),s=()=>o.read().then(o=>{if(o.done)return a.dataLength&&i(t,n,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));let c=o.value,l=c.length;return t.loaded+=l,l<r||a.dataLength?(a.push(c),a.dataLength>=r&&i(t,n,a.flush().buffer,e)):i(t,n,c.buffer,e),s()}).catch(()=>Promise.reject());return s()}};function fm(e,t){let n={method:`GET`,mode:`cors`,credentials:`same-origin`,signal:t,headers:new self.Headers(U({},e.headers))};return e.rangeEnd&&n.headers.set(`Range`,`bytes=`+e.rangeStart+`-`+String(e.rangeEnd-1)),n}function pm(e){let t=um.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}function mm(e){let t=e.get(`Content-Range`);if(t){let e=pm(t);if(L(e))return e}let n=e.get(`Content-Length`);if(n)return parseInt(n)}function hm(e,t){return new self.Request(e.url,t)}var gm=class extends Error{constructor(e,t,n){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=n}},_m=/^age:\s*[\d.]+\s*$/im,vm=class{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 gi,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){let 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,n){if(this.stats.loading.start)throw Error(`Loader can only be used once.`);this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=n,this.loadInternal()}loadInternal(){let{config:e,context:t}=this;if(!e||!t)return;let n=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=!1;let i=this.xhrSetup;i?Promise.resolve().then(()=>{if(!(this.loader!==n||this.stats.aborted))return i(n,t.url)}).catch(e=>{if(!(this.loader!==n||this.stats.aborted))return n.open(`GET`,t.url,!0),i(n,t.url)}).then(()=>{this.loader!==n||this.stats.aborted||this.openAndSendXhr(n,t,e)}).catch(e=>{var i;(i=this.callbacks)==null||i.onError({code:n.status,text:e.message},t,n,r)}):this.openAndSendXhr(n,t,e)}openAndSendXhr(e,t,n){e.readyState||e.open(`GET`,t.url,!0);let r=t.headers,{maxTimeToFirstByteMs:i,maxLoadTimeMs:a}=n.loadPolicy;if(r)for(let t in r)e.setRequestHeader(t,r[t]);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),n.timeout=i&&L(i)?i:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.timeout),e.send()}readystatechange(){let{context:e,loader:t,stats:n}=this;if(!e||!t)return;let r=t.readyState,i=this.config;if(!n.aborted&&r>=2&&(n.loading.first===0&&(n.loading.first=Math.max(self.performance.now(),n.loading.start),i.timeout!==i.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),i.timeout=i.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.loadPolicy.maxLoadTimeMs-(n.loading.first-n.loading.start)))),r===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;let r=t.status,s=t.responseType===`text`?t.responseText:null;if(r>=200&&r<300){let i=s??t.response;if(i!=null){var a;n.loading.end=Math.max(self.performance.now(),n.loading.first),n.loaded=n.total=t.responseType===`arraybuffer`?i.byteLength:i.length,n.bwEstimate=n.total*8e3/(n.loading.end-n.loading.first);let o=this.callbacks?.onProgress;o&&o(n,e,i,t);let s={url:t.responseURL,data:i,code:r};(a=this.callbacks)==null||a.onSuccess(s,n,e,t);return}}let c=i.loadPolicy.errorRetry,l=n.retry;if(vo(c,l,!1,{url:e.url,data:void 0,code:r}))this.retry(c);else{var o;G.error(`${r} while loading ${e.url}`),(o=this.callbacks)==null||o.onError({code:r,text:t.statusText},e,t,n)}}}loadtimeout(){if(!this.config)return;let e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(vo(e,t,!0))this.retry(e);else{G.warn(`timeout while loading ${this.context?.url}`);let e=this.callbacks;e&&(this.abortInternal(),e.onTimeout(this.stats,this.context,this.loader))}}retry(e){let{context:t,stats:n}=this;this.retryDelay=go(e,n.retry),n.retry++,G.warn(`${status?`HTTP Status `+status:`Timeout`} while loading ${t?.url}, retrying ${n.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){let t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&_m.test(this.loader.getAllResponseHeaders())){let t=this.loader.getResponseHeader(`age`);e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&RegExp(`^${e}:\\s*[\\d.]+\\s*$`,`im`).test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}},ym=W(W({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:1/0,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:vm,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:ro,bufferController:Gu,capLevelController:Yu,errorController:Co,fpsController:Df,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:Cs,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:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},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},bm()),{},{subtitleStreamController:np,subtitleTrackController:Ff,timelineController:nm,audioStreamController:Fu,audioTrackController:Bu,emeController:Sf,cmcdController:_f,contentSteeringController:yf,interstitialsController:ep});function bm(){return{cueHandler:cm,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 xm(e,t,n){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw Error(`Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration`);if(t.liveMaxLatencyDurationCount!==void 0&&(t.liveSyncDurationCount===void 0||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw Error(`Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"`);if(t.liveMaxLatencyDuration!==void 0&&(t.liveSyncDuration===void 0||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw Error(`Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"`);let r=Sm(e),i=[`manifest`,`level`,`frag`],a=[`TimeOut`,`MaxRetry`,`RetryDelay`,`MaxRetryTimeout`];return i.forEach(e=>{let i=`${e===`level`?`playlist`:e}LoadPolicy`,o=t[i]===void 0,s=[];a.forEach(n=>{let a=`${e}Loading${n}`,c=t[a];if(c!==void 0&&o){s.push(a);let e=r[i].default;switch(t[i]={default:e},n){case`TimeOut`:e.maxLoadTimeMs=c,e.maxTimeToFirstByteMs=c;break;case`MaxRetry`:e.errorRetry.maxNumRetry=c,e.timeoutRetry.maxNumRetry=c;break;case`RetryDelay`:e.errorRetry.retryDelayMs=c,e.timeoutRetry.retryDelayMs=c;break;case`MaxRetryTimeout`:e.errorRetry.maxRetryDelayMs=c,e.timeoutRetry.maxRetryDelayMs=c;break}}}),s.length&&n.warn(`hls.js config: "${s.join(`", "`)}" setting(s) are deprecated, use "${i}": ${Y(t[i])}`)}),W(W({},r),t)}function Sm(e){return e&&typeof e==`object`?Array.isArray(e)?e.map(Sm):Object.keys(e).reduce((t,n)=>(t[n]=Sm(e[n]),t),{}):e}function Cm(e,t){let n=e.loader;n!==dm&&n!==vm?(t.log(`[config]: Custom loader detected, cannot enable progressive streaming`),e.progressive=!1):lm()&&(e.loader=dm,e.progressive=!0,e.enableSoftwareAES=!0,t.log(`[config]: Progressive streaming enabled, using FetchLoader`))}var wm=2,Tm=.1,Em=.05,Dm=100,Om=class extends Wo{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 e;(e=this.media)!=null&&e.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{this.hls&&(this.ended=this.media?.currentTime||1,this.hls.trigger(B.MEDIA_ENDED,{stalled:!1}))},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){let{hls:e}=this;e&&(e.on(B.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(B.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(B.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(B.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(B.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(B.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(Dm),this.mediaSource=t.mediaSource;let n=this.media=t.media;bc(n,`playing`,this.onMediaPlaying),bc(n,`waiting`,this.onMediaWaiting),bc(n,`ended`,this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();let{media:n}=this;n&&(xc(n,`playing`,this.onMediaPlaying),xc(n,`waiting`,this.onMediaWaiting),xc(n,`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;let t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){let n=this.hls?.config;if(!n)return;let r=this.media;if(!r)return;let{seeking:i}=r,a=this.seeking&&!i,o=!this.seeking&&i,s=r.paused&&!i||r.ended||r.playbackRate===0;if(this.seeking=i,e!==t){t&&(this.ended=0),this.moved=!0,i||(this.nudgeRetry=0,n.nudgeOnVideoHole&&!s&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(o||a){a&&this.stallResolved(e);return}if(s){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&r.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(B.MEDIA_ENDED,{stalled:!1}));return}if(!X.getBuffered(r).length){this.nudgeRetry=0;return}let c=X.bufferInfo(r,e,0),l=c.nextStart||0,u=this.fragmentTracker;if(i&&u&&this.hls){let t=km(this.hls.inFlightFragments,e),n=c.len>wm,r=!l||t||l-e>wm&&!u.getPartialFragment(e);if(n||r)return;this.moved=!1}let d=this.hls?.latestLevelDetails;if(!this.moved&&this.stalled!==null&&u){if(!(c.len>0)&&!l)return;let t=Math.max(l,c.start||0)-e,n=d!=null&&d.live?d.targetduration*2:wm,i=jm(e,u);if(t>0&&(t<=n||i)){r.paused||this._trySkipBufferHole(i);return}}let f=n.detectStallWithCurrentTimeMs,p=self.performance.now(),m=this.waiting,h=this.stalled;if(h===null)if(m>0&&p-m<f)h=this.stalled=m;else{this.stalled=p;return}let g=p-h;if(!i&&(g>=f||m)&&this.hls){if(this.mediaSource?.readyState===`ended`&&!(d!=null&&d.live)&&Math.abs(e-(d?.edge||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(B.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(c),!this.media||!this.hls)return}let _=X.bufferInfo(r,e,n.maxBufferHole);this._tryFixBufferStall(_,g,e)}stallResolved(e){let t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){let n=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(n)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(B.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var n;let r=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(n=this.buffered.audio)!=null&&n.length&&r&&r.length>1&&e>r.end(0)){let n=X.bufferedInfo(X.timeRangesToArray(this.buffered.audio),e,0);if(n.len>1&&t>=n.start){let n=X.timeRangesToArray(r),i=X.bufferedInfo(n,t,0).bufferedIndex;if(i>-1&&i<n.length-1){let t=X.bufferedInfo(n,e,0).bufferedIndex,r=n[i].end,a=n[i+1].start;if((t===-1||t>i)&&a-r<1&&e-r<2){let n=Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${r} -> ${a} buffered index: ${t}`);this.warn(n.message),this.media.currentTime+=1e-6;let i=jm(e,this.fragmentTracker);i&&`fragment`in i?i=i.fragment:i||=void 0;let o=X.bufferInfo(this.media,e,0);this.hls.trigger(B.ERROR,{type:R.MEDIA_ERROR,details:z.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:n,reason:n.message,frag:i,buffer:o.len,bufferInfo:o})}}}}}_tryFixBufferStall(e,t,n){let{fragmentTracker:r,media:i}=this,a=this.hls?.config;if(!i||!r||!a)return;let o=this.hls?.latestLevelDetails,s=jm(n,r);if((s||o!=null&&o.live&&n<o.fragmentStart)&&(this._trySkipBufferHole(s)||!this.media))return;let c=e.buffered,l=this.adjacentTraversal(e,n);(c&&c.length>1&&e.len>a.maxBufferHole||e.nextStart&&(e.nextStart-n<a.maxBufferHole||l))&&(t>a.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn(`Trying to nudge playhead over buffer-hole`),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){let n=this.fragmentTracker,r=e.nextStart;if(n&&r){let e=n.getFragAtPos(t,H.MAIN),i=n.getFragAtPos(r,H.MAIN);if(e&&i)return i.sn-e.sn<2}return!1}_reportStall(e){let{hls:t,media:n,stallReported:r,stalled:i}=this;if(!r&&i!==null&&n&&t){this.stallReported=!0;let r=Error(`Playback stalling at @${n.currentTime} due to low buffer (${Y(e)})`);this.warn(r.message),t.trigger(B.ERROR,{type:R.MEDIA_ERROR,details:z.BUFFER_STALLED_ERROR,fatal:!1,error:r,buffer:e.len,bufferInfo:e,stalled:{start:i}})}}_trySkipBufferHole(e){let{fragmentTracker:t,media:n}=this,r=this.hls?.config;if(!n||!t||!r)return 0;let i=n.currentTime,a=X.bufferInfo(n,i,0),o=i<a.start?a.start:a.nextStart;if(o&&this.hls){let c=a.len<=r.maxBufferHole,l=a.len>0&&a.len<1&&n.readyState<3,u=o-i;if(u>0&&(c||l)){if(u>r.maxBufferHole){let n=!1;if(i===0){let e=t.getAppendedFrag(0,H.MAIN);e&&o<e.end&&(n=!0)}if(!n&&e){var s;if(!((s=this.hls.loadLevelObj)!=null&&s.details)||km(this.hls.inFlightFragments,o))return 0;let n=!1,r=e.end;for(;r<o;){let e=jm(r,t);if(e)r+=e.duration;else{n=!0;break}}if(n)return 0}}let c=Math.max(o+Em,i+Tm);if(this.warn(`skipping hole, adjusting currentTime from ${i} to ${c}`),this.moved=!0,n.currentTime=c,!(e!=null&&e.gap)){let t=Error(`fragment loaded with buffer holes, seeking from ${i} to ${c}`),n={type:R.MEDIA_ERROR,details:z.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:t,reason:t.message,buffer:a.len,bufferInfo:a};e&&(`fragment`in e?n.part=e:n.frag=e),this.hls.trigger(B.ERROR,n)}return c}}return 0}_tryNudgeBuffer(e){let{hls:t,media:n,nudgeRetry:r}=this,i=t?.config;if(!n||!i)return 0;let a=n.currentTime;if(this.nudgeRetry++,r<i.nudgeMaxRetry){let o=a+(r+1)*i.nudgeOffset,s=Error(`Nudging 'currentTime' from ${a} to ${o}`);this.warn(s.message),n.currentTime=o,t.trigger(B.ERROR,{type:R.MEDIA_ERROR,details:z.BUFFER_NUDGE_ON_STALL,error:s,fatal:!1,buffer:e.len,bufferInfo:e})}else{let n=Error(`Playhead still not moving while enough data buffered @${a} after ${i.nudgeMaxRetry} nudges`);this.error(n.message),t.trigger(B.ERROR,{type:R.MEDIA_ERROR,details:z.BUFFER_STALLED_ERROR,error:n,fatal:!0,buffer:e.len,bufferInfo:e})}}};function km(e,t){let n=Am(e.main);if(n&&n.start<=t)return n;let r=Am(e.audio);return r&&r.start<=t?r:null}function Am(e){if(!e)return null;switch(e.state){case Z.IDLE:case Z.STOPPED:case Z.ENDED:case Z.ERROR:return null}return e.frag}function jm(e,t){return t.getAppendedFrag(e,H.MAIN)||t.getPartialFragment(e)}var Mm=.25;function Nm(){if(!(typeof self>`u`))return self.VTTCue||self.TextTrackCue}function Pm(e,t,n,r,i){let a=new e(t,n,``);try{a.value=r,i&&(a.type=i)}catch{a=new e(t,n,Y(i?W({type:i},r):r))}return a}var Fm=(()=>{let e=Nm();try{e&&new e(0,1/0,``)}catch{return Number.MAX_VALUE}return 1/0})(),Im=class{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(B.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(){let{hls:e}=this;e&&(e.on(B.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(B.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(B.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(B.MANIFEST_LOADING,this.onManifestLoading,this),e.on(B.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(B.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(B.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(B.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){let{hls:e}=this;e&&(e.off(B.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(B.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(B.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(B.MANIFEST_LOADING,this.onManifestLoading,this),e.off(B.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(B.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(B.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(B.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){this.media=t.media,t.overrides?.cueRemoval===!1&&(this.removeCues=!1)}onMediaAttached(){let e=this.hls?.latestLevelDetails;e&&this.updateDateRangeCues(e)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&=(this.removeCues&&Af(this.id3Track,this.onEventCueEnter),null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){let t=this.getID3Track(e.textTracks);return t.mode=`hidden`,t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){let n=e[t];if(n.kind===`metadata`&&n.label===`id3`)return Of(n,this.media),n}return this.media.addTextTrack(`metadata`,`id3`)}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;let{enableEmsgMetadataCues:n,enableID3MetadataCues:r}=this.hls.config;if(!n&&!r)return;let{samples:i}=t;this.id3Track||=this.createTrack(this.media);let a=Nm();if(a)for(let e=0;e<i.length;e++){let t=i[e].type;if(t===_l.emsg&&!n||!r)continue;let o=pl(i[e].data),s=i[e].pts,c=s+i[e].duration;c>Fm&&(c=Fm),c-s<=0&&(c=s+Mm);for(let e=0;e<o.length;e++){let n=o[e];if(!ml(n)){this.updateId3CueEnds(s,t);let e=Pm(a,s,c,n,t);e&&this.id3Track.addCue(e)}}}}updateId3CueEnds(e,t){let n=this.id3Track?.cues;if(n)for(let r=n.length;r--;){let i=n[r];i.type===t&&i.startTime<e&&i.endTime===Fm&&(i.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:n,type:r}){let{id3Track:i,hls:a}=this;if(!a)return;let{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:s}}=a;if(i&&(o||s)){let e;e=r===`audio`?e=>e.type===_l.audioId3&&s:r===`video`?e=>e.type===_l.emsg&&o:e=>e.type===_l.audioId3&&s||e.type===_l.emsg&&o,jf(i,t,n,e)}}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;let{assetPlayerId:n,timelineOffset:r,enableDateRangeMetadataCues:i,interstitialsController:a}=this.hls.config;if(!i)return;let o=Nm();if(n&&r&&!a){let{fragmentStart:t,fragmentEnd:r}=e,i=this.assetCue;i?(i.startTime=t,i.endTime=r):o&&(i=this.assetCue=Pm(o,t,r,{assetPlayerId:this.hls.config.assetPlayerId},`hlsjs.interstitial.asset`),i&&(i.id=n,this.id3Track||=this.createTrack(this.media),this.id3Track.addCue(i),i.addEventListener(`enter`,this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;let{id3Track:s}=this,{dateRanges:c}=e,l=Object.keys(c),u=this.dateRangeCuesAppended;if(s&&t){var d;if((d=s.cues)!=null&&d.length){let e=Object.keys(u).filter(e=>!l.includes(e));for(let t=e.length;t--;){let n=e[t],r=u[n]?.cues;delete u[n],r&&Object.keys(r).forEach(e=>{let t=r[e];if(t){t.removeEventListener(`enter`,this.onEventCueEnter);try{s.removeCue(t)}catch{}}})}}else u=this.dateRangeCuesAppended={}}let f=e.fragments[e.fragments.length-1];if(!(l.length===0||!L(f?.programDateTime))){this.id3Track||=this.createTrack(this.media);for(let e=0;e<l.length;e++){let t=l[e],n=c[t],r=n.startTime,i=u[t],s=i?.cues||{},d=i?.durationKnown||!1,f=Fm,{duration:p,endDate:m}=n;if(m&&p!==null)f=r+p,d=!0;else if(n.endOnNext&&!d){let e=l.reduce((e,t)=>{if(t!==n.id){let r=c[t];if(r.class===n.class&&r.startDate>n.startDate&&(!e||n.startDate<e.startDate))return r}return e},null);e&&(f=e.startTime,d=!0)}let h=Object.keys(n.attr);for(let e=0;e<h.length;e++){let c=h[e];if(!rs(c))continue;let l=s[c];if(l)d&&!(i!=null&&i.durationKnown)?l.endTime=f:Math.abs(l.startTime-r)>.01&&(l.startTime=r,l.endTime=f);else if(o){let e=n.attr[c];is(c)&&(e=ui(e));let i=Pm(o,r,f,{key:c,data:e},_l.dateRange);i&&(i.id=t,this.id3Track.addCue(i),s[c]=i,a&&(c===`X-ASSET-LIST`||c===`X-ASSET-URL`)&&i.addEventListener(`enter`,this.onEventCueEnter))}}u[t]={cues:s,dateRange:n,durationKnown:d}}}}},Lm=class{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=()=>{let{media:e}=this,t=this.levelDetails;if(!e||!t)return;this.currentTime=e.currentTime;let n=this.computeLatency();if(n===null)return;this._latency=n;let{lowLatencyMode:r,maxLiveSyncPlaybackRate:i}=this.config;if(!r||i===1||!t.live)return;let a=this.targetLatency;if(a===null)return;let o=n-a;if(o<Math.min(this.maxLatency,a+t.targetduration)&&o>.05&&this.forwardBufferLength>1){let t=Math.min(2,Math.max(1,i)),n=Math.round(2/(1+Math.exp(-.75*o-this.edgeStalled))*20)/20,r=Math.min(t,Math.max(1,n));this.changeMediaPlaybackRate(e,r)}else e.playbackRate!==1&&e.playbackRate!==0&&this.changeMediaPlaybackRate(e,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){return this.hls?.latestLevelDetails||null}get latency(){return this._latency||0}get maxLatency(){let{config:e}=this;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;let t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){let e=this.levelDetails;if(e===null||this.hls===null)return null;let{holdBack:t,partHoldBack:n,targetduration:r}=e,{liveSyncDuration:i,liveSyncDurationCount:a,lowLatencyMode:o}=this.config,s=this.hls.userConfig,c=o&&n||t;(this._targetLatencyUpdated||s.liveSyncDuration||s.liveSyncDurationCount||c===0)&&(c=i===void 0?a*r:i);let l=r;return c+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,l)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){let e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null)return null;let n=this.levelDetails;if(n===null)return null;let r=n.edge,i=e-t-this.edgeStalled,a=r-n.totalduration,o=r-(this.config.lowLatencyMode&&n.partTarget||n.targetduration);return Math.min(Math.max(a,i),o)}get drift(){let e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){let e=this.levelDetails;if(e===null)return 0;let t=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){let{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;let n=e.buffered.length;return(n?e.buffered.end(n-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){let{hls:e}=this;e&&(e.on(B.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(B.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(B.MANIFEST_LOADING,this.onManifestLoading,this),e.on(B.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(B.ERROR,this.onError,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(B.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(B.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(B.MANIFEST_LOADING,this.onManifestLoading,this),e.off(B.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(B.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),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 n;t.details===z.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(n=this.levelDetails)!=null&&n.live&&this.hls.logger.warn(`[latency-controller]: Stall detected, adjusting target latency`))}changeMediaPlaybackRate(e,t){var n;e.playbackRate!==t&&((n=this.hls)==null||n.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${this.targetLatency?.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){let e=this.levelDetails;return e===null?null:e.edge+e.age}computeLatency(){let e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}},Rm=class extends Iu{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(){let{hls:e}=this;e.on(B.MANIFEST_LOADING,this.onManifestLoading,this),e.on(B.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(B.LEVEL_LOADED,this.onLevelLoaded,this),e.on(B.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(B.FRAG_BUFFERED,this.onFragBuffered,this),e.on(B.ERROR,this.onError,this)}_unregisterListeners(){let{hls:e}=this;e.off(B.MANIFEST_LOADING,this.onManifestLoading,this),e.off(B.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(B.LEVEL_LOADED,this.onLevelLoaded,this),e.off(B.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(B.FRAG_BUFFERED,this.onFragBuffered,this),e.off(B.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(e=>{e.loadError=0,e.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){let n=this.hls.config.preferManagedMediaSource,r=[],i={},a={},o=!1,s=!1,c=!1;t.levels.forEach(e=>{let t=e.attrs,{audioCodec:l,videoCodec:u}=e;l&&(e.audioCodec=l=pa(l,n)||void 0),u&&=e.videoCodec=_a(u);let{width:d,height:f,unknownCodecs:p}=e,m=p?.length||0;if(o||=!!(d&&f),s||=!!u,c||=!!l,m||l&&!this.isAudioSupported(l)||u&&!this.isVideoSupported(u)){this.log(`Some or all CODECS not supported "${t.CODECS}"`);return}let{CODECS:h,"FRAME-RATE":g,"HDCP-LEVEL":_,"PATHWAY-ID":v,RESOLUTION:y,"VIDEO-RANGE":b}=t,x=`${`${v||`.`}-`}${e.bitrate}-${y}-${g}-${h}-${b}-${_}`;if(!i[x]){let t=this.createLevel(e);i[x]=t,a[x]=1,r.push(t)}else if(i[x].uri!==e.url&&!e.attrs[`PATHWAY-ID`]){let t=a[x]+=1;e.attrs[`PATHWAY-ID`]=Array(t+1).join(`.`);let n=this.createLevel(e);i[x]=n,r.push(n)}else i[x].addGroupId(`audio`,t.AUDIO),i[x].addGroupId(`text`,t.SUBTITLES)}),this.filterAndSortMediaOptions(r,t,o,s,c)}createLevel(e){let t=new za(e),n=e.supplemental;if(n!=null&&n.videoCodec&&!this.isVideoSupported(n.videoCodec)){let e=Error(`SUPPLEMENTAL-CODECS not supported "${n.videoCodec}"`);this.log(e.message),t.supportedResult=wa(e,[])}return t}isAudioSupported(e){return aa(e,`audio`,this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return aa(e,`video`,this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,n,r,i){let a=[],o=[],s=e,c=t.stats?.parsing||{};if((n||r)&&i&&(s=s.filter(({videoCodec:e,videoRange:t,width:n,height:r})=>(!!e||!!(n&&r))&&Fa(t))),s.length===0){Promise.resolve().then(()=>{if(this.hls){let e=`no level with compatible codecs found in manifest`,n=e;t.levels.length&&(n=`one or more CODECS in variant not supported: ${Y(t.levels.map(e=>e.attrs.CODECS).filter((e,t,n)=>n.indexOf(e)===t))}`,this.warn(n),e+=` (${n})`);let r=Error(e);this.hls.trigger(B.ERROR,{type:R.MEDIA_ERROR,details:z.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:r,reason:n})}}),c.end=performance.now();return}t.audioTracks&&(a=t.audioTracks.filter(e=>!e.audioCodec||this.isAudioSupported(e.audioCodec)),zm(a)),t.subtitles&&(o=t.subtitles,zm(o));let l=s.slice(0);s.sort((e,t)=>{if(e.attrs[`HDCP-LEVEL`]!==t.attrs[`HDCP-LEVEL`])return(e.attrs[`HDCP-LEVEL`]||``)>(t.attrs[`HDCP-LEVEL`]||``)?1:-1;if(n&&e.height!==t.height)return e.height-t.height;if(e.frameRate!==t.frameRate)return e.frameRate-t.frameRate;if(e.videoRange!==t.videoRange)return Pa.indexOf(e.videoRange)-Pa.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){let n=ca(e.videoCodec),r=ca(t.videoCodec);if(n!==r)return r-n}if(e.uri===t.uri&&e.codecSet!==t.codecSet){let n=la(e.codecSet),r=la(t.codecSet);if(n!==r)return r-n}return e.averageBitrate===t.averageBitrate?0:e.averageBitrate-t.averageBitrate});let u=l[0];if(this.steering&&(s=this.steering.filterParsedLevels(s),s.length!==l.length)){for(let e=0;e<l.length;e++)if(l[e].pathwayId===s[0].pathwayId){u=l[e];break}}this._levels=s;for(let e=0;e<s.length;e++)if(s[e]===u){this._firstLevel=e;let t=u.bitrate,n=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${s.length} level(s) found, first bitrate: ${t}`),this.hls.userConfig?.abrEwmaDefaultEstimate===void 0){let e=Math.min(t,this.hls.config.abrEwmaDefaultEstimateMax);e>n&&n===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=e)}break}let d=i&&!r,f=this.hls.config,p=!!(f.audioStreamController&&f.audioTrackController),m={levels:s,audioTracks:a,subtitleTracks:o,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:i,video:r,altAudio:p&&!d&&a.some(e=>!!e.url)};c.end=performance.now(),this.hls.trigger(B.MANIFEST_PARSED,m)}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){let t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){let n=Error(`invalid level idx`),r=e<0;if(this.hls.trigger(B.ERROR,{type:R.OTHER_ERROR,details:z.LEVEL_SWITCH_ERROR,level:e,fatal:r,error:n,reason:n.message}),r)return;e=Math.min(e,t.length-1)}let n=this.currentLevelIndex,r=this.currentLevel,i=r?r.attrs[`PATHWAY-ID`]:void 0,a=t[e],o=a.attrs[`PATHWAY-ID`];if(this.currentLevelIndex=e,this.currentLevel=a,n===e&&r&&i===o)return;this.log(`Switching to level ${e} (${a.height?a.height+`p `:``}${a.videoRange?a.videoRange+` `:``}${a.codecSet?a.codecSet+` `:``}@${a.bitrate})${o?` with Pathway `+o:``} from level ${n}${i?` with Pathway `+i:``}`);let s={level:e,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger(B.LEVEL_SWITCHING,s);let c=a.details;if(!c||c.live){let e=this.switchParams(a.uri,r?.details,c);this.loadPlaylist(e)}}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){let e=this.hls.config.startLevel;return e===void 0?this.hls.firstAutoLevel:e}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){let t=this.steering.pathways(),n=e.filter(e=>t.indexOf(e)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=n}}onError(e,t){t.fatal||!t.context||t.context.type===V.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===H.MAIN){let e=t.elementaryStreams;if(!Object.keys(e).some(t=>!!e[t]))return;let 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 n;let{level:r,details:i}=t,a=t.levelInfo;if(!a){var o;this.warn(`Invalid level index ${r}`),(o=t.deliveryDirectives)!=null&&o.skip&&(i.deltaUpdateFailed=!0);return}if(a===this.currentLevel||t.withoutMultiVariant){a.fragmentError===0&&(a.loadError=0);let e=a.details;e===t.details&&e.advanced&&(e=void 0),this.playlistLoaded(r,t,e)}else (n=t.deliveryDirectives)!=null&&n.skip&&(i.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let n=this.getUrlWithDirectives(e.uri,t),r=this.currentLevelIndex,i=e.attrs[`PATHWAY-ID`],a=e.details,o=a?.age;this.log(`Loading level index ${r}${t?.msn===void 0?``:` at sn `+t.msn+` part `+t.part}${i?` Pathway `+i:``}${o&&a.live?` age `+o.toFixed(1)+(a.type&&` `+a.type||``):``} ${n}`),this.hls.trigger(B.LEVEL_LOADING,{url:n,level:r,levelInfo:e,pathwayId:e.attrs[`PATHWAY-ID`],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return this.manualLevelIndex===-1?this.hls.nextAutoLevel:this.manualLevelIndex}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(this._levels.length===1)return;let n=this._levels.filter((t,n)=>n===e?(this.steering&&this.steering.removeLevel(t),t===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,t.details&&t.details.fragments.forEach(e=>e.level=-1)),!1):!0);uc(n),this._levels=n,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);let r=n.length-1;this._firstLevel=Math.min(this._firstLevel,r),this._startLevel&&=Math.min(this._startLevel,r),this.hls.trigger(B.LEVELS_UPDATED,{levels:n})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){let{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:n}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(B.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:n}))}};function zm(e){let t={};e.forEach(e=>{let n=e.groupId||``;e.id=t[n]=t[n]||0,t[n]++})}function Bm(){return self.SourceBuffer||self.WebKitSourceBuffer}function Vm(){if(!ai())return!1;let e=Bm();return!e||e.prototype&&typeof e.prototype.appendBuffer==`function`&&typeof e.prototype.remove==`function`}function Hm(){if(!Vm())return!1;let e=ai();return typeof e?.isTypeSupported==`function`&&([`avc1.42E01E,mp4a.40.2`,`av01.0.01M.08`,`vp09.00.50.08`].some(t=>e.isTypeSupported(sa(t,`video`)))||[`mp4a.40.2`,`fLaC`].some(t=>e.isTypeSupported(sa(t,`audio`))))}function Um(){var e;let t=Bm();return typeof(t==null||(e=t.prototype)==null?void 0:e.changeType)==`function`}var Wm=100,Gm=class extends Cc{constructor(e,t,n){super(e,t,n,`stream-controller`,H.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=()=>{let e=this.media,t=e?e.currentTime:null;if(t===null||!L(t)||(this.log(`Media seeked to ${t.toFixed(3)}`),!this.getBufferedFrag(t)))return;let n=this.getFwdBufferInfoAtPos(e,t,H.MAIN,0);if(n===null||n.len===0){this.warn(`Main forward buffer length at ${t} on "seeked" event ${n?n.len:`empty`})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(B.MANIFEST_PARSED,this.onManifestParsed,this),e.on(B.LEVEL_LOADING,this.onLevelLoading,this),e.on(B.LEVEL_LOADED,this.onLevelLoaded,this),e.on(B.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(B.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(B.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(B.BUFFER_CREATED,this.onBufferCreated,this),e.on(B.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(B.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(B.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(B.MANIFEST_PARSED,this.onManifestParsed,this),e.off(B.LEVEL_LOADED,this.onLevelLoaded,this),e.off(B.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(B.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(B.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(B.BUFFER_CREATED,this.onBufferCreated,this),e.off(B.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(B.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(B.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){let{lastCurrentTime:n,hls:r}=this;if(this.stopLoad(),this.setInterval(Wm),this.level=-1,!this.startFragRequested){let e=r.startLevel;e===-1&&(r.config.testBandwidth&&this.levels.length>1?(e=0,this.bitrateTest=!0):e=r.firstAutoLevel),r.nextLoadLevel=e,this.level=r.loadLevel,this._hasEnoughToStart=!!t}n>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${n.toFixed(3)}`),e=n),this.state=Z.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=Z.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case Z.WAITING_LEVEL:{let{levels:e,level:t}=this,n=e?.[t],r=n?.details;if(r&&(!r.live||this.levelLastLoaded===n&&!this.waitForLive(n))){if(this.waitForCdnTuneIn(r))break;this.state=Z.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=Z.IDLE;break}break}case Z.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===Z.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(){let{hls:e,levelLastLoaded:t,levels:n,media:r}=this;if(t===null||!r&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;let i=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(n!=null&&n[i]))return;let a=n[i],o=this.getMainFwdBufferInfo();if(o===null)return;let s=this.getLevelDetails();if(s&&this._streamEnded(o,s)){let e={};this.altAudio===2&&(e.type=`video`),this.hls.trigger(B.BUFFER_EOS,e),this.state=Z.ENDED;return}if(!this.buffering)return;e.loadLevel!==i&&e.manualLevel===-1&&this.log(`Adapting to level ${i} from level ${this.level}`),this.level=e.nextLoadLevel=i;let c=a.details;if(!c||this.state===Z.WAITING_LEVEL||this.waitForLive(a)){this.level=i,this.state=Z.WAITING_LEVEL,this.startFragRequested=!1;return}let l=o.len,u=this.getMaxBufferLength(a.maxBitrate);if(l>=u)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);let d=this.backtrackFragment?this.backtrackFragment.start:o.end,f=this.getNextFragment(d,c);if(this.couldBacktrack&&!this.fragPrevious&&f&&vi(f)&&this.fragmentTracker.getState(f)!==To.OK){let e=(this.backtrackFragment??f).sn-c.startSN,t=c.fragments[e-1];t&&f.cc===t.cc&&(f=t,this.fragmentTracker.removeFragment(t))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,d)){if(!f.gap){let e=this.audioOnly&&!this.altAudio?K.AUDIO:K.VIDEO,t=(e===K.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;t&&this.afterBufferFlushed(t,e,H.MAIN)}f=this.getNextFragmentLoopLoading(f,c,o,H.MAIN,u)}f&&(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,a,d))}loadFragment(e,t,n){let r=this.fragmentTracker.getState(e);r===To.NOT_LOADED||r===To.PARTIAL?vi(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,n):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,H.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,1/0)}nextLevelSwitch(){let{levels:e,media:t}=this;if(t!=null&&t.readyState){let n,r=this.getAppendedFrag(t.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.start-1);let i=this.getLevelDetails();if(i!=null&&i.live){let e=this.getMainFwdBufferInfo();if(!e||e.len<i.targetduration*2)return}if(!t.paused&&e){let t=e[this.hls.nextLoadLevel],r=this.fragLastKbps;n=r&&this.fragCurrent?this.fragCurrent.duration*t.maxBitrate/(1e3*r)+1:0}else n=0;let a=this.getBufferedFrag(t.currentTime+n);if(a){let e=this.followingBufferedFrag(a);if(e){this.abortCurrentFrag();let t=e.maxStartPTS?e.maxStartPTS:e.start,n=e.duration,r=Math.max(a.end,t+Math.min(Math.max(n-this.config.maxFragLookUpTolerance,n*(this.couldBacktrack?.5:.125)),n*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(r,1/0)}}}}abortCurrentFrag(){let e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case Z.KEY_LOADING:case Z.FRAG_LOADING:case Z.FRAG_LOADING_WAITING_RETRY:case Z.PARSING:case Z.PARSED:this.state=Z.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);let n=t.media;bc(n,`playing`,this.onMediaPlaying),bc(n,`seeked`,this.onMediaSeeked)}onMediaDetaching(e,t){let{media:n}=this;n&&(xc(n,`playing`,this.onMediaPlaying),xc(n,`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(B.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 n=!1,r=!1;for(let e=0;e<t.levels.length;e++){let i=t.levels[e].audioCodec;i&&(n||=i.indexOf(`mp4a.40.2`)!==-1,r||=i.indexOf(`mp4a.40.5`)!==-1)}this.audioCodecSwitch=n&&r&&!Um(),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){let{levels:n}=this;if(!n||this.state!==Z.IDLE)return;let r=t.levelInfo;(!r.details||r.details.live&&(this.levelLastLoaded!==r||r.details.expired)||this.waitForCdnTuneIn(r.details))&&(this.state=Z.WAITING_LEVEL)}onLevelLoaded(e,t){var n;let{levels:r,startFragRequested:i}=this,a=t.level,o=t.details,s=o.totalduration;if(!r){this.warn(`Levels were reset while loading level ${a}`);return}this.log(`Level ${a} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:``}, cc [${o.startCC}, ${o.endCC}] duration:${s}`);let c=t.levelInfo,l=this.fragCurrent;l&&(this.state===Z.FRAG_LOADING||this.state===Z.FRAG_LOADING_WAITING_RETRY)&&l.level!==t.level&&l.loader&&this.abortCurrentFrag();let u=0;if(o.live||(n=c.details)!=null&&n.live){if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;u=this.alignPlaylists(o,c.details,this.levelLastLoaded?.details)}if(c.details=o,this.levelLastLoaded=c,i||this.setStartPosition(o,u),this.hls.trigger(B.LEVEL_UPDATED,{details:o,level:a}),this.state===Z.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=Z.IDLE}i&&o.live&&this.synchronizeToLiveEdge(o),this.tick()}synchronizeToLiveEdge(e){let{config:t,media:n}=this;if(!n)return;let r=this.hls.liveSyncPosition,i=this.getLoadPosition(),a=e.fragmentStart,o=e.edge,s=i>=a-t.maxFragLookUpTolerance&&i<=o;if(r!==null&&n.duration>r&&(i<r||!s)){let a=t.liveMaxLatencyDuration===void 0?t.liveMaxLatencyDurationCount*e.targetduration:t.liveMaxLatencyDuration;if((!s&&n.readyState<4||i<o-a)&&(this._hasEnoughToStart||(this.nextLoadPosition=r),n.readyState))if(this.warn(`Playback: ${i.toFixed(3)} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${r.toFixed(3)}`),this.config.liveSyncMode===`buffered`){var c;let e=X.bufferInfo(n,r,0);if(!((c=e.buffered)!=null&&c.length)){n.currentTime=r;return}if(e.start<=i){n.currentTime=r;return}let{nextStart:t}=X.bufferedInfo(e.buffered,i,0);t&&(n.currentTime=t)}else n.currentTime=r}}_handleFragmentLoadProgress(e){let t=e.frag,{part:n,payload:r}=e,{levels:i}=this;if(!i){this.warn(`Levels were reset while fragment load was in progress. Fragment ${t.sn} of level ${t.level} will not be buffered`);return}let a=i[t.level];if(!a){this.warn(`Level ${t.level} not found on progress`);return}let o=a.details;if(!o){this.warn(`Dropping fragment ${t.sn} of level ${t.level} after level details were reset`),this.fragmentTracker.removeFragment(t);return}let s=a.videoCodec,c=o.PTSKnown||!o.live,l=t.initSegment?.data,u=this._getAudioCodec(a),d=this.transmuxer=this.transmuxer||new Nu(this.hls,H.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=n?n.index:-1,p=f!==-1,m=new Go(t.level,t.sn,t.stats.chunkCount,r.byteLength,f,p),h=this.initPTS[t.cc];d.push(r,l,u,s,t,n,o.totalduration,c,m,h)}onAudioTrackSwitching(e,t){let n=this.hls,r=this.altAudio!==0;if(no(t.url,n))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;let e=this.fragCurrent;e&&(this.log(`Switching to main audio track, cancel main fragment load`),e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(r){this.altAudio=0,this.fragmentTracker.removeAllFragments(),n.once(B.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(B.AUDIO_TRACK_SWITCHED,t)}),n.trigger(B.BUFFER_FLUSHING,{startOffset:0,endOffset:1/0,type:null});return}n.trigger(B.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){let n=no(t.url,this.hls);if(n){let e=this.videoBuffer;e&&this.mediaBuffer!==e&&(this.log(`Switching on alternate audio, use video.buffered to schedule main fragment loading`),this.mediaBuffer=e)}this.altAudio=n?2:0,this.tick()}onBufferCreated(e,t){let n=t.tracks,r,i,a=!1;for(let e in n){let t=n[e];if(t.id===`main`){if(i=e,r=t,e===`video`){let t=n[e];t&&(this.videoBuffer=t.buffer)}}else a=!0}a&&r?(this.log(`Alternate track found, use ${i}.buffered to schedule main fragment loading`),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){let{frag:n,part:r}=t,i=n.type===H.MAIN;if(i){if(this.fragContextChanged(n)){this.warn(`Fragment ${n.sn}${r?` p: `+r.index:``} of level ${n.level} finished buffering, but was aborted. state: ${this.state}`),this.state===Z.PARSED&&(this.state=Z.IDLE);return}let e=r?r.stats:n.stats;this.fragLastKbps=Math.round(8*e.total/(e.buffering.end-e.loading.first)),vi(n)&&(this.fragPrevious=n),this.fragBufferedComplete(n,r)}let a=this.media;a&&(!this._hasEnoughToStart&&X.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),i&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){if(t.fatal){this.state=Z.ERROR;return}switch(t.details){case z.FRAG_GAP:case z.FRAG_PARSING_ERROR:case z.FRAG_DECRYPT_ERROR:case z.FRAG_LOAD_ERROR:case z.FRAG_LOAD_TIMEOUT:case z.KEY_LOAD_ERROR:case z.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(H.MAIN,t);break;case z.LEVEL_LOAD_ERROR:case z.LEVEL_LOAD_TIMEOUT:case z.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===Z.WAITING_LEVEL&&t.context?.type===V.LEVEL&&(this.state=Z.IDLE);break;case z.BUFFER_ADD_CODEC_ERROR:case z.BUFFER_APPEND_ERROR:if(t.parent!==`main`)return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case z.BUFFER_FULL_ERROR:if(t.parent!==`main`)return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,1/0));break;case z.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=Z.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==K.AUDIO||!this.altAudio){let e=(t===K.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;e&&(this.afterBufferFlushed(e,t,H.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(){let{media:e}=this;if(!e)return;let t=e.currentTime,n=this.startPosition;if(n>=0&&t<n){if(e.seeking){this.log(`could not seek to ${n}, already seeking at ${t}`);return}let r=this.timelineOffset;r&&n&&(n+=r);let i=this.getLevelDetails(),a=X.getBuffered(e),o=a.length?a.start(0):0,s=o-n,c=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||s>0&&(s<c||this.loadingParts&&s<2*(i?.partTarget||0)))&&(this.log(`adjusting start position by ${s} to match buffer start`),n+=s,this.startPosition=n),t<n&&(this.log(`seek to target start position ${n} from current time ${t} buffer start ${o}`),e.currentTime=n)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log(`Swapping audio codec`),t=t.indexOf(`mp4a.40.5`)===-1?`mp4a.40.5`:`mp4a.40.2`),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(e=>{let{hls:n}=this,r=e?.frag;if(!r||this.fragContextChanged(r))return;t.fragmentError=0,this.state=Z.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;let i=r.stats;i.parsing.start=i.parsing.end=i.buffering.start=i.buffering.end=self.performance.now(),n.trigger(B.FRAG_LOADED,e),r.bitrateTest=!1}).catch(t=>{this.state===Z.STOPPED||this.state===Z.ERROR||(this.warn(t),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){let t=this.playlistType,{hls:n}=this,{remuxResult:r,chunkMeta:i}=e,a=this.getCurrentContext(i);if(!a){this.resetWhenMissingContext(i);return}let{frag:o,part:s,level:c}=a,{video:l,text:u,id3:d,initSegment:f}=r,{details:p}=c,m=this.altAudio?void 0:r.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=Z.PARSING,f){let e=f.tracks;if(e){let r=o.initSegment||o;if(this.unhandledEncryptionError(f,o))return;this._bufferInitSegment(c,e,r,i),n.trigger(B.FRAG_PARSING_INIT_SEGMENT,{frag:r,id:t,tracks:e})}let r=f.initPTS,a=f.timescale,s=this.initPTS[o.cc];if(L(r)&&(!s||s.baseTime!==r||s.timescale!==a)){let e=f.trackId;this.initPTS[o.cc]={baseTime:r,timescale:a,trackId:e},n.trigger(B.INIT_PTS_FOUND,{frag:o,id:t,initPTS:r,timescale:a,trackId:e})}}if(l&&p){m&&l.type===`audiovideo`&&this.logMuxedErr(o);let e=p.fragments[o.sn-1-p.startSN],t=o.sn===p.startSN,n=!e||o.cc>e.cc;if(r.independent!==!1){let{startPTS:e,endPTS:r,startDTS:a,endDTS:c}=l;if(s)s.elementaryStreams[l.type]={startPTS:e,endPTS:r,startDTS:a,endDTS:c};else if(l.firstKeyFrame&&l.independent&&i.id===1&&!n&&(this.couldBacktrack=!0),l.dropped&&l.independent){let i=this.getMainFwdBufferInfo(),a=(i?i.end:this.getLoadPosition())+this.config.maxBufferHole,s=l.firstKeyFramePTS?l.firstKeyFramePTS:e;if(!t&&a<s-this.config.maxBufferHole&&!n){this.backtrack(o);return}else n&&(o.gap=!0);o.setElementaryStreamInfo(l.type,o.start,r,o.start,c,!0)}else t&&e-(p.appliedTimelineOffset||0)>wm&&(o.gap=!0);o.setElementaryStreamInfo(l.type,e,r,a,c),this.backtrackFragment&&=o,this.bufferFragmentData(l,o,s,i,t||n)}else if(t||n)o.gap=!0;else{this.backtrack(o);return}}if(m){let{startPTS:e,endPTS:t,startDTS:n,endDTS:r}=m;s&&(s.elementaryStreams[K.AUDIO]={startPTS:e,endPTS:t,startDTS:n,endDTS:r}),o.setElementaryStreamInfo(K.AUDIO,e,t,n,r),this.bufferFragmentData(m,o,s,i)}if(p&&d!=null&&d.samples.length){let e={id:t,frag:o,details:p,samples:d.samples};n.trigger(B.FRAG_PARSING_METADATA,e)}if(p&&u){let e={id:t,frag:o,details:p,samples:u.samples};n.trigger(B.FRAG_PARSING_USERDATA,e)}}logMuxedErr(e){this.warn(`${vi(e)?`Media`:`Init`} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,n,r){if(this.state!==Z.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(n));let{audio:i,video:a,audiovideo:o}=t;if(i){let n=e.audioCodec,r=ha(i.codec,n);r===`mp4a`&&(r=`mp4a.40.5`);let a=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){r&&=r.indexOf(`mp4a.40.5`)===-1?`mp4a.40.5`:`mp4a.40.2`;let e=i.metadata;e&&`channelCount`in e&&(e.channelCount||1)!==1&&a.indexOf(`firefox`)===-1&&(r=`mp4a.40.5`)}r&&r.indexOf(`mp4a.40.5`)!==-1&&a.indexOf(`android`)!==-1&&i.container!==`audio/mpeg`&&(r=`mp4a.40.2`,this.log(`Android: force audio codec to ${r}`)),n&&n!==r&&this.log(`Swapping manifest audio codec "${n}" for "${r}"`),i.levelCodec=r,i.id=H.MAIN,this.log(`Init audio buffer, container:${i.container}, codecs[selected/level/parsed]=[${r||``}/${n||``}/${i.codec}]`),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=H.MAIN;let n=a.codec;if(n?.length===4)switch(n){case`hvc1`:case`hev1`:a.codec=`hvc1.1.6.L120.90`;break;case`av01`:a.codec=`av01.0.04M.08`;break;case`avc1`:a.codec=`avc1.42e01e`;break}this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||``}/${n}]${a.codec===n?``:` parsed-corrected=`+a.codec}${a.supplemental?` supplemental=`+a.supplemental:``}`),delete t.audiovideo}o&&(this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),delete t.video,delete t.audio);let s=Object.keys(t);if(s.length){if(this.hls.trigger(B.BUFFER_CODECS,t),!this.hls)return;s.forEach(e=>{let i=t[e].initSegment;i!=null&&i.byteLength&&this.hls.trigger(B.BUFFER_APPENDING,{type:e,data:i,frag:n,part:null,chunkMeta:r,parent:n.type})})}this.tickImmediate()}getMainFwdBufferInfo(){let e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,H.MAIN)}get maxBufferLength(){let{levels:e,level:t}=this,n=e?.[t];return n?this.getMaxBufferLength(n.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=Z.IDLE}checkFragmentChanged(){let e=this.media,t=null;if(e&&e.readyState>1&&e.seeking===!1){let n=e.currentTime;if(X.isBuffered(e,n)?t=this.getAppendedFrag(n):X.isBuffered(e,n+.1)&&(t=this.getAppendedFrag(n+.1)),t){this.backtrackFragment=null;let e=this.fragPlaying,n=t.level;(!e||t.sn!==e.sn||e.level!==n)&&(this.fragPlaying=t,this.hls.trigger(B.FRAG_CHANGED,{frag:t}),(!e||e.level!==n)&&this.hls.trigger(B.LEVEL_SWITCHED,{level:n}))}}}get nextLevel(){let e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){if(this.fragPlaying)return this.fragPlaying;let e=this.media?.currentTime||this.lastCurrentTime;return L(e)?this.getAppendedFrag(e):null}get currentProgramDateTime(){let e=this.media?.currentTime||this.lastCurrentTime;if(L(e)){let t=this.getLevelDetails(),n=this.currentFrag||(t?oo(null,t.fragments,e):null);if(n){let t=n.programDateTime;if(t!==null){let r=t+(e-n.start)*1e3;return new Date(r)}}}return null}get currentLevel(){let e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){let e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}},Km=class extends Zr{constructor(e,t){super(`key-loader`,t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(let t in this.keyIdToKeyInfo){let n=this.keyIdToKeyInfo[t].loader;if(n){if(e&&e!==n.context?.frag.type)return;n.abort()}}}detach(){for(let e in this.keyIdToKeyInfo){let t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){this.detach();for(let e in this.keyIdToKeyInfo){let t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,t=z.KEY_LOAD_ERROR,n,r,i){return new Uo({type:R.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:i,error:n,networkDetails:r})}loadClear(e,t,n){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let r=0,i=t.length;r<i;r++){let a=t[r];if(e.cc<=a.cc&&(!vi(e)||!vi(a)||e.sn<a.sn)||!n&&r==i-1)return this.emeController.selectKeySystemFormat(a).then(e=>{if(!this.emeController)return;a.setKeyFormat(e);let t=bs(e);if(t)return this.emeController.getKeySystemAccess([t])})}if(this.config.requireKeySystemAccessOnStart){let e=Ss(this.config);if(e.length)return this.emeController.getKeySystemAccess(e)}}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 n,r;t&&e.setKeyFormat(t);let i=e.decryptdata;if(!i){let n=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,z.KEY_LOAD_ERROR,n))}let a=i.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,z.KEY_LOAD_ERROR,Error(`Invalid key URI: "${a}"`)));let o=qm(i),s=this.keyIdToKeyInfo[o];if((n=s)!=null&&n.decryptdata.key)return i.key=s.decryptdata.key,Promise.resolve({frag:e,keyInfo:s});if(this.emeController&&(r=s)!=null&&r.keyLoadPromise)switch(this.emeController.getKeyStatus(s.decryptdata)){case`usable`:case`usable-in-future`:return s.keyLoadPromise.then(t=>{let{keyInfo:n}=t;return i.key=n.decryptdata.key,{frag:e,keyInfo:n}})}switch(this.log(`${this.keyIdToKeyInfo[o]?`Rel`:`L`}oading${i.keyId?` keyId: `+li(i.keyId):``} URI: ${i.uri} from ${e.type} ${e.level}`),s=this.keyIdToKeyInfo[o]={decryptdata:i,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},i.method){case`SAMPLE-AES`:case`SAMPLE-AES-CENC`:case`SAMPLE-AES-CTR`:return i.keyFormat===`identity`?this.loadKeyHTTP(s,e):this.loadKeyEME(s,e);case`AES-128`:case`AES-256`:case`AES-256-CTR`:return this.loadKeyHTTP(s,e);default:return Promise.reject(this.createKeyLoadError(e,z.KEY_LOAD_ERROR,Error(`Key supplied with unsupported METHOD: "${i.method}"`)))}}loadKeyEME(e,t){let n={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var r;if(!e.decryptdata.keyId&&(r=t.initSegment)!=null&&r.data){let n=Bi(t.initSegment.data);if(n.length){let t=n[0];t.some(e=>e!==0)?(this.log(`Using keyId found in init segment ${li(t)}`),ks.setKeyIdForUri(e.decryptdata.uri,t)):(t=ks.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${li(t)}`)),e.decryptdata.keyId=t}}return!e.decryptdata.keyId&&!vi(t)?Promise.resolve(n):(e.keyLoadPromise=this.emeController.loadKey(n).then(t=>(e.mediaKeySessionContext=t,n))).catch(n=>{throw e.keyLoadPromise=null,`data`in n&&(n.data.frag=t),n})}return Promise.resolve(n)}loadKeyHTTP(e,t){let n=this.config,r=n.loader,i=new r(n);return t.keyLoader=e.loader=i,e.keyLoadPromise=new Promise((r,a)=>{let o={keyInfo:e,frag:t,responseType:`arraybuffer`,url:e.decryptdata.uri},s=n.keyLoadPolicy.default,c={loadPolicy:s,timeout:s.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};i.load(o,c,{onSuccess:(e,t,n,i)=>{let{frag:o,keyInfo:s}=n,c=qm(s.decryptdata);if(!o.decryptdata||s!==this.keyIdToKeyInfo[c])return a(this.createKeyLoadError(o,z.KEY_LOAD_ERROR,Error(`after key load, decryptdata unset or changed`),i));s.decryptdata.key=o.decryptdata.key=new Uint8Array(e.data),o.keyLoader=null,s.loader=null,r({frag:o,keyInfo:s})},onError:(e,n,r,i)=>{this.resetLoader(n),a(this.createKeyLoadError(t,z.KEY_LOAD_ERROR,Error(`HTTP Error ${e.code} loading key ${e.text}`),r,W({url:o.url,data:void 0},e)))},onTimeout:(e,n,r)=>{this.resetLoader(n),a(this.createKeyLoadError(t,z.KEY_LOAD_TIMEOUT,Error(`key loading timed out`),r))},onAbort:(e,n,r)=>{this.resetLoader(n),a(this.createKeyLoadError(t,z.INTERNAL_ABORTED,Error(`key loading aborted`),r))}})})}resetLoader(e){let{frag:t,keyInfo:n,url:r}=e,i=n.loader;t.keyLoader===i&&(t.keyLoader=null,n.loader=null);let a=qm(n.decryptdata)||r;delete this.keyIdToKeyInfo[a],i&&i.destroy()}};function qm(e){if(e.keyFormat!==ys.FAIRPLAY){let t=e.keyId;if(t)return li(t)}return e.uri}function Jm(e){let{type:t}=e;switch(t){case V.AUDIO_TRACK:return H.AUDIO;case V.SUBTITLE_TRACK:return H.SUBTITLE;default:return H.MAIN}}function Ym(e,t){let n=e.url;return(n===void 0||n.indexOf(`data:`)===0)&&(n=t.url),n}var Xm=class{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(){let{hls:e}=this;e.on(B.MANIFEST_LOADING,this.onManifestLoading,this),e.on(B.LEVEL_LOADING,this.onLevelLoading,this),e.on(B.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(B.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(B.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){let{hls:e}=this;e.off(B.MANIFEST_LOADING,this.onManifestLoading,this),e.off(B.LEVEL_LOADING,this.onLevelLoading,this),e.off(B.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(B.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(B.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){let t=this.hls.config,n=t.pLoader,r=t.loader,i=new(n||r)(t);return this.loaders[e.type]=i,i}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(let e in this.loaders){let t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){let{url:n}=t;this.variableList=null,this.load({id:null,level:0,responseType:`text`,type:V.MANIFEST,url:n,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){let{id:n,level:r,pathwayId:i,url:a,deliveryDirectives:o,levelInfo:s}=t;this.load({id:n,level:r,pathwayId:i,responseType:`text`,type:V.LEVEL,url:a,deliveryDirectives:o,levelOrTrack:s})}onAudioTrackLoading(e,t){let{id:n,groupId:r,url:i,deliveryDirectives:a,track:o}=t;this.load({id:n,groupId:r,level:null,responseType:`text`,type:V.AUDIO_TRACK,url:i,deliveryDirectives:a,levelOrTrack:o})}onSubtitleTrackLoading(e,t){let{id:n,groupId:r,url:i,deliveryDirectives:a,track:o}=t;this.load({id:n,groupId:r,level:null,responseType:`text`,type:V.SUBTITLE_TRACK,url:i,deliveryDirectives:a,levelOrTrack:o})}onLevelsUpdated(e,t){let n=this.loaders[V.LEVEL];if(n){let e=n.context;e&&!t.levels.some(t=>t===e.levelOrTrack)&&(n.abort(),delete this.loaders[V.LEVEL])}}load(e){let t=this.hls.config,n=this.getInternalLoader(e);if(n){let t=this.hls.logger,r=n.context;if(r&&r.levelOrTrack===e.levelOrTrack&&(r.url===e.url||r.deliveryDirectives&&!e.deliveryDirectives)){r.url===e.url?t.log(`[playlist-loader]: ignore ${e.url} ongoing request`):t.log(`[playlist-loader]: ignore ${e.url} in favor of ${r.url}`);return}t.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),n.abort()}let r;if(r=e.type===V.MANIFEST?t.manifestLoadPolicy.default:U({},t.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),n=this.createInternalLoader(e),L(e.deliveryDirectives?.part)){let t;if(e.type===V.LEVEL&&e.level!==null?t=this.hls.levels[e.level].details:e.type===V.AUDIO_TRACK&&e.id!==null?t=this.hls.audioTracks[e.id].details:e.type===V.SUBTITLE_TRACK&&e.id!==null&&(t=this.hls.subtitleTracks[e.id].details),t){let e=t.partTarget,n=t.targetduration;if(e&&n){let t=Math.max(e*3,n*.8)*1e3;r=U({},r,{maxTimeToFirstByteMs:Math.min(t,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(t,r.maxTimeToFirstByteMs)})}}}let i=r.errorRetry||r.timeoutRetry||{},a={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:i.maxNumRetry||0,retryDelay:i.retryDelayMs||0,maxRetryDelay:i.maxRetryDelayMs||0};n.load(e,a,{onSuccess:(e,t,n,r)=>{let i=this.getInternalLoader(n);this.resetInternalLoader(n.type);let a=e.data;t.parsing.start=performance.now(),Rs.isMediaPlaylist(a)||n.type!==V.MANIFEST?this.handleTrackOrLevelPlaylist(e,t,n,r||null,i):this.handleMasterPlaylist(e,t,n,r)},onError:(e,t,n,r)=>{this.handleNetworkError(t,n,!1,e,r)},onTimeout:(e,t,n)=>{this.handleNetworkError(t,n,!0,void 0,e)}})}checkAutostartLoad(){if(!this.hls)return;let{config:{autoStartLoad:e,startPosition:t},forceStartLoad:n}=this.hls;(e||n)&&(this.hls.logger.log(`${e?`auto`:`force`} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,n,r){let i=this.hls,a=e.data,o=Ym(e,n),s=Rs.parseMasterPlaylist(a,o);if(s.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,n,s.playlistParsingError,r,t);return}let{contentSteering:c,levels:l,sessionData:u,sessionKeys:d,startTimeOffset:f,variableList:p}=s;this.variableList=p,l.forEach(e=>{let{unknownCodecs:t}=e;if(t){let{preferManagedMediaSource:n}=this.hls.config,{audioCodec:r,videoCodec:i}=e;for(let a=t.length;a--;){let o=t[a];aa(o,`audio`,n)?(e.audioCodec=r=r?`${r},${o}`:o,ra.audio[r.substring(0,4)]=2,t.splice(a,1)):aa(o,`video`,n)&&(e.videoCodec=i=i?`${i},${o}`:o,ra.video[i.substring(0,4)]=2,t.splice(a,1))}}});let{AUDIO:m=[],SUBTITLES:h,"CLOSED-CAPTIONS":g}=Rs.parseMasterPlaylistMedia(a,o,s);m.length&&!m.some(e=>!e.url)&&l[0].audioCodec&&!l[0].attrs.AUDIO&&(this.hls.logger.log(`[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one`),m.unshift({type:`main`,name:`main`,groupId:`main`,default:!1,autoselect:!1,forced:!1,id:-1,attrs:new ts({}),bitrate:0,url:``})),i.trigger(B.MANIFEST_LOADED,{levels:l,audioTracks:m,subtitles:h,captions:g,contentSteering:c,url:o,stats:t,networkDetails:r,sessionData:u,sessionKeys:d,startTimeOffset:f,variableList:p})}handleTrackOrLevelPlaylist(e,t,n,r,i){let a=this.hls,{id:o,level:s,type:c}=n,l=Ym(e,n),u=L(s)?s:L(o)?o:0,d=Jm(n),f=Rs.parseLevelPlaylist(e.data,l,u,d,0,this.variableList);if(c===V.MANIFEST){let e={attrs:new ts({}),bitrate:0,details:f,name:``,url:l};f.requestScheduled=t.loading.start+oc(f,0),a.trigger(B.MANIFEST_LOADED,{levels:[e],audioTracks:[],url:l,stats:t,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),n.levelDetails=f,this.handlePlaylistLoaded(f,e,t,n,r,i)}handleManifestParsingError(e,t,n,r,i){this.hls.trigger(B.ERROR,{type:R.NETWORK_ERROR,details:z.MANIFEST_PARSING_ERROR,fatal:t.type===V.MANIFEST,url:e.url,err:n,error:n,reason:n.message,response:e,context:t,networkDetails:r,stats:i})}handleNetworkError(e,t,n=!1,r,i){let a=`A network ${n?`timeout`:`error`+(r?` (status `+r.code+`)`:``)} occurred while loading ${e.type}`;e.type===V.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===V.AUDIO_TRACK||e.type===V.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);let o=Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let s=z.UNKNOWN,c=!1,l=this.getInternalLoader(e);switch(e.type){case V.MANIFEST:s=n?z.MANIFEST_LOAD_TIMEOUT:z.MANIFEST_LOAD_ERROR,c=!0;break;case V.LEVEL:s=n?z.LEVEL_LOAD_TIMEOUT:z.LEVEL_LOAD_ERROR,c=!1;break;case V.AUDIO_TRACK:s=n?z.AUDIO_TRACK_LOAD_TIMEOUT:z.AUDIO_TRACK_LOAD_ERROR,c=!1;break;case V.SUBTITLE_TRACK:s=n?z.SUBTITLE_TRACK_LOAD_TIMEOUT:z.SUBTITLE_LOAD_ERROR,c=!1;break}l&&this.resetInternalLoader(e.type);let u={type:R.NETWORK_ERROR,details:s,fatal:c,url:e.url,loader:l,context:e,error:o,networkDetails:t,stats:i};r&&(u.response=W({url:t?.url||e.url,data:void 0},r)),this.hls.trigger(B.ERROR,u)}handlePlaylistLoaded(e,t,n,r,i,a){let o=this.hls,{type:s,level:c,levelOrTrack:l,id:u,groupId:d,deliveryDirectives:f}=r,p=Ym(t,r),m=Jm(r),h=typeof r.level==`number`&&m===H.MAIN?c:void 0,g=e.playlistParsingError;if(g){if(this.hls.logger.warn(`${g} ${e.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(B.ERROR,{type:R.NETWORK_ERROR,details:z.LEVEL_PARSING_ERROR,fatal:!1,url:p,error:g,reason:g.message,response:t,context:r,level:h,parent:m,networkDetails:i,stats:n});return}e.playlistParsingError=null}if(!e.fragments.length){let a=e.playlistParsingError=Error(`No Segments found in Playlist`);o.trigger(B.ERROR,{type:R.NETWORK_ERROR,details:z.LEVEL_EMPTY_ERROR,fatal:!1,url:p,error:a,reason:a.message,response:t,context:r,level:h,parent:m,networkDetails:i,stats:n});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),s){case V.MANIFEST:case V.LEVEL:if(h){if(!l)h=0;else if(l!==o.levels[h]){let e=o.levels.indexOf(l);e>-1&&(h=e)}}o.trigger(B.LEVEL_LOADED,{details:e,levelInfo:l||o.levels[0],level:h||0,id:u||0,stats:n,networkDetails:i,deliveryDirectives:f,withoutMultiVariant:s===V.MANIFEST});break;case V.AUDIO_TRACK:o.trigger(B.AUDIO_TRACK_LOADED,{details:e,track:l,id:u||0,groupId:d||``,stats:n,networkDetails:i,deliveryDirectives:f});break;case V.SUBTITLE_TRACK:o.trigger(B.SUBTITLE_TRACK_LOADED,{details:e,track:l,id:u||0,groupId:d||``,stats:n,networkDetails:i,deliveryDirectives:f});break}}},Zm=class e{static get version(){return jc}static isMSESupported(){return Vm()}static isSupported(){return Hm()}static getMediaSource(){return ai()}static get Events(){return B}static get MetadataSchema(){return _l}static get ErrorTypes(){return R}static get ErrorDetails(){return z}static get DefaultConfig(){return e.defaultConfig?e.defaultConfig:ym}static set DefaultConfig(t){e.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Ac,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;let n=this.logger=ii(t.debug||!1,`Hls instance`,t.assetPlayerId),r=this.config=xm(e.DefaultConfig,t,n);this.userConfig=t,r.progressive&&Cm(r,n);let{abrController:i,bufferController:a,capLevelController:o,errorController:s,fpsController:c}=r,l=new s(this),u=this.abrController=new i(this),d=new Eo(this),f=r.interstitialsController,p=f?this.interstitialsController=new f(this,e):null,m=this.bufferController=new a(this,d),h=this.capLevelController=new o(this),g=new c(this),_=new Xm(this),v=r.contentSteeringController,y=v?new v(this):null,b=this.levelController=new Rm(this,y),x=new Im(this),S=new Km(this.config,this.logger),C=this.streamController=new Gm(this,d,S),w=this.gapController=new Om(this,d);h.setStreamController(C),g.setStreamController(C);let T=[_,b,C];p&&T.splice(1,0,p),y&&T.splice(1,0,y),this.networkControllers=T;let E=[u,m,w,h,g,x,d];this.audioTrackController=this.createController(r.audioTrackController,T);let ee=r.audioStreamController;ee&&T.push(this.audioStreamController=new ee(this,d,S)),this.subtitleTrackController=this.createController(r.subtitleTrackController,T);let D=r.subtitleStreamController;D&&T.push(this.subtititleStreamController=new D(this,d,S)),this.createController(r.timelineController,E),S.emeController=this.emeController=this.createController(r.emeController,E),this.cmcdController=this.createController(r.cmcdController,E),this.latencyController=this.createController(Lm,E),this.coreComponents=E,T.push(l);let te=l.onErrorOut;typeof te==`function`&&this.on(B.ERROR,te,l),this.on(B.MANIFEST_LOADED,_.onManifestLoaded,_)}createController(e,t){if(e){let n=new e(this);return t&&t.push(n),n}return null}on(e,t,n=this){this._emitter.on(e,t,n)}once(e,t,n=this){this._emitter.once(e,t,n)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,n=this,r){this._emitter.off(e,t,n,r)}listeners(e){return this._emitter.listeners(e)}emit(e,t,n){return this._emitter.emit(e,t,n)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(t){if(this.logger.error(`An internal error happened while handling event `+e+`. Error message: "`+t.message+`". Here is a stacktrace:`,t),!this.triggeringException){this.triggeringException=!0;let n=e===B.ERROR;this.trigger(B.ERROR,{type:R.OTHER_ERROR,details:z.INTERNAL_EXCEPTION,fatal:n,event:e,error:t}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log(`destroy`),this.trigger(B.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(e=>e.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(e=>e.destroy()),this.coreComponents.length=0;let e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||`media`in e&&!e.media){let t=Error(`attachMedia failed: invalid argument (${e})`);this.trigger(B.ERROR,{type:R.OTHER_ERROR,details:z.ATTACH_MEDIA_ERROR,fatal:!0,error:t});return}this.logger.log(`attachMedia`),this._media&&(this.logger.warn(`media must be detached before attaching`),this.detachMedia());let t=`media`in e,n=t?e.media:e,r=t?e:{media:n};this._media=n,this.trigger(B.MEDIA_ATTACHING,r)}detachMedia(){this.logger.log(`detachMedia`),this.trigger(B.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;let e=this.bufferController.transferMedia();return this.trigger(B.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();let t=this.media,n=this._url,r=this._url=hi.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${r}`),t&&n&&(n!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(B.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 n=0;n<this.networkControllers.length&&(this.networkControllers[n].startLoad(e,t),!(!this.started||!this.networkControllers));n++);}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(){let e={[H.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[H.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[H.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log(`swapAudioCodec`),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log(`recoverMediaError`);let e=this._media,t=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||=this._sessionId=If(),e}get levels(){return this.levelController.levels||[]}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(){let 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){let 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(){let{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){let{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){let{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){Na(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(){let{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;let n=e.length;for(let r=0;r<n;r++)if(e[r].maxBitrate>=t)return r;return 0}get maxAutoLevel(){let{levels:e,autoLevelCapping:t,maxHdcpLevel:n}=this,r;if(r=t===-1&&e!=null&&e.length?e.length-1:t,n)for(let t=r;t--;){let r=e[t].attrs[`HDCP-LEVEL`];if(r&&r<=n)return t}return r}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){return this.audioTrackController?.setAudioOption(e)||null}setSubtitleOption(e){return this.subtitleTrackController?.setSubtitleOption(e)||null}get allAudioTracks(){let e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){let e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){let e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){let t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){let e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){let e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){let e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){let t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){let e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){let 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(){return this.interstitialsController?.interstitialsManager||null}getMediaDecodingInfo(e,t=this.allAudioTracks){return Ea(e,Ka(t),navigator.mediaCapabilities)}};Zm.defaultConfig=void 0;var Qm=class{constructor(e){if(this.terminated=!1,this.restartPause=2e3,this.ws=null,this.pc=null,this.restartTimeout=null,!e?.videoElement)throw Error(`videoElement is required`);if(!e.wsUri)throw Error(`wsUri is required`);this.wsUri=e.wsUri,this.videoElement=e.videoElement,this.onOnline=e.onOnline,this.onOffline=e.onOffline}start(){console.log(`connecting`),this.ws=new WebSocket(this.wsUri),this.ws.onerror=()=>{console.log(`ws error`),this.ws!==null&&(this.ws.close(),this.ws=null)},this.ws.onclose=()=>{console.log(`ws closed`),this.ws=null,this.onOffline(),this.scheduleRestart()},this.ws.onmessage=e=>this.onIceServers(e)}onIceServers(e){if(this.ws===null)return;let t=JSON.parse(e.data);this.pc=new RTCPeerConnection({iceServers:t}),this.ws.onmessage=e=>this.onRemoteDescription(e),this.pc.onicecandidate=e=>this.onIceCandidate(e),this.pc.oniceconnectionstatechange=()=>{if(this.pc!==null)switch(console.log(`peer connection state:`,this.pc.iceConnectionState),this.pc.iceConnectionState){case`connected`:this.pc.onicecandidate=void 0,this.ws.onmessage=void 0,this.ws.onerror=void 0,this.ws.onclose=void 0,this.onOnline();break;case`disconnected`:this.scheduleRestart(),this.onOffline()}},this.pc.ontrack=e=>{console.log(`new track `+e.track.kind),this.videoElement.srcObject=e.streams[0]};let n=`sendrecv`;this.pc.addTransceiver(`video`,{direction:n}),this.pc.addTransceiver(`audio`,{direction:n}),this.pc.createOffer().then(e=>{this.pc===null||this.ws===null||(this.pc.setLocalDescription(e),console.log(`sending offer`),this.ws.send(JSON.stringify(e)))})}onRemoteDescription(e){this.pc===null||this.ws===null||(this.pc.setRemoteDescription(new RTCSessionDescription(JSON.parse(e.data))),this.ws.onmessage=e=>this.onRemoteCandidate(e))}onIceCandidate(e){this.ws!==null&&e.candidate!==null&&e.candidate.candidate!==``&&this.ws.send(JSON.stringify(e.candidate))}onRemoteCandidate(e){this.pc!==null&&this.pc.addIceCandidate(JSON.parse(e.data))}scheduleRestart(){this.terminated||(this.ws!==null&&(this.ws.close(),this.ws=null),this.pc!==null&&(this.pc.close(),this.pc=null),this.restartTimeout=window.setTimeout(()=>{this.restartTimeout=null,this.start()},this.restartPause))}},Q=function(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)},$m,$,eh,th,nh,rh,ih,ah,oh,sh,ch,lh,uh,dh,fh,ph,mh,hh,gh,_h,vh,yh,bh,xh,Sh,Ch=class{constructor(e){$m.add(this),this.retryPause=2e3,this.state=`getting_codecs`,this.restartTimeout=null,this.pc=null,this.offerData=null,this.sessionUrl=null,this.queuedCandidates=[],this.nonAdvertisedCodecs=[],this.conf=e,Q(this,$m,`m`,fh).call(this)}close(){this.state=`closed`,this.pc!==null&&this.pc.close(),this.restartTimeout!==null&&clearTimeout(this.restartTimeout)}};$=Ch,$m=new WeakSet,eh=function(e,t){return new Promise(n=>{let r=new RTCPeerConnection({iceServers:[]}),i=`audio`,a=``;r.addTransceiver(i,{direction:`recvonly`}),r.createOffer().then(n=>{if(n.sdp===void 0)throw Error(`SDP not present`);if(n.sdp.includes(` ${e}`))throw Error(`already present`);let o=n.sdp.split(`m=${i}`),s=o.slice(1).map(e=>e.split(`\r
42
+ `)[0].split(` `).slice(3)).reduce((e,t)=>[...e,...t],[]);a=Q(this,$,`m`,ih).call(this,s);let c=o[1].split(`\r
43
+ `);return c[0]+=` ${a}`,c.splice(c.length-1,0,`a=rtpmap:${a} ${e}`),t!==void 0&&c.splice(c.length-1,0,`a=fmtp:${a} ${t}`),o[1]=c.join(`\r
44
+ `),n.sdp=o.join(`m=${i}`),r.setLocalDescription(n)}).then(()=>r.setRemoteDescription(new RTCSessionDescription({type:`answer`,sdp:`v=0\r
45
45
  o=- 6539324223450680508 0 IN IP4 0.0.0.0\r
46
46
  s=-\r
47
47
  t=0 0\r
48
48
  a=fingerprint:sha-256 0D:9F:78:15:42:B5:4B:E6:E2:94:3E:5B:37:78:E1:4B:54:59:A3:36:3A:E5:05:EB:27:EE:8F:D2:2D:41:29:25\r
49
- m=${n} 9 UDP/TLS/RTP/SAVPF ${a}\r
50
- c=IN IP4 0.0.0.0\r
49
+ m=${i} 9 UDP/TLS/RTP/SAVPF ${a}\r\nc=IN IP4 0.0.0.0\r
51
50
  a=ice-pwd:7c3bf4770007e7432ee4ea4d697db675\r
52
51
  a=ice-ufrag:29e036dc\r
53
52
  a=sendonly\r
54
53
  a=rtcp-mux\r
55
- a=rtpmap:${a} ${e}\r
56
- `+(t!==void 0?`a=fmtp:${a} ${t}\r
57
- `:"")}))).then(()=>{s(!0)}).catch(()=>{s(!1)}).finally(()=>{i.close()})})},zn=function(e){return JSON.parse(`"${e}"`)},su=function(e){return e!==null?e.split(", ").map(t=>{const s=t.match(/^<(.+?)>; rel="ice-server"(; username="(.*?)"; credential="(.*?)"; credential-type="password")?/i),i={urls:[s[1]]};return s[3]!==void 0&&(i.username=Q(this,me,"m",zn).call(this,s[3]),i.credential=Q(this,me,"m",zn).call(this,s[4]),i.credentialType="password"),i}):[]},iu=function(e){const t={iceUfrag:"",icePwd:"",medias:[]};for(const s of e.split(`\r
58
- `))s.startsWith("m=")?t.medias.push(s.slice(2)):t.iceUfrag===""&&s.startsWith("a=ice-ufrag:")?t.iceUfrag=s.slice(12):t.icePwd===""&&s.startsWith("a=ice-pwd:")&&(t.icePwd=s.slice(10));return t},Ze=function(e){for(let t=30;t<=127;t++)if((t<=63||t>=96)&&!e.includes(t.toString())){const s=t.toString();return e.push(s),s}throw Error("unable to find a free payload type")},ru=function(e,t){const s=t.split(`\r
59
- `);let i=Q(this,me,"m",Ze).call(this,e);return s[0]+=` ${i}`,s.splice(s.length-1,0,`a=rtpmap:${i} PCMU/8000/2`),s.splice(s.length-1,0,`a=rtcp-fb:${i} transport-cc`),i=Q(this,me,"m",Ze).call(this,e),s[0]+=` ${i}`,s.splice(s.length-1,0,`a=rtpmap:${i} PCMA/8000/2`),s.splice(s.length-1,0,`a=rtcp-fb:${i} transport-cc`),s.join(`\r
60
- `)},nu=function(e,t){const s=t.split(`\r
61
- `);let i=Q(this,me,"m",Ze).call(this,e);return s[0]+=` ${i}`,s.splice(s.length-1,0,`a=rtpmap:${i} multiopus/48000/3`),s.splice(s.length-1,0,`a=fmtp:${i} channel_mapping=0,2,1;num_streams=2;coupled_streams=1`),s.splice(s.length-1,0,`a=rtcp-fb:${i} transport-cc`),i=Q(this,me,"m",Ze).call(this,e),s[0]+=` ${i}`,s.splice(s.length-1,0,`a=rtpmap:${i} multiopus/48000/4`),s.splice(s.length-1,0,`a=fmtp:${i} channel_mapping=0,1,2,3;num_streams=2;coupled_streams=2`),s.splice(s.length-1,0,`a=rtcp-fb:${i} transport-cc`),i=Q(this,me,"m",Ze).call(this,e),s[0]+=` ${i}`,s.splice(s.length-1,0,`a=rtpmap:${i} multiopus/48000/5`),s.splice(s.length-1,0,`a=fmtp:${i} channel_mapping=0,4,1,2,3;num_streams=3;coupled_streams=2`),s.splice(s.length-1,0,`a=rtcp-fb:${i} transport-cc`),i=Q(this,me,"m",Ze).call(this,e),s[0]+=` ${i}`,s.splice(s.length-1,0,`a=rtpmap:${i} multiopus/48000/6`),s.splice(s.length-1,0,`a=fmtp:${i} channel_mapping=0,4,1,2,3,5;num_streams=4;coupled_streams=2`),s.splice(s.length-1,0,`a=rtcp-fb:${i} transport-cc`),i=Q(this,me,"m",Ze).call(this,e),s[0]+=` ${i}`,s.splice(s.length-1,0,`a=rtpmap:${i} multiopus/48000/7`),s.splice(s.length-1,0,`a=fmtp:${i} channel_mapping=0,4,1,2,3,5,6;num_streams=4;coupled_streams=4`),s.splice(s.length-1,0,`a=rtcp-fb:${i} transport-cc`),i=Q(this,me,"m",Ze).call(this,e),s[0]+=` ${i}`,s.splice(s.length-1,0,`a=rtpmap:${i} multiopus/48000/8`),s.splice(s.length-1,0,`a=fmtp:${i} channel_mapping=0,6,1,4,5,2,3,7;num_streams=5;coupled_streams=4`),s.splice(s.length-1,0,`a=rtcp-fb:${i} transport-cc`),s.join(`\r
62
- `)},au=function(e,t){const s=t.split(`\r
63
- `);let i=Q(this,me,"m",Ze).call(this,e);return s[0]+=` ${i}`,s.splice(s.length-1,0,`a=rtpmap:${i} L16/8000/2`),s.splice(s.length-1,0,`a=rtcp-fb:${i} transport-cc`),i=Q(this,me,"m",Ze).call(this,e),s[0]+=` ${i}`,s.splice(s.length-1,0,`a=rtpmap:${i} L16/16000/2`),s.splice(s.length-1,0,`a=rtcp-fb:${i} transport-cc`),i=Q(this,me,"m",Ze).call(this,e),s[0]+=` ${i}`,s.splice(s.length-1,0,`a=rtpmap:${i} L16/48000/2`),s.splice(s.length-1,0,`a=rtcp-fb:${i} transport-cc`),s.join(`\r
64
- `)},ou=function(e){let t="";const s=e.split(`\r
65
- `);for(let i=0;i<s.length;i++)if(s[i].startsWith("a=rtpmap:")&&s[i].toLowerCase().includes("opus/")){t=s[i].slice(9).split(" ")[0];break}if(t==="")return e;for(let i=0;i<s.length;i++)s[i].startsWith(`a=fmtp:${t} `)&&(s[i].includes("stereo")||(s[i]+=";stereo=1"),s[i].includes("sprop-stereo")||(s[i]+=";sprop-stereo=1"));return s.join(`\r
66
- `)},lu=function(e,t){const s=e.split("m="),i=s.slice(1).map(n=>n.split(`\r
67
- `)[0].split(" ").slice(3)).reduce((n,a)=>[...n,...a],[]);for(let n=1;n<s.length;n++)if(s[n].startsWith("audio")){s[n]=Q(this,me,"m",ou).call(this,s[n]),t.includes("pcma/8000/2")&&(s[n]=Q(this,me,"m",ru).call(this,i,s[n])),t.includes("multiopus/48000/6")&&(s[n]=Q(this,me,"m",nu).call(this,i,s[n])),t.includes("L16/48000/2")&&(s[n]=Q(this,me,"m",au).call(this,i,s[n]));break}return s.join("m=")},cu=function(e,t){const s={};for(const a of t){const o=a.sdpMLineIndex;o!==null&&s[o]===void 0&&(s[o]=[]),o!==null&&s[o].push(a)}let i=`a=ice-ufrag:${e.iceUfrag}\r
68
- a=ice-pwd:${e.icePwd}\r
69
- `,n=0;for(const a of e.medias){if(s[n]!==void 0){i+=`m=${a}\r
70
- a=mid:${n}\r
71
- `;for(const o of s[n])i+=`a=${o.candidate}\r
72
- `}n++}return i},fi=function(e){this.state==="running"?(this.pc!==null&&(this.pc.close(),this.pc=null),this.offerData=null,this.sessionUrl!==null&&(fetch(this.sessionUrl,{method:"DELETE"}),this.sessionUrl=null),this.queuedCandidates=[],this.state="restarting",this.restartTimeout=window.setTimeout(()=>{this.restartTimeout=null,this.state="running",Q(this,_e,"m",Qn).call(this)},this.retryPause),this.conf.onError!==void 0&&this.conf.onError(`${e}, retrying in some seconds`)):this.state==="getting_codecs"&&(this.state="failed",this.conf.onError!==void 0&&this.conf.onError(e))},uu=function(){Promise.all([["pcma/8000/2"],["multiopus/48000/6","channel_mapping=0,4,1,2,3,5;num_streams=4;coupled_streams=2"],["L16/48000/2"]].map(e=>Q(at,me,"m",tu).call(at,e[0],e[1]).then(t=>t?e[0]:!1))).then(e=>e.filter(t=>t!==!1)).then(e=>{if(this.state!=="getting_codecs")throw new Error("closed");this.nonAdvertisedCodecs=e,this.state="running",Q(this,_e,"m",Qn).call(this)}).catch(e=>{Q(this,_e,"m",fi).call(this,e)})},Qn=function(){Q(this,_e,"m",hu).call(this).then(e=>Q(this,_e,"m",du).call(this,e)).then(e=>Q(this,_e,"m",fu).call(this,e)).then(e=>Q(this,_e,"m",gu).call(this,e)).catch(e=>{Q(this,_e,"m",fi).call(this,e.toString())})},Jn=function(){return this.conf.user!==void 0&&this.conf.user!==""?{Authorization:`Basic ${btoa(`${this.conf.user}:${this.conf.pass}`)}`}:this.conf.token!==void 0&&this.conf.token!==""?{Authorization:`Bearer ${this.conf.token}`}:{}},hu=function(){return fetch(this.conf.url,{method:"OPTIONS",headers:Q(this,_e,"m",Jn).call(this)}).then(e=>Q(at,me,"m",su).call(at,e.headers.get("Link")))},du=function(e){if(this.state!=="running")throw new Error("closed");this.pc=new RTCPeerConnection({iceServers:e});const t="recvonly";return this.pc.addTransceiver("video",{direction:t}),this.pc.addTransceiver("audio",{direction:t}),this.pc.onicecandidate=s=>Q(this,_e,"m",mu).call(this,s),this.pc.onconnectionstatechange=()=>Q(this,_e,"m",pu).call(this),this.pc.ontrack=s=>Q(this,_e,"m",yu).call(this,s),this.pc.createOffer().then(s=>{if(!s.sdp)throw new Error("SDP not present");return s.sdp=Q(at,me,"m",lu).call(at,s.sdp,this.nonAdvertisedCodecs),this.offerData=Q(at,me,"m",iu).call(at,s.sdp),this.pc.setLocalDescription(s).then(()=>s.sdp)})},fu=function(e){if(this.state!=="running")throw new Error("closed");return fetch(this.conf.url,{method:"POST",headers:{...Q(this,_e,"m",Jn).call(this),"Content-Type":"application/sdp"},body:e}).then(t=>{switch(t.status){case 201:break;case 404:throw new Error("stream not found");case 400:return t.json().then(i=>{throw new Error(i.error)});default:throw new Error(`bad status code ${t.status}`)}const s=t.headers.get("location");if(!s)throw new Error("No location header in response");return this.sessionUrl=new URL(s,this.conf.url).toString(),t.text()})},gu=function(e){if(this.state!=="running")throw new Error("closed");return this.pc.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})).then(()=>{this.state==="running"&&this.queuedCandidates.length!==0&&(Q(this,_e,"m",Zn).call(this,this.queuedCandidates),this.queuedCandidates=[])})},mu=function(e){this.state==="running"&&e.candidate!==null&&(this.sessionUrl===null?this.queuedCandidates.push(e.candidate):Q(this,_e,"m",Zn).call(this,[e.candidate]))},Zn=function(e){if(!this.sessionUrl)throw new Error("Session URL not available");fetch(this.sessionUrl,{method:"PATCH",headers:{"Content-Type":"application/trickle-ice-sdpfrag","If-Match":"*"},body:Q(at,me,"m",cu).call(at,this.offerData,e)}).then(t=>{switch(t.status){case 204:break;case 404:throw new Error("stream not found");default:throw new Error(`bad status code ${t.status}`)}}).catch(t=>{Q(this,_e,"m",fi).call(this,t.toString())})},pu=function(){this.state==="running"&&this.pc&&(this.pc.connectionState==="failed"||this.pc.connectionState==="closed")&&Q(this,_e,"m",fi).call(this,"peer connection closed")},yu=function(e){this.conf.onTrack!==void 0&&this.conf.onTrack(e)};var zp=Qt('<video id="video" part="video" class="video svelte-8tcri8" autoplay=""><track kind="captions" src="" srclang="en" label="English" default=""/></video>',2),Qp=Qt('<div style="flex: 1"><div class="subsection svelte-8tcri8"><div><!></div></div></div> <div style="flex:1"><div class="subsection svelte-8tcri8"><div style="flex:1"><div class="subsection svelte-8tcri8"><div><!></div></div></div> <div style="flex:1"><div class="subsection svelte-8tcri8"><div><!></div></div></div></div></div>',1),Jp=Qt('<div style="flex: 1"><div class="subsection svelte-8tcri8"><div><!></div></div></div> <div style="flex:1"><div class="subsection svelte-8tcri8"><div style="flex:1"><div class="subsection svelte-8tcri8"><div><!></div></div></div></div></div>',1),Zp=Qt('<div style="flex: 1"><div class="subsection svelte-8tcri8"><div><!></div></div></div>'),e0=Qt('<div part="replacewithtext" class="replacetext video svelte-8tcri8"><!></div>'),t0=Qt('<div class="replacetext video svelte-8tcri8" part="replacewithtext">offline</div>'),s0=Qt('<div class="replacetext video svelte-8tcri8" part="replacewithtext">nouri</div>'),i0=Qt('<div part="container" style="width: 100%;position:relative"><!> <!></div>');const r0={hash:"svelte-8tcri8",code:'@import url("https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap");:host {font-family:"Roboto", sans-serif;}.replacetext.svelte-8tcri8 {position:absolute;width:100%;height:100%;top:0px;}.video.svelte-8tcri8 {width:100%;background-color:black;color:white;display:flex;align-items:center;justify-content:center;flex-direction:column;aspect-ratio:16/9;margin:auto;}.subsection.svelte-8tcri8 {display:flex;height:100%;align-items:center;justify-content:center;flex-direction:column;}'};function vu(r,e){da(e,!0),Kh(r,r0);let t=ws(e,"id",7,""),s=ws(e,"mediauri"),i=ws(e,"forcecover",7,void 0),n=ws(e,"media_type",7,"auto"),a=ws(e,"no_controls",7,!1),o=ws(e,"replacewithtext",7,void 0),c=Ge(void 0),l=Ge(!1),u=Ge(void 0),h=Ge(void 0),d=Ge(void 0),g=Ge(void 0);Fa(()=>{if(a()&&a()!=="no"&&a()!=="false"&&a(!0),typeof o()=="string")try{o(JSON.parse(o()))}catch{}s()&&re(g)&&s()!==re(g)&&(de(g,s(),!0),re(h)&&(re(h).close(),de(h,void 0)),de(l,!1),de(c,void 0),re(d)&&p(re(d)),y().catch(()=>{console.error("merr")}).then(()=>{console.log("start live checker")}))});function f(A,x){e.$$host.dispatchEvent(new CustomEvent(A,{detail:x}))}function p(A){if(console.log("setttviiiii",n()),de(d,A,!0),f("htmlVideoInit",{htmlVideoElement:re(d),id:t()}),n()==="hls")if(A&&Dt.isSupported()){const x=new Dt({});x.loadSource(s()),x.attachMedia(A),x.on(Dt.Events.MEDIA_ATTACHED,function(){A.muted=!0;try{A.play()}catch(C){console.error("cannot autoplay",C)}})}else A?.canPlayType("application/vnd.apple.mpegurl")?(console.log("without Media Source Extensions"),A.src=s(),A.muted=!0,A.addEventListener("canplay",function(){try{A.play()}catch(x){console.error("cannot autoplay",x)}})):console.error("no hls support");else if(n()==="whep"){console.info("whep",s());try{let x=function(){console.info("offline whep"),f("liveStatus",{live:!1,id:t()}),de(l,!1)},C=function(M){console.info("online whep"),A.srcObject=M?.streams?.[0],f("liveStatus",{live:!0,id:t()}),de(l,!0)};console.info("whep",s()),de(h,new at({url:s(),onTrack:C,onError:x}),!0);try{A.muted=!0,A.play()}catch(M){console.error("cannot autoplay whep",M)}}catch(x){console.error("whep error ....",x)}}else if(n()==="webrtc"){console.info("webrtc",s());try{let x=function(){f("liveStatus",{live:!1,id:t()}),de(l,!1)},C=function(){f("liveStatus",{live:!0,id:t()}),de(l,!0)};de(u,new Xp({videoElement:A,wsUri:s(),onOnline:C,onOffline:x}),!0),re(u).start();try{A.muted=!0,A.play()}catch(M){console.error("cannot autoplay webrtc",M)}}catch(x){console.error("webrtc error ....",x)}}else console.error("unknown media type",n())}async function y(){function A(){console.log("reloading",re(l),s()),(!re(l)||!s())&&y().catch(x=>{console.error("reload uri",x)})}try{if(!s()){de(c,setTimeout(A,5e3),!0);return}if(n()==="hls"){console.info("checking live");const x=await fetch(s());if(!x||x.status&&(x.status>299||x.status<199))throw new Error("wrong uri");de(l,!0),f("liveStatus",{live:!0,id:t()})}else throw new Error("wrong media type")}catch{re(l)!==!1&&f("liveStatus",{live:!1,id:t()}),de(l,!1),de(c,setTimeout(A,5e3),!0)}}e.$$host.getVideoElement=()=>{if(re(d))return re(d)},Gh(()=>(de(g,s(),!0),y().catch(()=>{console.error("merr")}).then(()=>{console.log("start live checker")}),()=>{console.log("destroying player"),re(c)&&(console.log("destroy live checker"),clearTimeout(re(c))),re(h)&&re(h).close()}));var v={get id(){return t()},set id(A=""){t(A),ls()},get mediauri(){return s()},set mediauri(A){s(A),ls()},get forcecover(){return i()},set forcecover(A=void 0){i(A),ls()},get media_type(){return n()},set media_type(A="auto"){n(A),ls()},get no_controls(){return a()},set no_controls(A=!1){a(A),ls()},get replacewithtext(){return o()},set replacewithtext(A=void 0){o(A),ls()}},E=i0(),T=ge(E);{var S=A=>{var x=zp();Vh(x,C=>p?.(C)),cs(()=>x.controls=!a()),De(A,x)};Mr(T,A=>{s()&&n()&&A(S)})}var _=Ri(T,2);{var D=A=>{var x=e0(),C=ge(x);{var M=N=>{var w=kr(),U=Qs(w);Mt(U,e,"replacewithtext",{},F=>{var B=Qp(),W=Qs(B),k=ge(W),O=ge(k),q=ge(O);Mt(q,e,"replacetitle",{},Ut=>{var Gt=Cs();cs(()=>Ps(Gt,o()?.title||"")),De(Ut,Gt)}),fe(O),fe(k),fe(W);var Z=Ri(W,2),X=ge(Z),z=ge(X),Se=ge(z),ve=ge(Se),Ne=ge(ve);Mt(Ne,e,"replacesubtitle",{},Ut=>{var Gt=Cs();cs(()=>Ps(Gt,o()?.subtitle||"")),De(Ut,Gt)}),fe(ve),fe(Se),fe(z);var Me=Ri(z,2),$e=ge(Me),mr=ge($e),gi=ge(mr);Mt(gi,e,"replacetext",{},Ut=>{var Gt=Cs();cs(()=>Ps(Gt,o()?.text||"")),De(Ut,Gt)}),fe(mr),fe($e),fe(Me),fe(X),fe(Z),De(F,B)}),De(N,w)},K=N=>{var w=kr(),U=Qs(w);Mt(U,e,"replacewithtext",{},F=>{var B=Jp(),W=Qs(B),k=ge(W),O=ge(k),q=ge(O);Mt(q,e,"replacetitle",{},Me=>{var $e=Cs();cs(()=>Ps($e,o()?.title||"")),De(Me,$e)}),fe(O),fe(k),fe(W);var Z=Ri(W,2),X=ge(Z),z=ge(X),Se=ge(z),ve=ge(Se),Ne=ge(ve);Mt(Ne,e,"replacesubtitle",{},Me=>{var $e=Cs();cs(()=>Ps($e,o()?.subtitle||"")),De(Me,$e)}),fe(ve),fe(Se),fe(z),fe(X),fe(Z),De(F,B)}),De(N,w)},V=N=>{var w=kr(),U=Qs(w);Mt(U,e,"replacewithtext",{},F=>{var B=Zp(),W=ge(B),k=ge(W),O=ge(k);Mt(O,e,"replacetitle",{},q=>{var Z=Cs();cs(()=>Ps(Z,o()?.title||"")),De(q,Z)}),fe(k),fe(W),fe(B),De(F,B)}),De(N,w)};Mr(C,N=>{o()?.title&&o()?.subtitle&&o()?.text?N(M):o()?.title&&o()?.subtitle?N(K,1):o()?.title&&N(V,2)})}fe(x),De(A,x)},I=A=>{var x=t0();De(A,x)},b=A=>{var x=s0();De(A,x)};Mr(_,A=>{i()||s()&&!re(l)&&(o()?.title||o()?.subtitle||o()?.text)?A(D):s()&&!re(l)&&(!o()||!o().title&&!o().subtitle&&!o().text)?A(I,1):s()||A(b,2)})}return fe(E),De(r,E),fa(v)}customElements.define("hb-player-live",qh(vu,{id:{},mediauri:{},forcecover:{},media_type:{},no_controls:{},replacewithtext:{}},["replacewithtext","replacetitle","replacesubtitle","replacetext"],[],{mode:"open"})),ea.Component=vu,Object.defineProperty(ea,Symbol.toStringTag,{value:"Module"})})(this["player-live"]=this["player-live"]||{});
73
- //# sourceMappingURL=main.iife.js.map
54
+ a=rtpmap:${a} ${e}\r\n`+(t===void 0?``:`a=fmtp:${a} ${t}\r\n`)}))).then(()=>{n(!0)}).catch(()=>{n(!1)}).finally(()=>{r.close()})})},th=function(e){return JSON.parse(`"${e}"`)},nh=function(e){return e===null?[]:e.split(`, `).map(e=>{let t=e.match(/^<(.+?)>; rel="ice-server"(; username="(.*?)"; credential="(.*?)"; credential-type="password")?/i),n={urls:[t[1]]};return t[3]!==void 0&&(n.username=Q(this,$,`m`,th).call(this,t[3]),n.credential=Q(this,$,`m`,th).call(this,t[4]),n.credentialType=`password`),n})},rh=function(e){let t={iceUfrag:``,icePwd:``,medias:[]};for(let n of e.split(`\r
55
+ `))n.startsWith(`m=`)?t.medias.push(n.slice(2)):t.iceUfrag===``&&n.startsWith(`a=ice-ufrag:`)?t.iceUfrag=n.slice(12):t.icePwd===``&&n.startsWith(`a=ice-pwd:`)&&(t.icePwd=n.slice(10));return t},ih=function(e){for(let t=30;t<=127;t++)if((t<=63||t>=96)&&!e.includes(t.toString())){let n=t.toString();return e.push(n),n}throw Error(`unable to find a free payload type`)},ah=function(e,t){let n=t.split(`\r
56
+ `),r=Q(this,$,`m`,ih).call(this,e);return n[0]+=` ${r}`,n.splice(n.length-1,0,`a=rtpmap:${r} PCMU/8000/2`),n.splice(n.length-1,0,`a=rtcp-fb:${r} transport-cc`),r=Q(this,$,`m`,ih).call(this,e),n[0]+=` ${r}`,n.splice(n.length-1,0,`a=rtpmap:${r} PCMA/8000/2`),n.splice(n.length-1,0,`a=rtcp-fb:${r} transport-cc`),n.join(`\r
57
+ `)},oh=function(e,t){let n=t.split(`\r
58
+ `),r=Q(this,$,`m`,ih).call(this,e);return n[0]+=` ${r}`,n.splice(n.length-1,0,`a=rtpmap:${r} multiopus/48000/3`),n.splice(n.length-1,0,`a=fmtp:${r} channel_mapping=0,2,1;num_streams=2;coupled_streams=1`),n.splice(n.length-1,0,`a=rtcp-fb:${r} transport-cc`),r=Q(this,$,`m`,ih).call(this,e),n[0]+=` ${r}`,n.splice(n.length-1,0,`a=rtpmap:${r} multiopus/48000/4`),n.splice(n.length-1,0,`a=fmtp:${r} channel_mapping=0,1,2,3;num_streams=2;coupled_streams=2`),n.splice(n.length-1,0,`a=rtcp-fb:${r} transport-cc`),r=Q(this,$,`m`,ih).call(this,e),n[0]+=` ${r}`,n.splice(n.length-1,0,`a=rtpmap:${r} multiopus/48000/5`),n.splice(n.length-1,0,`a=fmtp:${r} channel_mapping=0,4,1,2,3;num_streams=3;coupled_streams=2`),n.splice(n.length-1,0,`a=rtcp-fb:${r} transport-cc`),r=Q(this,$,`m`,ih).call(this,e),n[0]+=` ${r}`,n.splice(n.length-1,0,`a=rtpmap:${r} multiopus/48000/6`),n.splice(n.length-1,0,`a=fmtp:${r} channel_mapping=0,4,1,2,3,5;num_streams=4;coupled_streams=2`),n.splice(n.length-1,0,`a=rtcp-fb:${r} transport-cc`),r=Q(this,$,`m`,ih).call(this,e),n[0]+=` ${r}`,n.splice(n.length-1,0,`a=rtpmap:${r} multiopus/48000/7`),n.splice(n.length-1,0,`a=fmtp:${r} channel_mapping=0,4,1,2,3,5,6;num_streams=4;coupled_streams=4`),n.splice(n.length-1,0,`a=rtcp-fb:${r} transport-cc`),r=Q(this,$,`m`,ih).call(this,e),n[0]+=` ${r}`,n.splice(n.length-1,0,`a=rtpmap:${r} multiopus/48000/8`),n.splice(n.length-1,0,`a=fmtp:${r} channel_mapping=0,6,1,4,5,2,3,7;num_streams=5;coupled_streams=4`),n.splice(n.length-1,0,`a=rtcp-fb:${r} transport-cc`),n.join(`\r
59
+ `)},sh=function(e,t){let n=t.split(`\r
60
+ `),r=Q(this,$,`m`,ih).call(this,e);return n[0]+=` ${r}`,n.splice(n.length-1,0,`a=rtpmap:${r} L16/8000/2`),n.splice(n.length-1,0,`a=rtcp-fb:${r} transport-cc`),r=Q(this,$,`m`,ih).call(this,e),n[0]+=` ${r}`,n.splice(n.length-1,0,`a=rtpmap:${r} L16/16000/2`),n.splice(n.length-1,0,`a=rtcp-fb:${r} transport-cc`),r=Q(this,$,`m`,ih).call(this,e),n[0]+=` ${r}`,n.splice(n.length-1,0,`a=rtpmap:${r} L16/48000/2`),n.splice(n.length-1,0,`a=rtcp-fb:${r} transport-cc`),n.join(`\r
61
+ `)},ch=function(e){let t=``,n=e.split(`\r
62
+ `);for(let e=0;e<n.length;e++)if(n[e].startsWith(`a=rtpmap:`)&&n[e].toLowerCase().includes(`opus/`)){t=n[e].slice(9).split(` `)[0];break}if(t===``)return e;for(let e=0;e<n.length;e++)n[e].startsWith(`a=fmtp:${t} `)&&(n[e].includes(`stereo`)||(n[e]+=`;stereo=1`),n[e].includes(`sprop-stereo`)||(n[e]+=`;sprop-stereo=1`));return n.join(`\r
63
+ `)},lh=function(e,t){let n=e.split(`m=`),r=n.slice(1).map(e=>e.split(`\r
64
+ `)[0].split(` `).slice(3)).reduce((e,t)=>[...e,...t],[]);for(let e=1;e<n.length;e++)if(n[e].startsWith(`audio`)){n[e]=Q(this,$,`m`,ch).call(this,n[e]),t.includes(`pcma/8000/2`)&&(n[e]=Q(this,$,`m`,ah).call(this,r,n[e])),t.includes(`multiopus/48000/6`)&&(n[e]=Q(this,$,`m`,oh).call(this,r,n[e])),t.includes(`L16/48000/2`)&&(n[e]=Q(this,$,`m`,sh).call(this,r,n[e]));break}return n.join(`m=`)},uh=function(e,t){let n={};for(let e of t){let t=e.sdpMLineIndex;t!==null&&n[t]===void 0&&(n[t]=[]),t!==null&&n[t].push(e)}let r=`a=ice-ufrag:${e.iceUfrag}\r\na=ice-pwd:${e.icePwd}\r\n`,i=0;for(let t of e.medias){if(n[i]!==void 0){r+=`m=${t}\r\na=mid:${i}\r\n`;for(let e of n[i])r+=`a=${e.candidate}\r\n`}i++}return r},dh=function(e){this.state===`running`?(this.pc!==null&&(this.pc.close(),this.pc=null),this.offerData=null,this.sessionUrl!==null&&(fetch(this.sessionUrl,{method:`DELETE`}),this.sessionUrl=null),this.queuedCandidates=[],this.state=`restarting`,this.restartTimeout=window.setTimeout(()=>{this.restartTimeout=null,this.state=`running`,Q(this,$m,`m`,ph).call(this)},this.retryPause),this.conf.onError!==void 0&&this.conf.onError(`${e}, retrying in some seconds`)):this.state===`getting_codecs`&&(this.state=`failed`,this.conf.onError!==void 0&&this.conf.onError(e))},fh=function(){Promise.all([[`pcma/8000/2`],[`multiopus/48000/6`,`channel_mapping=0,4,1,2,3,5;num_streams=4;coupled_streams=2`],[`L16/48000/2`]].map(e=>Q(Ch,$,`m`,eh).call(Ch,e[0],e[1]).then(t=>t?e[0]:!1))).then(e=>e.filter(e=>e!==!1)).then(e=>{if(this.state!==`getting_codecs`)throw Error(`closed`);this.nonAdvertisedCodecs=e,this.state=`running`,Q(this,$m,`m`,ph).call(this)}).catch(e=>{Q(this,$m,`m`,dh).call(this,e)})},ph=function(){Q(this,$m,`m`,hh).call(this).then(e=>Q(this,$m,`m`,gh).call(this,e)).then(e=>Q(this,$m,`m`,_h).call(this,e)).then(e=>Q(this,$m,`m`,vh).call(this,e)).catch(e=>{Q(this,$m,`m`,dh).call(this,e.toString())})},mh=function(){return this.conf.user!==void 0&&this.conf.user!==``?{Authorization:`Basic ${btoa(`${this.conf.user}:${this.conf.pass}`)}`}:this.conf.token!==void 0&&this.conf.token!==``?{Authorization:`Bearer ${this.conf.token}`}:{}},hh=function(){return fetch(this.conf.url,{method:`OPTIONS`,headers:Q(this,$m,`m`,mh).call(this)}).then(e=>Q(Ch,$,`m`,nh).call(Ch,e.headers.get(`Link`)))},gh=function(e){if(this.state!==`running`)throw Error(`closed`);this.pc=new RTCPeerConnection({iceServers:e});let t=`recvonly`;return this.pc.addTransceiver(`video`,{direction:t}),this.pc.addTransceiver(`audio`,{direction:t}),this.pc.onicecandidate=e=>Q(this,$m,`m`,yh).call(this,e),this.pc.onconnectionstatechange=()=>Q(this,$m,`m`,xh).call(this),this.pc.ontrack=e=>Q(this,$m,`m`,Sh).call(this,e),this.pc.createOffer().then(e=>{if(!e.sdp)throw Error(`SDP not present`);return e.sdp=Q(Ch,$,`m`,lh).call(Ch,e.sdp,this.nonAdvertisedCodecs),this.offerData=Q(Ch,$,`m`,rh).call(Ch,e.sdp),this.pc.setLocalDescription(e).then(()=>e.sdp)})},_h=function(e){if(this.state!==`running`)throw Error(`closed`);return fetch(this.conf.url,{method:`POST`,headers:{...Q(this,$m,`m`,mh).call(this),"Content-Type":`application/sdp`},body:e}).then(e=>{switch(e.status){case 201:break;case 404:throw Error(`stream not found`);case 400:return e.json().then(e=>{throw Error(e.error)});default:throw Error(`bad status code ${e.status}`)}let t=e.headers.get(`location`);if(!t)throw Error(`No location header in response`);return this.sessionUrl=new URL(t,this.conf.url).toString(),e.text()})},vh=function(e){if(this.state!==`running`)throw Error(`closed`);return this.pc.setRemoteDescription(new RTCSessionDescription({type:`answer`,sdp:e})).then(()=>{this.state===`running`&&this.queuedCandidates.length!==0&&(Q(this,$m,`m`,bh).call(this,this.queuedCandidates),this.queuedCandidates=[])})},yh=function(e){this.state===`running`&&e.candidate!==null&&(this.sessionUrl===null?this.queuedCandidates.push(e.candidate):Q(this,$m,`m`,bh).call(this,[e.candidate]))},bh=function(e){if(!this.sessionUrl)throw Error(`Session URL not available`);fetch(this.sessionUrl,{method:`PATCH`,headers:{"Content-Type":`application/trickle-ice-sdpfrag`,"If-Match":`*`},body:Q(Ch,$,`m`,uh).call(Ch,this.offerData,e)}).then(e=>{switch(e.status){case 204:break;case 404:throw Error(`stream not found`);default:throw Error(`bad status code ${e.status}`)}}).catch(e=>{Q(this,$m,`m`,dh).call(this,e.toString())})},xh=function(){this.state===`running`&&this.pc&&(this.pc.connectionState===`failed`||this.pc.connectionState===`closed`)&&Q(this,$m,`m`,dh).call(this,`peer connection closed`)},Sh=function(e){this.conf.onTrack!==void 0&&this.conf.onTrack(e)};var wh=gr(`<video id="video" part="video" class="video svelte-8tcri8" autoplay=""><track kind="captions" src="" srclang="en" label="English" default=""/></video>`,2),Th=gr(`<div style="flex: 1"><div class="subsection svelte-8tcri8"><div><!></div></div></div> <div style="flex:1"><div class="subsection svelte-8tcri8"><div style="flex:1"><div class="subsection svelte-8tcri8"><div><!></div></div></div> <div style="flex:1"><div class="subsection svelte-8tcri8"><div><!></div></div></div></div></div>`,1),Eh=gr(`<div style="flex: 1"><div class="subsection svelte-8tcri8"><div><!></div></div></div> <div style="flex:1"><div class="subsection svelte-8tcri8"><div style="flex:1"><div class="subsection svelte-8tcri8"><div><!></div></div></div></div></div>`,1),Dh=gr(`<div style="flex: 1"><div class="subsection svelte-8tcri8"><div><!></div></div></div>`),Oh=gr(`<div part="replacewithtext" class="replacetext video svelte-8tcri8"><!></div>`),kh=gr(`<div class="replacetext video svelte-8tcri8" part="replacewithtext">offline</div>`),Ah=gr(`<div class="replacetext video svelte-8tcri8" part="replacewithtext">nouri</div>`),jh=gr(`<div part="container" style="width: 100%;position:relative"><!> <!></div>`),Mh={hash:`svelte-8tcri8`,code:`@import url("https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap");:host {font-family:"Roboto", sans-serif;}.replacetext.svelte-8tcri8 {position:absolute;width:100%;height:100%;top:0px;}.video.svelte-8tcri8 {width:100%;background-color:black;color:white;display:flex;align-items:center;justify-content:center;flex-direction:column;aspect-ratio:16/9;margin:auto;}.subsection.svelte-8tcri8 {display:flex;height:100%;align-items:center;justify-content:center;flex-direction:column;}`};function Nh(e,t){Pe(t,!0),Pr(e,Mh);let n=Ir(t,`id`,7,``),r=Ir(t,`mediauri`,7),i=Ir(t,`forcecover`,7,void 0),a=Ir(t,`media_type`,7,`auto`),o=Ir(t,`no_controls`,7,!1),s=Ir(t,`replacewithtext`,7,void 0),c=Lt(void 0),l=Lt(!1),u=Lt(void 0),d=Lt(void 0),f=Lt(void 0),p=Lt(void 0);dn(()=>{if(o()&&o()!==`no`&&o()!==`false`&&o(!0),typeof s()==`string`)try{s(JSON.parse(s()))}catch{}r()&&I(p)&&r()!==I(p)&&(M(p,r(),!0),I(d)&&(I(d).close(),M(d,void 0)),M(l,!1),M(c,void 0),I(f)&&h(I(f)),g().catch(()=>{console.error(`merr`)}).then(()=>{console.log(`start live checker`)}))});function m(e,n){t.$$host.dispatchEvent(new CustomEvent(e,{detail:n}))}function h(e){if(console.log(`setttviiiii`,a()),M(f,e,!0),m(`htmlVideoInit`,{htmlVideoElement:I(f),id:n()}),a()===`hls`)if(e&&Zm.isSupported()){let t=new Zm({});t.loadSource(r()),t.attachMedia(e),t.on(Zm.Events.MEDIA_ATTACHED,function(){e.muted=!0;try{e.play()}catch(e){console.error(`cannot autoplay`,e)}})}else e?.canPlayType(`application/vnd.apple.mpegurl`)?(console.log(`without Media Source Extensions`),e.src=r(),e.muted=!0,e.addEventListener(`canplay`,function(){try{e.play()}catch(e){console.error(`cannot autoplay`,e)}})):console.error(`no hls support`);else if(a()===`whep`){console.info(`whep`,r());try{function t(){console.info(`offline whep`),m(`liveStatus`,{live:!1,id:n()}),M(l,!1)}function i(t){console.info(`online whep`),e.srcObject=t?.streams?.[0],m(`liveStatus`,{live:!0,id:n()}),M(l,!0)}console.info(`whep`,r()),M(d,new Ch({url:r(),onTrack:i,onError:t}),!0);try{e.muted=!0,e.play()}catch(e){console.error(`cannot autoplay whep`,e)}}catch(e){console.error(`whep error ....`,e)}}else if(a()===`webrtc`){console.info(`webrtc`,r());try{function t(){m(`liveStatus`,{live:!1,id:n()}),M(l,!1)}function i(){m(`liveStatus`,{live:!0,id:n()}),M(l,!0)}M(u,new Qm({videoElement:e,wsUri:r(),onOnline:i,onOffline:t}),!0),I(u).start();try{e.muted=!0,e.play()}catch(e){console.error(`cannot autoplay webrtc`,e)}}catch(e){console.error(`webrtc error ....`,e)}}else console.error(`unknown media type`,a())}async function g(){function e(){console.log(`reloading`,I(l),r()),(!I(l)||!r())&&g().catch(e=>{console.error(`reload uri`,e)})}try{if(!r()){M(c,setTimeout(e,5e3),!0);return}if(a()===`hls`){console.info(`checking live`);let e=await fetch(r());if(!e||e.status&&(e.status>299||e.status<199))throw Error(`wrong uri`);M(l,!0),m(`liveStatus`,{live:!0,id:n()})}else throw Error(`wrong media type`)}catch{I(l)!==!1&&m(`liveStatus`,{live:!1,id:n()}),M(l,!1),M(c,setTimeout(e,5e3),!0)}}t.$$host.getVideoElement=()=>{if(I(f))return I(f)},Ar(()=>(M(p,r(),!0),g().catch(()=>{console.error(`merr`)}).then(()=>{console.log(`start live checker`)}),()=>{console.log(`destroying player`),I(c)&&(console.log(`destroy live checker`),clearTimeout(I(c))),I(d)&&I(d).close()}));var _={get id(){return n()},set id(e=``){n(e),st()},get mediauri(){return r()},set mediauri(e){r(e),st()},get forcecover(){return i()},set forcecover(e=void 0){i(e),st()},get media_type(){return a()},set media_type(e=`auto`){a(e),st()},get no_controls(){return o()},set no_controls(e=!1){o(e),st()},get replacewithtext(){return s()},set replacewithtext(e=void 0){s(e),st()}},v=jh(),y=N(v),b=e=>{var t=wh();Fr(t,e=>h?.(e)),vn(()=>t.controls=!o()),yr(e,t)};Mr(y,e=>{r()&&a()&&e(b)});var x=$t(y,2),S=e=>{var n=Oh(),r=N(n),i=e=>{var n=vr();Nr(Qt(n),t,`replacewithtext`,{},e=>{var n=Th(),r=Qt(n),i=N(r),a=N(i);Nr(N(a),t,`replacetitle`,{},e=>{var t=_r();vn(()=>Sr(t,s()?.title||``)),yr(e,t)}),Ce(a),Ce(i),Ce(r);var o=$t(r,2),c=N(o),l=N(c),u=N(l),d=N(u);Nr(N(d),t,`replacesubtitle`,{},e=>{var t=_r();vn(()=>Sr(t,s()?.subtitle||``)),yr(e,t)}),Ce(d),Ce(u),Ce(l);var f=$t(l,2),p=N(f),m=N(p);Nr(N(m),t,`replacetext`,{},e=>{var t=_r();vn(()=>Sr(t,s()?.text||``)),yr(e,t)}),Ce(m),Ce(p),Ce(f),Ce(c),Ce(o),yr(e,n)}),yr(e,n)},a=e=>{var n=vr();Nr(Qt(n),t,`replacewithtext`,{},e=>{var n=Eh(),r=Qt(n),i=N(r),a=N(i);Nr(N(a),t,`replacetitle`,{},e=>{var t=_r();vn(()=>Sr(t,s()?.title||``)),yr(e,t)}),Ce(a),Ce(i),Ce(r);var o=$t(r,2),c=N(o),l=N(c),u=N(l),d=N(u);Nr(N(d),t,`replacesubtitle`,{},e=>{var t=_r();vn(()=>Sr(t,s()?.subtitle||``)),yr(e,t)}),Ce(d),Ce(u),Ce(l),Ce(c),Ce(o),yr(e,n)}),yr(e,n)},o=e=>{var n=vr();Nr(Qt(n),t,`replacewithtext`,{},e=>{var n=Dh(),r=N(n),i=N(r);Nr(N(i),t,`replacetitle`,{},e=>{var t=_r();vn(()=>Sr(t,s()?.title||``)),yr(e,t)}),Ce(i),Ce(r),Ce(n),yr(e,n)}),yr(e,n)};Mr(r,e=>{s()?.title&&s()?.subtitle&&s()?.text?e(i):s()?.title&&s()?.subtitle?e(a,1):s()?.title&&e(o,2)}),Ce(n),yr(e,n)},C=e=>{yr(e,kh())},w=e=>{yr(e,Ah())};return Mr(x,e=>{i()||r()&&!I(l)&&(s()?.title||s()?.subtitle||s()?.text)?e(S):r()&&!I(l)&&(!s()||!s().title&&!s().subtitle&&!s().text)?e(C,1):r()||e(w,2)}),Ce(v),yr(e,v),Fe(_)}customElements.define(`hb-player-live`,Hr(Nh,{id:{},mediauri:{},forcecover:{},media_type:{},no_controls:{},replacewithtext:{}},[`replacewithtext`,`replacetitle`,`replacesubtitle`,`replacetext`],[],{mode:`open`})),e.Component=Nh})(this[`player-live`]=this[`player-live`]||{});
65
+ //# sourceMappingURL=main.iife.js.map